answer
stringlengths 17
10.2M
|
|---|
package de.matthiasmann.twlthemeeditor.datamodel;
import de.matthiasmann.twl.model.Property;
import de.matthiasmann.twl.model.TreeTableNode;
import de.matthiasmann.twl.utils.ParameterStringParser;
import de.matthiasmann.twlthemeeditor.TestEnv;
import de.matthiasmann.twlthemeeditor.VirtualFile;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CloneNodeOperation;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateChildOperation;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateNewSimple;
import de.matthiasmann.twlthemeeditor.properties.AttributeProperty;
import de.matthiasmann.twlthemeeditor.properties.BooleanProperty;
import de.matthiasmann.twlthemeeditor.properties.ColorProperty;
import de.matthiasmann.twlthemeeditor.properties.HasProperties;
import de.matthiasmann.twlthemeeditor.properties.IntegerProperty;
import de.matthiasmann.twlthemeeditor.properties.NameProperty;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
/**
*
* @author Matthias Mann
*/
public class FontDef extends ThemeTreeNode implements HasProperties {
protected final ArrayList<VirtualFile> virtualFontFiles;
protected final NameProperty nameProperty;
protected final Property<String> fileNameProperty;
protected final BooleanProperty defaultProperty;
@SuppressWarnings("LeakingThisInConstructor")
public FontDef(ThemeFile themeFile, TreeTableNode parent, Element element) throws IOException {
super(themeFile, parent, element);
this.virtualFontFiles = new ArrayList<VirtualFile>();
nameProperty = new NameProperty(new AttributeProperty(element, "name"), getThemeTreeModel(), Kind.FONT, true) {
@Override
public void validateName(String name) throws IllegalArgumentException {
if(name == null || name.length() == 0) {
throw new IllegalArgumentException("Empty name not allowed");
}
}
};
addProperty(nameProperty);
fileNameProperty = new AttributeProperty(element, "filename", "Font file name", true);
fileNameProperty.addValueChangedCallback(new Runnable() {
public void run() {
try {
registerFontFiles();
} catch(IOException ignore) {
}
}
});
addProperty(fileNameProperty);
defaultProperty = new BooleanProperty(new AttributeProperty(element, "default", "Default font", true), false);
addProperty(defaultProperty);
addCommonFontDefProperties(this, element);
registerFontFiles();
}
@Override
public String getDisplayName() {
String name = getName();
if(name != null) {
if(defaultProperty.getValue()) {
return name + " *";
} else {
return name;
}
}
return super.getDisplayName();
}
@Override
public String getName() {
return nameProperty.getPropertyValue();
}
@Override
protected String getIcon() {
return "fontdef";
}
public Kind getKind() {
return Kind.FONT;
}
public URL getFontFileURL() throws MalformedURLException {
String value = fileNameProperty.getPropertyValue();
return (value != null) ? themeFile.getURL(value) : null;
}
public void addChildren() throws IOException {
addChildren(themeFile, element, new DomWrapperImpl());
}
@SuppressWarnings("unchecked")
public void addToXPP(DomXPPParser xpp) {
Utils.addToXPP(xpp, element.getName(), this, element.getAttributes());
}
@Override
public boolean canPasteElement(Element element) {
return canPasteFontDefElement(element);
}
public static boolean canPasteFontDefElement(Element element) {
return "fontParam".equals(element.getName());
}
@Override
public List<ThemeTreeOperation> getOperations() {
List<ThemeTreeOperation> operations = super.getOperations();
operations.add(new CloneNodeOperation(element, this) {
@Override
protected void adjustClonedElement(Element clonedElement) {
super.adjustClonedElement(clonedElement);
clonedElement.removeAttribute("default");
}
});
return operations;
}
@Override
public List<CreateChildOperation> getCreateChildOperations() {
List<CreateChildOperation> operations = super.getCreateChildOperations();
addFontParamOperations(operations, this, element);
return operations;
}
private void registerFontFiles() throws IOException {
registerFontFiles(getThemeFile().getEnv(), virtualFontFiles, getFontFileURL());
}
static void addCommonFontDefProperties(ThemeTreeNode node, Element element) {
node.addProperty(new ColorProperty(new AttributeProperty(element, "color", "Font color", true)));
node.addProperty(new IntegerProperty(new AttributeProperty(element, "offsetX", "Offset X", true), -100, 100));
node.addProperty(new IntegerProperty(new AttributeProperty(element, "offsetY", "Offset Y", true), -100, 100));
node.addProperty(new BooleanProperty(new AttributeProperty(element, "linethrough", "line through / striked", true), false));
node.addProperty(new BooleanProperty(new AttributeProperty(element, "underline", "Underlined", true), false));
node.addProperty(new IntegerProperty(new AttributeProperty(element, "underlineOffset", "Underline offset", true), -100, 100));
}
static void addFontParamOperations(List<CreateChildOperation> operations, ThemeTreeNode parent, Element element) {
operations.add(new CreateNewSimple(parent, element, "fontParam", "if", "hover"));
}
static void registerFontFiles(TestEnv env, ArrayList<VirtualFile> virtualFontFiles, URL fontFileURL) throws IOException {
env.unregisterFiles(virtualFontFiles);
virtualFontFiles.clear();
if(fontFileURL != null) {
virtualFontFiles.add(env.registerFile(fontFileURL));
InputStream is = fontFileURL.openStream();
try {
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(1);
if(bis.read() != 'i') {
bis.reset();
Document fontFileDOM = Utils.loadDocument(bis);
Element pages = fontFileDOM.getRootElement().getChild("pages");
if(pages != null) {
for(Object obj : pages.getChildren("page")) {
Element page = (Element)obj;
String file = page.getAttributeValue("file");
if(file != null) {
virtualFontFiles.add(env.registerFile(new URL(fontFileURL, file)));
}
}
}
} else {
bis.reset();
InputStreamReader isr = new InputStreamReader(bis);
BufferedReader br = new BufferedReader(isr);
String line;
while((line=br.readLine()) != null) {
if(line.startsWith("page ")) {
ParameterStringParser psp = new ParameterStringParser(line, ' ', '=');
while(psp.next()) {
if("file".equals(psp.getKey())) {
virtualFontFiles.add(env.registerFile(new URL(fontFileURL, psp.getValue())));
}
}
}
if(line.startsWith("char")) {
break;
}
}
}
} finally {
is.close();
}
}
}
static class DomWrapperImpl implements DomWrapper {
public TreeTableNode wrap(ThemeFile themeFile, ThemeTreeNode parent, Element element) throws IOException {
if("fontParam".equals(element.getName())) {
return new FontParam(themeFile, parent, element);
}
return null;
}
}
}
|
package javaslang;
import javaslang.collection.*;
import javaslang.control.Either;
import javaslang.control.Match;
import javaslang.control.Option;
import javaslang.control.Try;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Conversion methods, shared by {@link javaslang.algebra.Monad} and {@link javaslang.Value}.
*
* @param <T> Component type.
* @author Daniel Dietrich
* @since 2.0.0
*/
public interface Convertible<T> {
/**
* Provides syntactic sugar for {@link javaslang.control.Match.MatchMonad.Of}.
* <p>
* We write
*
* <pre><code>
* value.match()
* .when(...).then(...)
* .get();
* </code></pre>
*
* instead of
*
* <pre><code>
* Match.of(value)
* .when(...).then(...)
* .get();
* </code></pre>
*
* @return a new type-safe match builder.
*/
Match.MatchMonad.Of<? extends Convertible<T>> match();
/**
* Converts this value to a {@link Array}.
*
* @return A new {@link Array}.
*/
Array<T> toArray();
/**
* Converts this value to a {@link CharSeq}.
*
* @return A new {@link CharSeq}.
*/
CharSeq toCharSeq();
/**
* Converts this value to an untyped Java array.
*
* @return A new Java array.
*/
default Object[] toJavaArray() {
return toJavaList().toArray();
}
/**
* Converts this value to a typed Java array.
*
* @param componentType Component type of the array
* @return A new Java array.
* @throws NullPointerException if componentType is null
*/
T[] toJavaArray(Class<T> componentType);
/**
* Converts this value to an {@link java.util.List}.
*
* @return A new {@link java.util.ArrayList}.
*/
java.util.List<T> toJavaList();
/**
* Converts this value to a {@link java.util.Map}.
*
* @param f A function that maps an element to a key/value pair represented by Tuple2
* @param <K> The key type
* @param <V> The value type
* @return A new {@link java.util.HashMap}.
*/
<K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f);
/**
* Converts this value to an {@link java.util.Optional}.
*
* @return A new {@link java.util.Optional}.
*/
java.util.Optional<T> toJavaOptional();
/**
* Converts this value to a {@link java.util.Set}.
*
* @return A new {@link java.util.HashSet}.
*/
java.util.Set<T> toJavaSet();
/**
* Converts this value to a {@link java.util.stream.Stream}.
*
* @return A new {@link java.util.stream.Stream}.
*/
java.util.stream.Stream<T> toJavaStream();
/**
* Converts this value to a {@link Lazy}.
*
* @return A new {@link Lazy}.
*/
Lazy<T> toLazy();
/**
* Converts this value to a {@link Either}.
*
* @param <R> right type
* @param right A supplier of a right value
* @return A new {@link Either.Right} containing the result of {@code right} if this is empty, otherwise
* a new {@link Either.Left} containing this value.
* @throws NullPointerException if {@code right} is null
*/
<R> Either<T, R> toLeft(Supplier<? extends R> right);
/**
* Converts this value to a {@link Either}.
*
* @param <R> right type
* @param right An instance of a right value
* @return A new {@link Either.Right} containing the value of {@code right} if this is empty, otherwise
* a new {@link Either.Left} containing this value.
* @throws NullPointerException if {@code right} is null
*/
<R> Either<T, R> toLeft(R right);
/**
* Converts this value to a {@link List}.
*
* @return A new {@link List}.
*/
List<T> toList();
/**
* Converts this value to a {@link Map}.
*
* @param mapper A function that maps an element to a key/value pair represented by Tuple2
* @param <K> The key type
* @param <V> The value type
* @return A new {@link HashMap}.
*/
<K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> mapper);
/**
* Converts this value to an {@link Option}.
*
* @return A new {@link Option}.
*/
Option<T> toOption();
/**
* Converts this value to a {@link Queue}.
*
* @return A new {@link Queue}.
*/
Queue<T> toQueue();
/**
* Converts this value to a {@link Either}.
*
* @param <L> left type
* @param left A supplier of a left value
* @return A new {@link Either.Left} containing the result of {@code left} if this is empty, otherwise
* a new {@link Either.Right} containing this value.
* @throws NullPointerException if {@code left} is null
*/
<L> Either<L, T> toRight(Supplier<? extends L> left);
/**
* Converts this value to a {@link Either}.
*
* @param <L> left type
* @param left An instance of a left value
* @return A new {@link Either.Left} containing the value of {@code left} if this is empty, otherwise
* a new {@link Either.Right} containing this value.
* @throws NullPointerException if {@code left} is null
*/
<L> Either<L, T> toRight(L left);
/**
* Converts this value to a {@link Set}.
*
* @return A new {@link HashSet}.
*/
Set<T> toSet();
/**
* Converts this value to a {@link Stack}.
*
* @return A new {@link List}, which is a {@link Stack}.
*/
Stack<T> toStack();
/**
* Converts this value to a {@link Stream}.
*
* @return A new {@link Stream}.
*/
Stream<T> toStream();
/**
* Converts this value to a {@link Try}.
* <p>
* If this value is undefined, i.e. empty, then a new {@code Failure(NoSuchElementException)} is returned,
* otherwise a new {@code Success(value)} is returned.
*
* @return A new {@link Try}.
*/
Try<T> toTry();
/**
* Converts this value to a {@link Try}.
* <p>
* If this value is undefined, i.e. empty, then a new {@code Failure(ifEmpty.get())} is returned,
* otherwise a new {@code Success(value)} is returned.
*
* @param ifEmpty an exception supplier
* @return A new {@link Try}.
*/
Try<T> toTry(Supplier<? extends Throwable> ifEmpty);
/**
* Converts this value to a {@link Tree}.
*
* @return A new {@link Tree}.
*/
Tree<T> toTree();
/**
* Converts this value to a {@link Vector}.
*
* @return A new {@link Vector}.
*/
Vector<T> toVector();
}
|
package de.sebhn.algorithm.excercise1;
import java.util.concurrent.TimeUnit;
/**
* Excercise 2 <br>
* Use -Xss258m to avoid stackOverflowError
*
* @author manuel
*
*/
public class StringManipulation {
private static String STRING_1024_LENGTH =
"ZE6lS55KaYu4w6sewoLSNB658fZZWYm49AVksTxccx3t64WBbAB6GmGpwBVMwNBjOjne5cfAzPxvUHvtRE2ARY224T3InSHTDngiqN72DLKXIgO6kmpAX6a8JmLSmJMLaaIVj5JH3WEONpwqOtkiagDalr6j2fw5ey7yMW1rLgIOlpsv4LWviujjA5iW2T4lTj1wUQ2bq46AMPRgOUZNEFyxt76tIsIIKELtlAKuTrJLTk97kOhQKrUrTEF8Q7vx4ypGA9xJxQ37OCxs88Q5Q1MXvrr3iZLUzhKmavs6uihfmIpoz2VX4Z0XmEEsQEyAkM0ybyQij57l11OH3pVtYWj4D90RZVZu4NjwUF6VMxUqxy8sZzZrBmba0WegpEzTb87Heez5vn6jJhuv9jmezgXlyfwrq2hwjwP4yH4NC1ueEgiIzrlCEYw9xus2F2rvryt93ojBVl2hWKF7gxAqwUKOxhcVSkb9AmtiQKgvgGNuzfWNuVR1TQ0sZQyHOaHWuD14PYTvWWL58e2ZscSZ3ESO3cW9MsAHRFnaOkEF3Wh8h9KxLo9l3E9kXxvjL1UEE7vNcbU05lcJHB84gpO5BM3J2vUeMDFHVQ3cqj0bAcXEwKNFmgJb0ro2xIfaGqfvbOUKHUx37xbq85gKAJU03LmcwHPRgkatG1sa37IupGv9iB8VTstgR9HAKs3ayOveS1vr4kri9gI65UwEzA5zV5goPsJUCAh4GYRr7Sp29eHFJPZpErOEQJ7ZFVEgu2JkuLcZwJUvk2hJ7kPSWfy4FethN6lXs3EzUVSGfqMzfuN3FyTsaKMVOcJ9Ym1DQbhQSmNFn2KnzXMM0gbOI0pNMaYrX1EgQmNpBlaz9ikBG1S649lbMyoz2wkrELIqz0Mi0l7arA8ZggV3N4yWZpx0Ml3kTHSAiaq5obZklhMSoL4hNgN5Z26hku1PLvCsaleHIASHXQ4nL4snivVYyx9nWYG7vNtexOCLncRU4p5foUWUO1Snjs1y6gKkAgr7KFQa";
private static String STRING_2048_LENGTH =
"5VIWrLwsz2sbYMA4JiG4GlsjYkRGvHjzMcBKEmZfEFsfG6pf4JG8fqnxVAWnAWHENEnfWSPzsTUYCI2gBQjYYz6ZA0U8mCmtcizQ3BJlVfBlsCnH2BLv34J3IJbW2fBn5vDQT4I8qXP62YX288RJoc7hQpUAJQzaN909ODg0S9SwhY6aQOUkNuZkGCusRjoUFl7IjwDl6Yy87ntvP6V6VKhQlBGcJ07m4B8VJ4Z7WD8onlDV99juIE1sysruiDv89i13FJiLEi2Qj4FouJGu8OEKhYzHNlsioz19TQlsX5tXWCAz4jWD0XP3V2fkFR9khJN1lkAaasL1otGXv6uaSf9WbbA5COoE07G1bV3zb3vR6BCqUNfSrNoGmerJgeLrS6fGrocBUDIvfOoCj8zcO6Snc9f5IqWKftPgsFkXmVVWXyScVVgYb4TrAYhXLoVuXpcEhqmoUvfJoOurzgvTNMraSgjUEnePfMibgV99hlYnHPkpqNK3KNlRJ6N76BhwxTPyXy4HQTJ5JNbZ8AoXV3vp81iAuPjcVZxkX0AxX7eQoBy5CvUp3X6J0ji0IatlhKuWJiLKnMlyitgS7HfBurZLkLe11BJqDwMw4VCTaRLwiS6NjyvTYhyo72QHqmtmPpB5pruTNbojb4CF47ZWIamgxXS172BRGheKcEpbjIRPAXpm2EDA53PBcz21VNsIjKY3lTvC5uVKl8TOVbhLTo9clITHssQmphNNnrzM5XijiCxrBOS6Lz0eiKVCnSzUN4jGS6kJK5MwiXSF9NrTKZvEjzzb4u5lYIbzopS1iOh1wrEXbiVTm3rl0LPJmbgxjjek7NxNPUCarJKlfDIKWhWNggssPwewHgZpSYpewuNs9MIexJegMejFIWQsNGLkxAUxUqr6xNb6iy3MOJassQRqo9rPpJ4z0z4JiXb4gyw59vY4r55bHDj2kpSHUqYELvBHAZ24F10LX0kkVZT4rk4pPkKtVcHxN0vv4y1frKRYmJv2ofZfLKQDGroHieK6eEYXxyjSCPJV0Fko6Voxz17f7yM0nKbAol2LslnL2uqXEY5zIlKwAsmsRTxOa2UB24cperBXyistwE8BHVW8YlrkeYr3xPooBimHgqVS8n68lOW9WwUNDYTQ8QTv30eQZXH3rUcDuryn0ycTX1GGZy21HbjlYOsiGqGgPo0ezcyPytZ2apYbwgOWj1NAJ0rsNPvBNUUFW4gQJ3c3Lh4A74cHtkUHTDN1nXRyBRc8h8HwKrfN67nfw1RQUjYBAyjAqgWwloHcj9bAD36VQ5WjEFQltN08FY3X8mEq4mhBb3t1iAQWePIEJpzCHbmDrwvPkvOBOTvCVMuvD7rRaSr2nzhYziYgU7bmyejkW6lxixaxPheJzvM0yU4tr4jVXqL9EzsP4UmbWGmRiTRmZw7SSqlxNfx3AlYbfHstvskqLwTOzgXRLtzafMjtq8eue49YNvaa3LZVeIuRTNl6eU94fhoFCuaDKRjrR9gaoPq5WJ22fu51aHH0T2CrtPfODz4sY3Vwls3x4qfwEaTjMAasYyPU38OqOyAvEPHRaLYix7AFIJPJEK3igv6U5m2L97lQ64zsGekzN9sNPjxeWws24XiTEEUpXrcrVBv4OjFe4P5tEmNg1bCnAG8XwlWH18gbh8wo9C37YHoT7rDYTuKFLaGYmENsQToSYlcp9YOXptKH50D9bW8XOCKPgsQiKjPk45G8VbOOjpyqKO5U8wrAesogFigTW7BnymcEbTP69TZVNT0MjNcB9AoVIca8Mvk0UZorVB8nesRzkcmTeNHsxQUNeZZoVxjxsyRapfGjHlFBJYvrB69bYcojSCRQ0WDou0L1H8BUiVA2X8eVCzAXlhkVq16QhImwUkjjhHN05nxqKkjlRMWWqUgQZHwFOQUfpwVH3At5IoLBz8VRzxSbQ5MCoEz8jPSj0gDUG0zlqfjVq9xySmhBsvVu587Tma9UryXDg5YUHENYXDwXBBSePxvAkZtvVjiyUVpY9RT6xtXyMn8BCEZ5lB6mIej5wKx7";
private static String STRING_4096_LENGTH =
"YGk0KJKAIVQfFMRRfZMO7MfETa7YxNkGKsAPs6TvuPGrfkfVQ8EqRTBTnF1CKNFVpSRvFo0zf6OCqjkhigPt2EwzpRqVOV5pC5M4tUcyhKG59vZUYgTxz9e1VMo80NuohxNnrcTwLjpmU6aqU5Het0CwtvfIiGFN5a0SXtSq9boHxUWc8us8BNh6LFIRgcrXJJXtaYHPeCOK0HFDT2oJxuR5HTnHYmPI6C9bobMH40NZbvc8ex0QMT2imFR8WeV2BrbtHIQcn5K6fv5X6p0EkAi958eWn74KaFxmppEfPJZJSFR7R4o98b0KHZi9hmJhyfAlRPxIB4faO93DCZI0lgGRMJSi4XSSJ1mgbSg10Pn2hxqNbKbHZIc65rEAxEpA3ZFOGtHs0nLD35HObq6HX8tmqowyiPCvAxiflK5kHXnb5UzwUD3IXANILQWH3bc6WoLSoUrnUSXZeZKcgHRkcwv6TOocVWhCPJbrADpXcnq0tUIGI0itxyZE4m1ghFgzJpDkT3VusioHZhok3BTnII0oBGsWrFHj5jYFVs78Dnqjmoaf4sECxzRzamL0i0EHtkjkCXQb1LWZUgzMxomj7ybFJ779Qg7fvvLLMXactpE5G3kJmlrP9fDAQZy4z1eF6VyNTrYLr3KwHuvlWSx54qOQWsXmlWNW95a4BQ05shUQREM90B4kBaxcU4gOh1By1w9X8ATwEWk9Wi3KAwCpBTxgFJHAM00eoHDjkejCz4BnFsPFwNxgQ706I8HOycs9fhXzqNQm3SDJRft1L4POT2JBf4ZMmbCzaWZUbtFHvTtAys4FTIVVT9vtr3DTrOWL0NAYqKyE4PUrN5CDDOuTx4li7vgrelC5EPxeL1VBPkCHND0RyobjU3gFBuRrZHse1hwtS20ubgSh5ykv65DFEqFDRisbUq6UTW6bhZPzPbqzyqCm7IbQeWz9JhcbDiqtV1VtvDMGhUDJa2RHUGUthOOvbzWY36VpfRN9VK6SfqgI57Jip6ZyxcDfNWZQIYGDlX7BIFyVsjcjQpxkZt54RR8cmNsBszrTtMB7yrzD2liQPV8VxbsB74GqbzLEAfKPu5bXXYE4McOLr8LHb5cCUoqqe2W4QAB7e0zFSJak6amL1WxiUU4sWmQxHB6waG2XrGWoDwzOUCKYBjbRq1iHomshNKYSasrDWB8QokZl3kLwEWvtxUEFE6MIwa2GNIVhXnluZaFLbMu8xRh7JZ6gMHhb5B0KrZzFUeEYDT0brDeaAxfGT1CgEZab6in4fuotPjnPzymAUQwta91eIfkZnPPxEQZQs8ZKp0j26hkuObJuBFfi1nbHYwOyiIFlSB3sv0UNcAoZi9ObBpATZCsnxuNuPJ5hxVX08Tpj85rWvwhbW9lT5BlHqqF61xgQXiW1x3xSMJKDb8SGeQw6cnPyC3LBu2UVP41QTpqQGb9zNyU3Yrg6yQWqfTigYvfyiMUMBAoOP1oDOlAJE2jJATW993aU53xeS8r0KQoJDH1FQwojheGQDhGl7ThDouiEylCkya0ygBuS3EMAycbevYl5JTA1yD7A6urbn8egh7rvh6gAD3DMT9sReSjWbr6Qocqm9oYfmfBRxzL5n1WqHvgSKOQhTXPoZGZOSom0vNnhWlFNmxLNMHqcrhwDUqXUyhyQC5F2kgQPqW4ql69ihv8wlF0CV8AfbZe3kS4nNHDB5zeDjbNb6A1tGZwrSxbveKSusZKsw9SoY8aIlbrJ6R6vNjR5jyH4g841BaGtJeiBRrKeEVXJb6rUWXIyTVzUL2lUH7Vn8F41ao9BOSQyVSX89YQnEIwxxko8tmRL0lXgmtGlqiw9IG5K9Prr11kkXScvLQ77WppSXqIm2Y1Vc2APb9f44YQlBoIrM7004Zi2RaNGNwgjkxsG8mAX3fnjD8z0z5FqUOpCMLSNN1grQD4RAouNAm4ASCquXnFvNpktAhR0x38T0WYDyAsQoicVXENAQJO2TafFqB20MGGRarZBiqVNHTsw9bbhJ9qwYGQOkq9QPKqXtkyOjyO4KpNH1oyzCG9qr6vtu9i4sZTQ7RgTJR2Z3Vus4awK6gjXiLp8BYVVZ6Vrjm4a3rDasmlgYSYATSGp3KfXWRlaq18IvYsUlGoUuHGX8T2RIRPihI6JJXXiVangWop0T40GkuC1PUwey8Hp7ebDQCiUmLZlYIHnF3teugZ75fzEyLyRzZ9E3H4A2Kqlfw6KCNmXH53i63yzWJDp8gbCH2IgYxzMP15KyUbtTZ01VO6G7us0y0HFKpSPnM9EpewGl2zC1IFZZEXfiYauMHCZKkPpaxJ64zlMVvouAYYXPevngzo5UipAwpcVlE1MFe4Hg5s63sr8gMmiggylgcgHL0yX7yXbGv1qT0rlhS4Yf5otW9E1KM2w7CXbnnYVCS29AZUCg5hWpK8UR2PGqtrCvD7URi13ewhnFDn2muWu6zxxCsTjDhA7mlmn5GaQlh0OVoaqQGvwRSWVNFYWrtFVqju08oRWN84LIqLbYgkJ1OToVqmjkl3IShl5SKAPvtovNRKnCP6DUf5iP9WF27AAKBT3Wuw8y5yshLvizcm66xXF2CYGIaAUwmbMx31MrYsqu2AmvzwWweY1FRJjDVwsCMyR4q8POs5hDj5hUFf17cUlYk9czRwxePfghhQmAj4Mnu3Z2sqQLR44gVbeB0lbmTptQurz6QHfvTJeuHu3N3JTrYQWUw5WhveNYcGqAhCVKIe2nbNk0oqAHXtPQAz9eB6Fq8LZDsZL0m71i7pkfsS9rRD7XFym7cRGMmo58uFj4bqnf3sxgCPGxPLP3rcUY2mpwk4yVPUpMDYpBcoi6pqlWGApZvGTL8R2wpp5PLPleQn24hxVjpcwVcnHiVZBirTzQV9pM2kMGcsAWJvuxgxOHZ9vH82rCht4nXL6Tzi5ksn7NQaA1y2W8BqJzQcOnImpeTbWQJalaMb2CBmStTtwpj43PUUILS2U1lcZB4KCpWpe4IoWkn0zzYZIQs2g3PG7K5SDZMBa4oEWgIEe5qnWwiNZ35laGVDvMZbGT4GDwywYvvRarSobhih8POhW6QXuuvzDssiwTIq6bKxIne8MWHsgDkiLYEHGxYaQFelnGkuAYG5KFg0kY8bPP9iC17r7VCFo9mwqnCsBONSzc409BmunAzQ1lIx491e8rMo1sGyz51NnXIscWa18sYfyP73JoH2qf4NgytLJAKywyKtpwavjITwMNQoOEtJZ6HBkt4pIDEOLPQB5bYQ6IkSnBC5OZ2FiB9f0gECwiV0pbg6sgZMJ8WMTPDaDF6x39EnvzDuIoGoySL0T1bo7k6jMLNIeeRKHFXuX2nP6saVq3qRFhg9te96DkRP7DSpqRvy3XKA2c7TIGjNV8a7N0aSNaBjSzITI608VUVrYK5C6fIODDtmRQ0kfwVz3Q8Sjhq9L9tPhEVfe0zBmVbTq43HW0CWZMVlebjuxOxg9ijlmIiFHtk2kw2H5jLBEspa09QBKtxBYeXzc0XGKKF5b17xO7vV4jvNwMg4U7XFnNGzElZIa4b0wEkwQgjWW9eAnG7EUfUrqz4rrYjuHIOpC0rZGjNfBgzkTazwRm0DAoS8F3yvNP8oqfuF2r5eNX0hNzSkR2eCSxcH9kB9TEhlaU9JfGckLWx8p64OlfgSw0vIwpwp627cJ3JJoF6a2cNyFgF2kiMY6hhkXwKElCnKwSxV0O5U7GOoHXtD02bMINvlJxlLPRMlXZTAF4pgNhNlQSEc5wq4OxhUGopzODXa7Hi54KDBjhHFBaV5JLMskM82H54H4Ie56KIYlkk4n46M7B2DvjAGDc0l7xvhXonLi0son0UqzfpuXD0W9N537s1l4ex21CtBFAzTv5bnVCL3h9OTgAJ4X4yCwiyVXRS9L3YeDFrCtO6xl61ftqWMRug9pz8rNg9BsNwieEYn7jUN2H2Kj2uTAHFGTA2Sv1Ty2eHBGSRG0FN8bXBAaPPVbtqEUKovuuiRu169SfFW3kfNwVAgMypFvGbnhUHuagf7LaMIEXcR3uzS5GfkHJSilGqcRT22B46zinDPzHsUCkNECDwPzbZiY437pkx7g";
private static String STRING_8192_LENGTH =
"zfLHsQ1H1FYIMsH0oWlbGe22NW5ITQmvrR8JMkg00e1uRWomBcejL3fgUrYbSrkG3CBf7Rp5c5FEnjO2qRoQYuXEkzPeNmbrhHxvGJRZo7MBzGWLlAiDuK8n7yXcYxVVxbnmKVcGLia4NDea8JKv7IokgPWFDbxwJgPOyMQyS1nrMIpxeNEmjCqIjPDatn8gt3TkyXxe0CFcqopwKuIMhkohZZMI9ycTUcDRlFYc4F2P61gg4CrcvNjptQMkxgRaUv4UsbqNU2uuq8oZRlKPMxfDSH9Fy4Oh5En1xQZwBrk39w7qhW8NyLozxzHeCz9Ot3Ia9cJw7rjYKshqFyL0Couo5cKrvj3caPxz3LY3NCUuwLB80wAXwWSYVYPHFHXqGKvplityYOhi7e9C5ADVGvvK6sKSIcOoNHNxsOrqFqX77A6eDcB83G0ROtY4ps1RiOjWQnLSMknb2Zxogp1CiOW0hlvoMVCzyfYJ4iak9Ma1mVfX7zcMX4EpVNUSM0cotvzCESERtahOajRCociSSvP30cPkR9K1Fbybz0sbx62qSMI1Es3h1qJ1IJ7bMbW06pT8GmNx1LDZorTEwrfYqEFyLBMueekEhDlVuIxfqE5CnCjGMXjNDXW75OAgxLPIa30K9R4gc1PfaMSQeDVgkbGTIi2bV0bQRo8EB5sQ0PAVJyP5oNUFFj9ZLQjXra5A6Ls9CfHuKCHlqDJoH5N5V2mk0bfuV8SB9baHvHp2Bwo62xKIjFclIEOeBOAwNjvTUOwFhsNwTCCYn2BPjlOFv4Pf4GkEfhpceUU2ReWgVRyuKBEESxozrsTHvq993XeIbQT4rBrn9pyHczxPuEgmHGMTlXCrj7l5HvVUAo9fKeExievXUnQSVY2As8ffC3KttD7z8Z5VXyTg22DHjUKp1qzRk0k2IUQw8B7GtJ2YZs7hEuIpxXZfCbG3RWAwT9a0ojO9DONNnoLxTrGXKKqreppjTSbXJCrUwHkzfKeNRE9iPyeQfGGmKPEAHeseJmXnng5woGsufizXnyO92uY6cAepzhRo9WE1l1IwaW37P0mSwuBPT8WHNVWTyn7lFGm50RxsPuHMR4VOUhaJvzAHkuQoE3ENDihRMH2mvsP2NRtJeyBYinbrnXtCYonGpTcNXcuPHI82LrxxrfyeghBQQVjBVJHq1FLgVYm0Gh7HMyRoSnlsQk4pCScXgfsnOGRiWlBA6RsycSWnbAHWoPq1hrhVZmS3iEymibZHP4FjqCtF9psoMb2tnOvmNGo06LQ8PkKxvlHT0jS41NXmJ8RuJjhl2gOUy21WqoBS8FRaQmQaOzGoLItS7sqkwPkJSvznY30YuRmcLaPHvOtF1y1hw6mM4WJw6q82jepMyzT72f2hETgjt8vbwkUU61MV8mB9VAQwxfNb5VTjNFmpyGucQjKShJDLWxGXgum8lsk3EWvVovBxs1nfJKAtHQsmnxKJUYzlTIaEM9xzTeaJT5ya5ZhaNpIBZB675ysXh0VhyUi41kF3kkZkwwMVMfDabibiPHhz82i1EtDXpF5vUmUV7ts1CYW1MZZbap6NpuQlxpmt9oKZgnLAqesM7jh9rK90f5HRyMtfqg87LAlT0ZM4O9YBgueolMHGGCAeMczyb1nnXNc3B9K7HCblhaRNVSKLlFGEAUESZBQ8ogXCypPhRRs5YgAEewVHvyoDTfQcZazhP8CeL85fFD5FgeglqYYDS6DRZ1kp4w9WMyLG5K6qmfv0SRVZFiw69u8aJuSNcbrCbYjIAPfCBR1SD7fBc3Ao9EToT5y2KpYTcfbCiu0l7BkntrMsBqruTvb55zEBxN4xcsm2OPxmyaz36v5ALjfiGAyXIKU0ltA9Yqkl7A8S131Jksfprs2tP2gN0e9BnzymMxjaC2USxPoZNvNWAsCBg0Gqghk8bybTlc1JKo08QDaCGzQepocqoW7TPjNbkbRp7Imrozv4RkknIcmwuTBRAI5FDBtqrRrrzyTMFh0mn8fT8lR2Cbes46QoG6qPtXZDnDeUNF5cgtovqjSU5jFx7lHX6Jw79M14Og6T8foDDuQYOwN2a1kfmlCrT3toOmFBoKJNsWk0UJDqIvjvhy4vFMHIDgsLBrJSNo9LEBjV6DCq4j7gtuNj5JJPCZKWKwXDbTFPxBHwxiX3Y9fjahVTT3gI6rnYcG9lA5JEeb9GaqYJbHHJgCSV4nTZ4NJiLE4FkvZDPq3YVfjmjvuORkn9MUP1F0PqEtG3exEIpzQyPINWOZlow5WpHugqrc4LqflXJvWBYGXP7ZI8G6GAPBULRkjwEkfmfqlD5iKqVDA4psg3ov9srIxOljZfracxbz4RRliP6RkJyLaZyWLeHshZxziCLOUp5X8SHnxhc5XgZrcUPmypRQJLVOy2xjGTtFUFjcVv4m7skXngcx7hmBmNXBPb0IJeHh5rWH6iyFoBWJcapKMxHRu2E2RMe5nS8wnQOPVxALtqtD45oCReOoDE1Fy391e7W3yIYCHJ5XP201m54cIKm8Go4kfYEYXXaNNDQVyDcGSSINhuNgGn0l9iMrFNNm8yEXY6rCUa2yxhDK713svzen5rsNhWtJmjm5O80BgkxH2zhttvrtjMkay7nx2AbaXNW1cHXoqasB2GDUrVYqqGgOC3Gqwk2GiVLXl1pcETpkRfgG1IkyeEktHMuSKCJVq6NbPNHSBtPpQLSO4SCMDIQcplhxaxnIqN4oDPuFrfB48Z3aIz2NvjjS7NbH2h65TQxgKhH7HiWCrVfkC7kzCZ4zMBsnPDc0EOTPVWA6Jr5Ia3NryY8jfRMjGQuyQ5lNxa1mPUvKx56XXTeOKVnRF7OOjHWtrGb5QiM39nQgpnTCBilAMA6vkLk2Rj72MrwJP8WVznGyrb6F1S2QqC4MjUTuzECIVw2cLOyzG3BElofEcWky9RFY1290ylEywyCSjHGJa4rPj4mHCxWwQZGcN6qSsExCynaWb04obFF7aA9SoolmsputzmpFpRKWztMEQGSTIreveN5bLKzCQilbpnkuLjMcuFoA2AGs342rof7Yfc8Mabb4Wz0knTcc3s439QIh76k79QvASpyuu2xxW5kRj15074UMjosVJMImeWnaOFybf90MTsa62izjHWXq1aYI82OMNgfqoVKHOeyS0ODybj2PiRS7g6oQqKjIWDUoJgGVTGmTyrQASs7k2PzyVgApeyGqW5fkZ3ZlI4V7vQSSheJcrf92t0X8XqGKZQ4MrT9qgT01aOxbj9t3slbj26yysVCowRBYKsmh2l7pNGjhgsZar5ROZM8sUcPGuYW7uTfLPRWVccRaiY3QNnIxNI94ZU0I9YFx7WjLFmxokJ5xPeJUkVYmAp0uK4DY9oxrUJ3twkn5rwUqXLFYLVVRh6hSpUJXraMMf4ysm5PUPQPpf65FytjwWvlrssVHEiy5bcMcbA1v0avWG3rP0oQmypOqNKrjyny0WuEp4F8CghPLAMY3oVmnoazWeTMwck9V6Oww7Dt3npPtTtfsnsqWHgPJtQF5icLu3VDgaMkHvqkCUXcuMjWVqlgWkU5in5a0YeyM1qksHwvClKzw1QOXj24gXYZCWruQYs7yPCVH3DUJXMIt3CCSEmbqP5LWfkhWVslYkuyIQDPc34uupMp4WBUK69zRsH5DEIbUJB6szQzVfnWPZz8CNq9h5pYZZBJxi3DpEKpqAACHN4KbA2yAQ2UHloxJZ1qu1IqNQYxRYssQ5tYhp9WCCHO19LIJCaw75lBjLDI4Ec2hLDscOXMuGlcKbgwWIp2lu8uA5n0RhEZLfxP6nciJS8k2MhbEXa8GJu5eqc81ylLN3N5znJ0IwkWZPLrI87B3RTK5nvhCg7KKz7qPNC2PON31MAmnq9Ezixk2qhyqhEJRQgAciUYQhPxEy6lPOJF19tPVT51b0PnhRJQAWuRQEE7zBstoLyKcsY0Z9FXPV5eIHJ102RNIbZJcJ3SqlNJW4JzkCXMgcM6VSnGRkekJVJPgtAnI6EtWvVVPmwzn6oCNS781GWXLpwOAwhRyuVVsWvhaLvgAuQqiCsVJQpHfYbeQFkOps8vl9FsfhOaQNCmJsCnM6JcJqrHTEH53uKPRQABoG13RvaRQgO1rbNeUWfR4sFchIafv6tM4AwIVAqPgEyofLPtELQznMMez1bnIkKXnrK1AK4JhJfiuIp5vKPLMBjcVapQHFJbnopeGOWkjuX6klb9MNyr7zhCDA7eXx5J5NU1xw2l35qOBx67Oqxnhwoo8Z8HtlfJb7AKsZ7FINAeQbOb6ggShe94lTFGZn5w9ML7rponLTmfCks4V8F4QVe24jYcDcBl7z5UPLfoDJp7hNQqwystikeaBGpWC8kCmX4USOlT77kzMbgzWSbxbzW6t6REAEeR6gEE737YXYAoZiGlB9rU4QxKaJEI6kSpaZbnvluAMfzzxWnyyjatuYuQIWSz2ikk1J34OHhYGRJ4N4YZRvUyF8YALmjkfr6A3qyMsvmDpvys5fFGEQai8Z5DNtaLBo2VKIBD8g3ZQvZIoRhLTTLcWD6V3AaR3rK9rcLNZiLjF62pRn3njKl8ZpwEfmh8xBJQIJ2zuEx6I4JAU21EJnlZbXl6fvhaZK07LRstyK8gcYGCTRUsRDkKsAQNnnxZe7fjEuHJQs00MRDyJZ0I3K4HAEceYsNvRbYn0K8M0fZSpn36gaF19PnZ7o1DjMNIYR22T37OV6QB5HU2ZWbDcORsA4rNueTzF981pjOl33jY0sE7QZCU5e0rkvRqCRcU5uNlpJyQKSrqxQUjqOnl0ICYzT5TAFeFviXQD2TvBRjhSVukrIqYKTwAkLrnVXPxrHFgKxxqroc8RTo9hUCQaKHz2nFbBO7bxNWveTJgwYIpvChfZOyxaRi1XehBYmvEMMorekYkIDBnY3wih61YS3tjEeA7s3ohrvyfhuk4Bi8H7Rg4pEh5AzUI7xsvLktgmWSBkWGlLkhS9yBuFwjWF1NEfhvDReWyoJCwwk67fOMk5oi2CN5IP8nBawpYBmBDtch2S8jiKih7h6usA7I6our7avsKgFGYNnB19JmsWAnAOiuHE6SoEVKzMexhVb7P0FCKTIUj99E9R9Guvn19DEvyOGUIJHh5qtUXiBC2AVwjVlIeQHzCFsJE8vjKZ1fkHNFAbxGRYt4GbxAEDVYB4Tvz4bfXoQtyvyJWQWOlb4He0wqy6ZM8NYCNO7zpAamBVIDhpcu06LBYWWtLsJ0OvMQ6bEi9r40NGPMCeoWbUZJfJg9TgR39Cepc6UKM6RKGQGkPRmTk2LRH1CRGmarzYmocsePqDLfLJA6AS6rxETRvcX9bls0QGYq4QRqsb41lSGXCts7al7uZzFXQAGrnuMtb1kAiy2mNNJ7qQfHMIsVKXbreFIwIsSuwUhTCGOBzCLBmCFobJ993kABoRkFylKxgO6rianTzcCi6AKOLx8x9W72pPGcKB1WcbRlY2KpW0DzQaTavStmog9PCEfbl7sxWB5qtWaFKpfIS3IgD4f44uHHWflu0sZ6giUcozp6KqhEbSnwjQVmf7EC5JogbgsQGjUWelMUjYTI9pOP8wWNkryp7KXfleEDzV7eIIHH2ywDKzEnNGqa0r4tgAByxX4Zr682j4icqzLaafwKXliwH6rF16KqsztxCcPyFV01u6M3VqpretnbnTDokGHEP1isycisMiNOPyHTz42gzvQmbcrTVkqcZbTANsgAIQ0zoXqlhMji6ZOPcZ1OGsKkR9NhDl4q0WELXTlSa1qXvCl2015RzkG3WLkBiA53ieVClsxDsJFvCQtiN5g6HvBs87vSpo008yTMK3xgKyeDxu1UcfESDvnZcm2qusoaC39LpkxHCWb7raikUcXMZumvcRm29C9881jIqr8tAsxj1fgIgzcBINq31h74BjSNGhyyDfngnjcUhfQ46mkE3sHzxaaeg2Y0CigWMWk5UG49p5pEWMEBOmnzCTEH7F0xB2iAiBn5kZ13UfVqPK4cBHx7GlzrcGvLtaTpZVkReWaKMp9k49Lz17Hj8SsrTE1MJCaazFurYKPSDh0gNVNNHAHyDTfssGcXNrYvhIaefjwmCUkc2znuwJwH4QOohoak0PAgmbVTsmx0xIg1WUuC7P4jzWYgi6KRloEnf4TqeuDLi8EZiWUuMhWZYrfSGQj0ns36Z04TKFoXVYN2UrCQOzruFHeFANjk4yGh6hrUbErQN8G3n0UxIfuEeGetgJ4WmfpFROLey0qbCC4aNMXoOj7HED12538JojquIWAAQsy0YiEfYEmWRbS6TjxVKUpFGTyVweBWxoQIbDycN4T7AUnygqvvZyMOrqS9XA2j94BBCjkSrs66jHLXllUhriwbauhomthWej4sUX9lvAawcjIT9JourzgaIVpotFL5LRmaGLqWDSyDNHfbi5mSZfZMHt5PZ069zabu2DI9JvW3CC8ZM7S2M1D7z9LM1Sg5WGPQ9UxBUx2OiWzvoLC3MP2yi5AH8cYvuMBERlfX9kyGQyeQW11Fj0Q173RRT4OLGD6nSXuVz1woQfg39q9uol7YHp8RtqoS49s3vv0qKKfQC0MEAnRy5G0Se06wLqENhrqGFjazgjt9xT07xAjoaVL9AxUGDWWrcxQDyMqhB0MZiM5uxPhfjPeVp5Zc39MKZPaIa46Z3tFfSeuf1qc9G7QyBfYNfVOLNYXc16K6wg1zO5QgWiqvGx0WK4gms8W9A4iP4s5kb4PukD6RqjqQ5cwZQ8Jz10qEQ2AYkzCJz6YOz4j1jWCBSLpgHxtjIAgmNMG6NSPGNOpV7n8faKrxQB6sCoIvLiOr93a8Q2AT3ktn06r9Fb88K5GSQiURMhe1cWRWMJQpoISOrMZj7yoFUwG4n2QovLIacewwLICqrktth5wtfoIy8JxIEVl5MNxywrxTJpe6KtauPfASlWe351Vw72jR2qeOmPgh5lfi4vT9mmv7ZZjzoQpHFXWziIVr25cEnQzjILw41Qa7bY2P86wZnvxQzXA3BXm4FsUfIxFsLER1WhrwJgH9GDm7JiOmJ5ilBpq2WNi1gX3Nkbr3zzmDhx212PkW2KAaBbS1nJyBRMugTb2AmO0W0VfBv6vaJJFxYsfDT4OYIWkjoXt3gE8LKD9RneetkZ5tLZxCu4bFlEj4ZNqPcnwX6VxzzNUGhHowPkeSfV3TCSgIsXs9EYcEqJRg55ZPPZiw1klK5OZSkv91ZOJZoKZnanng1igLffoNTHATX7zbZau4oRBzPgrimSZc7EiNfEOGIR1DGHvJebgSNu2XAs7lLIpF7suJ7wmbi1cHXwsYzVVJWh32gp2MX8vrcpaQgqh8tMETlw6SVfekBXIuIBatqhyeDvm2JoAcGb4QKUJEwo51qbZTwGw5ZuOCLEjOcDwtAy2HYTzWZvkgk7TNOLa6Kya42QmLnLQfFEv6hTrKB5cjkwcmsZvHS3fFzszilamllgfFEx5X7YPGhNXnNXMmGLEC0wooNOc5nin28POrfuZb09oOKfoaSZe9IFeRFpb3u6DAF0E0jJVrwKS7hPukmyNBCvWJ0YLJqQSmQYhSrf9BoyocuK6TYhqCOwHmbOMam7IwFjgOlLKXVYcCR9suNlLqADjK4ZsQe3gYGVnDfXo6zxKZplwxwSFSBWKFBR6Br5cBuCuPHIDMZCP3OoXtAtu5u99zefnwtJcLj1SPrhWCCAtAew4GA4a36rRh6FJCYpzcoDEEvPoOnBpf9ltgUkYByIbZD4mLwmsjW5hEqVXW1VwYeZq8jNnTaxIqJ1avfsN0QFOe4ffqIF5bG04SVp28ziTOC9HQmeg5kcnFXLC5ahs4OBM5TTARnDI5vqaIfJcHw9zEfRhtOwtnsGhWbNc6kfzWk77stt50VYWNXRLfO4mePk0C9JHwM28QuZez58I1tpoHorf4B6Z6faQQ5iHqrGzo1wO3DUeHSe0OlFv1kcma5R5jmTpzCMP1hi3cKgBxEyiHIP1RwVI1xsgMShRFH6sjCLBj9opYiv4XZZt7NPWQfiXRytXx57bXkakU6KILCWUMqXrxkohWBlaEVnpPsR65LAp2QBTDCl89PnqiKiAwn5WnYJxXtHY6qpmqfZnBP5l6lZmGT9znTsj6SEtwTviy4bo0rwgUU85Sq0MxEX9eUrA28xVLj4QwKEwplJxuC5GK";
private static int counterRekm;
private static int counterRekl;
public static void main(String[] args) {
measureReverse(STRING_1024_LENGTH);
measureReverse(STRING_2048_LENGTH);
measureReverse(STRING_4096_LENGTH);
measureReverse(STRING_8192_LENGTH);
System.exit(0);
}
private static void measureReverse(String someString) {
System.out.println("Length of String: " + someString.length());
long startRekm = System.nanoTime();
rekm(someString);
long durationRekm = System.nanoTime() - startRekm;
printDuration("Duration Rekm", durationRekm);
long startRekl = System.nanoTime();
rekl(someString);
long durationRekl = System.nanoTime() - startRekl;
printDuration("Duration Rekl", durationRekl);
System.out.println("rekm-calls " + counterRekm + "\nrekl-calls " + counterRekl);
counterRekm = 0;
counterRekl = 0;
}
private static void printDuration(String description, long durationInNs) {
System.out.println(description + " in " + TimeUnit.NANOSECONDS.toMillis(durationInNs) + "ms "
+ " in " + durationInNs + "ns");
}
public static String rekm(String s) {
int m = s.length() / 2;
counterRekm++;
return m == 0 ? s : rekm(s.substring(m)) + rekm(s.substring(0, m));
}
public static String rekl(String s) {
counterRekl++;
return s.length() <= 1 ? s : rekl(s.substring(1)) + s.charAt(0);
}
}
|
package knowledge;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import Utils.JSON_utils;
public class SemanticNet {
OntModel model;
Map<String, Resource> cache;
Map<Resource, List<Resource>> cache_in;
Map<Resource, List<Resource>> cache_out;
Map<String, List<String>> template;
Map<String, List<String>> cacheSpeechAct;
List<String> hierarchy;
public void common() {
cache = new HashMap<>();
cache_in = new HashMap<>();
cache_out = new HashMap<>();
template = new HashMap<>();
cacheSpeechAct = new HashMap<>();
hierarchy = relationClass();
}
public SemanticNet(String url) {
this.model = Reader.readModel(url);
common();
}
public SemanticNet(OntModel model) {
this.model = model;
common();
}
public OntModel getModel() {
return model;
}
public void printModel() {
model.write(System.out);
}
public JSONArray rel_out(JSONObject obj) {
JSONArray result = null;
if (has_rel_out(obj)) {
String rel_out = obj.get("rel_out").toString();
if (JSON_utils.isJSONArray(rel_out)) {
result = enrichJSONArray(new JSONArray(rel_out));
} else {
result = enrichJSONArray(new JSONArray('[' + rel_out + ']'));
}
} else {
result = new JSONArray();
}
return result;
}
public JSONArray rel_in(JSONObject obj) {
JSONArray result = null;
if (has_rel_in(obj)) {
String rel_in = obj.get("rel_in").toString();
if (JSON_utils.isJSONArray(rel_in)) {
result = enrichJSONArray(new JSONArray(rel_in));
} else {
result = enrichJSONArray(new JSONArray('[' + rel_in + ']'));
}
} else {
result = new JSONArray();
}
return result;
}
public boolean has_rel_out(JSONObject obj) {
return (obj).has("rel_out");
}
public boolean has_rel_in(JSONObject obj) {
return (obj).has("rel_in");
}
public boolean isTerminal(JSONObject obj) {
return !has_rel_out(obj);
}
public JSONArray enrichJSONArray(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
array.put(i, new JSONObject(enrich(array.get(i).toString())));
}
return array;
}
public JSONObject cleanEnrich(JSONObject obj) {
if (obj.has("rel_in")) {
obj.remove("rel_in");
}
if (obj.has("rel_out")) {
String out = obj.get("rel_out").toString();
if (out.charAt(0) != '[') {
out = '[' + out + ']';
}
JSONArray rel_out = new JSONArray(out);
obj.remove("rel_out");
for (int i = 0; i < rel_out.length(); i++) {
JSONObject out_obj = rel_out.getJSONObject(i);
String category = out_obj.getString("category");
if (obj.has(category)) {
if (obj.get(category) instanceof JSONObject) {
cleanEnrich(obj.getJSONObject(category));
} else if (obj.get(category) instanceof JSONArray) {
JSONArray array = obj.getJSONArray(category);
for (int k = 0; k < array.length(); k++) {
cleanEnrich(array.getJSONObject(k));
}
}
}
}
}
return obj;
}
public String enrich(String message) {
if (JSON_utils.isJSONArray(message)) {
JSONArray ambiguos_message = JSON_utils.convertJSONArray(message);
for (int i = 0; i < ambiguos_message.length(); i++) {
JSONObject part = ambiguos_message.getJSONObject(i);
ambiguos_message.put(i, new JSONObject(enrich(part.toString())));
}
return ambiguos_message.toString();
} else {
JSONObject jsonMessage = new JSONObject(message);
Resource res = getResource(jsonMessage);
List<Resource> in_rel = in_Relation(res);
List<Resource> out_rel = out_Relation(res);
for (Resource in : in_rel) {
String name = getName(in);
String category = getCategory(in);
JSONObject in_json = new JSONObject();
in_json.accumulate("name", name);
in_json.accumulate("category", category);
jsonMessage.accumulate("rel_in", in_json);
}
for (Resource out : out_rel) {
String name = getName(out);
String category = getCategory(out);
JSONObject out_json = new JSONObject();
out_json.accumulate("name", name);
out_json.accumulate("category", category);
jsonMessage.accumulate("rel_out", out_json);
}
JSONObject def = getDefault(res);
if (def != null) {
jsonMessage.accumulate(Vocabulary._defaultPropertyName, def);
}
String plan = getPlan(res);
if (plan != null) {
jsonMessage.accumulate(Vocabulary.planName, plan);
}
return jsonMessage.toString();
}
}
private String getName(Resource res) {
String result = null;
if (res.hasProperty(Vocabulary.name)) {
result = ((Literal) res.getProperty(Vocabulary.name).getObject()).getString();
}
return result;
}
private String getCategory(Resource res) {
String result = null;
if (res.hasProperty(RDF.type)) {
RDFNode ontClassNode = res.getProperty(RDF.type).getObject();
Resource ontClass = model.getResource(ontClassNode.toString());
result = getName(ontClass);
}
return result;
}
private Resource getResource(JSONObject message) {
Resource result = null;
JSONObject json = new JSONObject(message.toString());
String category = json.getString("category");
String semElement = json.getString("name");
if (!cache.containsKey(json.toString())) {
String queryString = "SELECT ?n \n WHERE{?n <" + RDF.type + "> ?category.\n ?category <" + Vocabulary.name
+ "> \"" + category + "\".\n?n <" + Vocabulary.name + "> \"" + semElement + "\"}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource n = soln.getResource("n");
return n;
}
} else {
result = cache.get(json.toString());
// if (DEBUG)
// System.out.println("GET res of " + json + " IN CACHE");
}
return result;
}
private List<Resource> in_Relation(Resource res) {
List<Resource> result = null;
if (cache_in.containsKey(res)) {
result = cache_in.get(res);
} else {
result = new ArrayList<>();
for (ObjectProperty p : Vocabulary.listProperty) {
String queryString = null;
queryString = "SELECT ?n \n WHERE {?n <" + p + "> <" + res + ">}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource r = soln.getResource("n");
result.add(r);
}
}
cache_in.put(res, result);
}
return result;
}
private List<Resource> out_Relation(Resource res) {
List<Resource> result = null;
if (cache_out.containsKey(res)) {
result = cache_out.get(res);
} else {
result = new ArrayList<>();
for (ObjectProperty p : Vocabulary.listProperty) {
String queryString = null;
queryString = "SELECT ?n \n WHERE {<" + res + "> <" + p + "> ?n}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource r = soln.getResource("n");
result.add(r);
}
}
cache_out.put(res, result);
}
return result;
}
public JSONObject getDefault(Resource res) {
JSONObject result = null;
String queryString = null;
queryString = "SELECT ?n \n WHERE{<" + res + "> <" + Vocabulary._default + "> ?n}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource r = soln.getResource("n");
result = new JSONObject();
result.accumulate("category", getCategory(r));
result.accumulate("name", getName(r));
break;
}
return result;
}
public String getPlan(Resource res) {
String result = null;
String queryString = null;
queryString = "SELECT ?n \n WHERE {<" + res + "> <" + Vocabulary.plan + "> ?n}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource r = soln.getResource("n");
result = getName(r);
break;
}
return result;
}
public String getPlan(JSONObject obj) {
String result = null;
// System.out.println("FIND PLAN: \n"+obj.toString(4));
// System.out.println(Vocabulary.planName);
if (obj.has(Vocabulary.planName)) {
result = obj.getString(Vocabulary.planName);
}
return result;
}
public String get_message_not(JSONObject obj) {
String result = null;
JSONObject json = new JSONObject();
json.accumulate("name", obj.get("name"));
json.accumulate("category", obj.get("category"));
Resource res = getResource(json);
NodeIterator itrNot = model.listObjectsOfProperty(res, Vocabulary.message_not);
while (itrNot.hasNext()) {
RDFNode NodeEx = itrNot.next();
result = ((Literal) NodeEx).getString();
}
if (JSON_utils.isJSONObject(result)) {
String field = (new JSONObject(result)).getString("value");
result = obj.get(field).toString();
}
return result;
}
public String get_message_singular(JSONObject obj) {
String result = null;
JSONObject json = new JSONObject();
json.accumulate("name", obj.get("name"));
json.accumulate("category", obj.get("category"));
Resource res = getResource(json);
NodeIterator itrNot = model.listObjectsOfProperty(res, Vocabulary.message_singular);
while (itrNot.hasNext()) {
RDFNode NodeEx = itrNot.next();
result = ((Literal) NodeEx).getString();
}
if (JSON_utils.isJSONObject(result)) {
String field = (new JSONObject(result)).getString("value");
result = obj.get(field).toString();
}
return result;
}
public String get_message_plural(JSONObject obj) {
String result = null;
JSONObject json = new JSONObject();
json.accumulate("name", obj.get("name"));
json.accumulate("category", obj.get("category"));
Resource res = getResource(json);
NodeIterator itrNot = model.listObjectsOfProperty(res, Vocabulary.message_plural);
while (itrNot.hasNext()) {
RDFNode NodeEx = itrNot.next();
result = ((Literal) NodeEx).getString();
}
if (JSON_utils.isJSONObject(result)) {
String field = (new JSONObject(result)).getString("value");
result = obj.get(field).toString();
}
return result;
}
public List<String> relationClass() {
List<String> result = new ArrayList<>();
result = readChild(null, 0);
return result;
}
public List<String> readChild(Resource father, int deep) {
List<String> result = new ArrayList<>();
List<Resource> listR = new ArrayList<>();
String queryString = null;
if (father == null) {
queryString = "SELECT ?n \n WHERE{ ?n <" + RDF.type + "> <" + RDFS.Class + ">.\n OPTIONAL{?a <"
+ Vocabulary.relation + "> ?n .}\n FILTER(!bound(?a))}";
} else {
queryString = "SELECT ?n \n WHERE { ?n <" + Vocabulary.name + "> ?name.\n <" + father + "> <"
+ Vocabulary.relation + "> ?n }";
}
//System.out.println("Query: " + queryString);
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
// RDFNode rel = soln.get("rel") ; // Get a result variable by name.
Resource r = soln.getResource("n"); // Get a result variable -
String name = getName(r);
if (name != null && !result.contains(name)) {
//System.out.println("class"+deep+": " + name);
result.add(name);
listR.add(r);
}
}
for (Resource r : listR) {
List<String> result1=readChild(r, deep + 1);
for(String r1:result1){
if(!result.contains(r1)){
result.add(r1);
}
}
}
return result;
}
public List<String> getHierarchy() {
return hierarchy;
}
public int getMinCardinality(JSONObject sup, JSONObject obj) {
Resource resSup = getResource(sup);
Resource resObj = getResource(obj);
String queryString = "SELECT ?n \n WHERE{<" + resSup + "> ?rel <" + resObj + ">.\n ?rel <"
+ Vocabulary.min_card + "> ?n }";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
// RDFNode rel = soln.get("rel") ; // Get a result variable by name.
// Resource rel = soln.getResource("sup"); // Get a result variable
// must be a resource
Literal n = soln.getLiteral("n");
if (n != null) {
int number = Vocabulary.cardinality().get(n.toString());
return number;
}
}
return -1;
}
public int getMaxCardinality(JSONObject sup, JSONObject obj) {
Resource resSup = getResource(sup);
Resource resObj = getResource(obj);
String queryString = "SELECT ?n \n WHERE{<" + resSup + "> ?rel <" + resObj + ">.\n ?rel <"
+ Vocabulary.min_card + "> ?n }";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
// RDFNode rel = soln.get("rel") ; // Get a result variable by name.
Resource rel = soln.getResource("sup"); // Get a result variable -
// must be a resource
Literal n = soln.getLiteral("n");
if (n != null) {
int number = Vocabulary.cardinality().get(n.toString());
return number;
}
}
return -1;
}
public boolean incomplete(JSONObject obj) {
boolean result = false;
if (has_rel_out(obj)) {
JSONArray children = JSON_utils.convertJSONArray(obj.get("rel_out").toString());
for (int i = 0; i < children.length() && !result; i++) {
JSONObject child = children.getJSONObject(i);
int min = getMinCardinality(obj, child);
if (min != 0) {
String child_category = child.getString("category");
if (obj.has(child_category)) {
JSONArray category = JSON_utils.convertJSONArray(obj.get(child_category).toString());
for (int j = 0; j < category.length() && !result; j++) {
child = category.getJSONObject(j);
result = result || incomplete(child);
}
} else {
result = true;
}
}
}
}
return result;
}
public boolean incomplete(JSONObject obj, int level) {
boolean result = false;
if (has_rel_out(obj)) {
JSONArray children = JSON_utils.convertJSONArray(obj.get("rel_out").toString());
for (int i = 0; i < children.length() && !result; i++) {
JSONObject child = children.getJSONObject(i);
int min = getMinCardinality(obj, child);
if (min != 0) {
String child_category = child.getString("category");
if (obj.has(child_category)) {
if (level > 0) {
JSONArray category = JSON_utils.convertJSONArray(obj.get(child_category).toString());
for (int j = 0; j < category.length() && !result; j++) {
child = category.getJSONObject(j);
result = result || incomplete(child, level - 1);
}
}
} else {
result = true;
}
}
}
}
return result;
}
public JSONArray remove_incomplete(JSONArray array) {
JSONArray result = new JSONArray();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (!incomplete(obj)) {
result.put(obj);
}
}
return result;
}
public List<String> getTemplate(String name) {
List<String> result;
if (template.containsKey(name)) {
result = template.get(name);
} else {
result = new ArrayList<>();
StmtIterator iterClass = model.listStatements(new SimpleSelector(null, Vocabulary.name, name));
while (iterClass.hasNext()) {
Statement stmClass = iterClass.next();
Resource res = stmClass.getSubject();
Statement listTemplate = res.getProperty(Vocabulary.template);
if (listTemplate != null) {
Resource list = (Resource) listTemplate.getObject();
while (list != null && list.hasProperty(RDF.first)) {
Resource first = (Resource) list.getProperty(RDF.first).getObject();
result.add(getName(first));
if (list.hasProperty(RDF.rest)) {
list = (Resource) list.getProperty(RDF.rest).getObject();
} else {
list = null;
}
}
}
}
template.put(name, result);
}
return result;
}
public boolean onlyOne(JSONObject sup, JSONObject obj) {
Boolean result;
result = getMaxCardinality(sup, obj) == 1;
return result;
}
public List<String> getInfluence(JSONObject obj) {
List<String> result = null;
Resource res = getResource(obj);
String queryString = "SELECT ?n \n WHERE{?n <" + Vocabulary.speechAct + "> <" + res + "> }";
if (!cacheSpeechAct.containsKey(obj.toString())) {
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect();
for (; results.hasNext();) {
QuerySolution soln = results.nextSolution();
Resource n = soln.getResource("n");
JSONObject act = new JSONObject();
String name = getName(n);
String category = getCategory(n);
act.accumulate("name", name);
act.accumulate("category", category);
if (result == null) {
result = new ArrayList<>();
}
result.add(act.toString());
}
cacheSpeechAct.put(obj.toString(), result);
} else {
result = cacheSpeechAct.get(obj.toString());
// if (DEBUG)
// System.out.println("GET res of " + json + " IN CACHE");
}
return result;
}
}
|
package de.unihamburg.swk.parsing.document;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import de.unihamburg.masterprojekt2016.traceability.TraceabilityPointer;
import de.unihamburg.masterprojekt2016.traceability.TypePointer;
import de.unihamburg.masterprojekt2016.traceability.TypePointerClassification;
import de.unihamburg.swk.traceabilityrecovery.ISearchableDocument;
public class DocumentStack<TDocument extends ISearchableDocument> implements IDocumentCreationStructure<TDocument> {
private LayerCalculator layerCalculator;
private static int ENCLOSE_TYPE_FACTOR = 1;
private static String ENCLOSE_TYPE = "ENCLOSE TYPE";
private String filePath;
private IDocumentFactory<TDocument> documentFactory;
private List<TDocument> documentBag;
private Stack<TDocument> documentStack;
private Stack<TypePointer> typeStack;
private Stack<String> typeNameStack;
public DocumentStack(String filePath, IDocumentFactory<TDocument> documentFactory) {
this.filePath = filePath;
this.documentFactory = documentFactory;
this.layerCalculator = new LayerCalculator();
documentBag = new LinkedList<>();
documentStack = new Stack<>();
typeStack = new Stack<>();
typeNameStack = new Stack<>();
}
@Override
public void enterTypeDeclaration(TypePointerClassification classification, String simpleName, int startLine) {
TypePointer typePointer;
pushTypeName(simpleName);
typePointer = new TypePointer(currentFullyQualifiedname(), classification, filePath, startLine);
typeStack.push(typePointer);
createEmptyDocumentFor(typePointer);
addEnclosingTypeTerm1();
}
private void addEnclosingTypeTerm1() {
if (typeNameStack.size() > 2 && ENCLOSE_TYPE_FACTOR > 0) {
documentStack.peek().addTerm(ENCLOSE_TYPE_FACTOR, typeNameStack.get(typeNameStack.size() - 2), ENCLOSE_TYPE);
}
}
@Override
public void closedRecentTypeDeclaration() {
closedRecentElementDeclaration();
typeNameStack.pop();
typeStack.pop();
}
@Override
public void enterElementDeclaration(TraceabilityPointer traceabilityPointer) {
initializePointer(traceabilityPointer);
createEmptyDocumentFor(traceabilityPointer);
addEnclosingTypeTerm2();
}
@Override
public void enterElementDeclarationWithoutParentType(TraceabilityPointer traceabilityPointer) {
initializePointer(traceabilityPointer);
createEmptyDocumentFor(traceabilityPointer);
}
private void addEnclosingTypeTerm2() {
if (typeNameStack.size() > 1 && ENCLOSE_TYPE_FACTOR > 0) {
documentStack.peek().addTerm(ENCLOSE_TYPE_FACTOR, typeNameStack.peek(), ENCLOSE_TYPE);
}
}
@Override
public void closedRecentElementDeclaration() {
documentBag.add(documentStack.pop());
layerCalculator.currentSize(documentStack.size());
}
@Override
public String recentSimpleTypeName() {
return typeNameStack.peek();
}
@Override
public void addTerm(String term, String termType, int allfactor) {
addTerm(term, termType, allfactor, allfactor);
}
@Override
public void addTerm(String term, String termType, int ownFactor, int otherFactor) {
if (!documentStack.isEmpty()) {
if (ownFactor > 0) {
documentStack.peek().addTerm(ownFactor, term, termType);
}
if (otherFactor > 0) {
for (TDocument tDocument : documentStack.subList(0, documentStack.size() - 1)) {
tDocument.addTerm(otherFactor, term, termType);
}
}
}
}
public void addTerms(List<String> terms, String termType, int ownFactor, int otherFactor) {
for (String term : terms) {
addTerm(term, termType, ownFactor, otherFactor);
}
}
@Override
public List<TDocument> getAllDocuments() {
return documentBag;
}
private void createEmptyDocumentFor(TraceabilityPointer traceabilityPointer) {
documentStack.push(documentFactory.createDocument(traceabilityPointer));
documentStack.peek().setLayer(layerCalculator.getCurrentLayer(documentStack.size()));
}
private String currentFullyQualifiedname() {
String fullyQualifiedName = typeNameStack.stream().collect(Collectors.joining("."));
if (fullyQualifiedName.startsWith(".")) {
fullyQualifiedName = fullyQualifiedName.substring(1);
}
return fullyQualifiedName;
}
private void pushTypeName(String typeName) {
boolean noPackageDeclaration = typeNameStack.isEmpty();
if (noPackageDeclaration) {
typeNameStack.push("");
}
typeNameStack.push(typeName);
}
private void initializePointer(TraceabilityPointer pointer) {
if (pointer instanceof IHasTypePointer) {
if (!typeStack.isEmpty()) {
((IHasTypePointer) pointer).setTypePointer(typeStack.peek());
}
}
pointer.setSourceFilePath(filePath);
}
public void addPackage(String fullPackageName) { // TODO private
if (typeNameStack.size() > 0)
return;
typeNameStack.add(fullPackageName);
}
public TraceabilityPointer currentTraceabilityPointer() { // TODO private
if (documentStack.isEmpty())
return null;
return documentStack.peek().getTraceabilityPointer();
}
public TraceabilityPointer secondCurrentTraceabilityPointer() { // TODO private
if (documentStack.size() < 1)
return null;
return documentStack.get(documentStack.size() - 1).getTraceabilityPointer();
}
public int countOpenTypes() {
return documentStack.size();
}
public void forEachOnStack(Consumer<TDocument> consumer) {
documentStack.forEach(consumer);
}
public void layerOf(List<String> types) {
layerCalculator.checkEnterlayer(types, typeStack.size() + 1);
}
public void printOpenElements() {
for (TDocument tDocument : documentStack) {
System.out.println(tDocument.getDescription());
}
}
public String getTopmostTypeName() {
return typeStack.peek().getDisplayName();
}
public TDocument currentDocument() {
if (documentStack.isEmpty())
return null;
return documentStack.peek();
}
}
|
package mci;
import kr.ac.kaist.se.Executor;
import kr.ac.kaist.se.Util;
import kr.ac.kaist.se.simulator.NormalDistributor;
import kr.ac.kaist.se.simulator.Simulator;
import java.util.ArrayList;
public class LargeScaleMCIMain {
public static void main(String[] args) throws Exception {
Util.create_result_directory("mci_result");
NormalDistributor distributor = new NormalDistributor();
distributor.setNormalDistParams(2500, 700);
LargeMCIScenario lMCI = new LargeMCIScenario();
Simulator sim = new Simulator(lMCI);
sim.setDEBUG();
ArrayList<String> csv_rows = new ArrayList<>();
csv_rows.add("action_info");
Executor.Perform_Debug_Experiment(distributor, sim, "large_MCI", csv_rows);
}
}
|
package dk.netarkivet.archive.indexserver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.netarkivet.common.CommonSettings;
import dk.netarkivet.common.distribute.indexserver.Index;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.Settings;
/**
* A generic cache that stores items in files. This abstract superclass
* handles placement of the cache directory and adding/getting files using
* the subclasses' methods for generating filenames.
*
*/
public abstract class FileBasedCache<I> {
/** Cache directory. */
File cacheDir;
/** Logger. */
private Log log = LogFactory.getLog(getClass().getName());
/** Creates a new FileBasedCache object. This creates a directory under
* the main cache directory holding cached files.
*
* @param cacheName Name of this cache (enabling sharing among processes).
* The directoriy creating in the cachedir will have this name.
*/
public FileBasedCache(String cacheName) {
ArgumentNotValid.checkNotNullOrEmpty(cacheName, "cacheName");
this.cacheDir = new File(new File(
Settings.get(CommonSettings.CACHE_DIR)),
cacheName).getAbsoluteFile();
log.info("Metadata cache for '" + cacheName + "' uses directory '"
+ getCacheDir().getAbsolutePath() + "'");
FileUtils.createDir(getCacheDir());
}
/** Get the directory that the files are cached in. Subclasses should
* override this to create their own directory with this directory. The
* full directory structure will be created if required in the constructor.
*
* @return A directory that cache files can reside in.
*/
public File getCacheDir() {
return cacheDir;
}
/** Get the file that caches content for the given ID.
*
* @param id Some sort of id that uniquely identifies the item within the
* cache.
* @return A file (possibly nonexistant or empty) that can cache the data
* for the id.
*/
public abstract File getCacheFile(I id);
/** Fill in actual data in the file in the cache. This is the workhorse
* method that is allowed to modify the cache. When this method is called,
* the cache can assume that getCacheFile(id) does not exist.
*
* @param id Some identifier for the item to be cached.
* @return An id of content actually available. In most cases, this will
* be the same as id, but for complex I it could be a subset (or null if
* the type argument I is a simple type). If the return value is not the
* same as id, the file will not contain cached data, and may not even
* exist.
*/
protected abstract I cacheData(I id);
/** Ensure that a file containing the appropriate content exists for the ID.
* If the content cannot be found, this method may return null (if I is
* a simple type) or an appropriate subset (if I is, say, a Set) indicating
* the data that is actually available. In the latter case, calling cache
* on the returned set should always fill the file for that subset (barring
* catastrophic failure).
*
* Locking: If the file is not immediately found, we enter a file-creation
* state. To avoid corrupted data, we must ensure that only one cache
* instance, and only one thread within any instance, creates the file.
* Thus as long as somebody else seems to be creating the file, we wait
* and see if they finish. This is checked by having an exclusive lock
* on a ".working" file (we cannot use the result file, as it has to be
* created to be locked, and we may end up with a different cached file
* than we thought, see above). The .working file itself is irrelevant,
* only the lock on it matters.
*
* @param id Some sort of id that uniquely identifies the item within
* the cache.
* @return The id given if it was successfully fetched, otherwise null
* if the type parameter I does not allow subsets, or a subset of id
* if it does. This subset should be immediately cacheable.
*
* FIXME added method synchronization. Try to fix bug 1547
*/
public I cache(I id) {
ArgumentNotValid.checkNotNull(id, "id");
File cachedFile = getCacheFile(id);
if (cachedFile.exists()) {
return id;
} else {
try {
File fileBehindLockFile
= new File(cachedFile.getAbsolutePath() + ".working");
FileOutputStream lockFile = new FileOutputStream(
fileBehindLockFile);
FileLock lock = null;
// Make sure no other thread tries to create this
synchronized (fileBehindLockFile.getAbsolutePath().intern()) {
try {
// Make sure no other process tries to create this
log.debug("locking filechannel for file '"
+ fileBehindLockFile.getAbsolutePath()
+ "' (thread = "
+ Thread.currentThread().getName() + ")");
try {
lock = lockFile.getChannel().lock();
} catch (OverlappingFileLockException e) {
log.warn(e);
throw new IOException(e);
}
// Now we know nobody else touches the file
// Just in case, check that the file wasn't created
// in the interim. If it was, we can return it.
if (cachedFile.exists()) {
return id;
}
return cacheData(id);
} finally {
if (lock != null) {
log.debug("release lock on filechannel "
+ lockFile.getChannel());
lock.release();
}
lockFile.close();
}
}
} catch (IOException e) {
String errMsg = "Error obtaining lock for file '"
+ cachedFile.getAbsolutePath() + "'.";
log.warn(errMsg, e);
throw new IOFailure(errMsg, e);
}
}
}
/** Utility method to get a number of cache entries at a time.
* Implementations of FileBasedCache may override this to perform the
* caching more efficiently, if caching overhead per file is large.
*
* @param IDs List of IDs that uniquely identify a set of items within
* the cache.
* @return A map from ID to the files containing cached data for those
* IDs. If caching failed, even partially, for an ID, the entry for the ID
* doesn't exist.
*/
public Map<I, File> get(Set<I> IDs) {
ArgumentNotValid.checkNotNull(IDs, "IDs");
Map<I, File> result = new HashMap<I, File>(IDs.size());
for (I ID : IDs) {
if (ID.equals(cache(ID))) {
result.put(ID, getCacheFile(ID));
} else {
result.put(ID, null);
}
}
return result;
}
/** Forgiving index generating method, that returns a file with an
* index, of the greatest possible subset of a given id, and the subset.
*
* If the type I for instance is a Set, you may get an index of only a
* subset. If I is a File, null may be seen as a subset.
*
* @see #cache for more information.
*
* @param id The requested index.
* @return An index over the greatest possible subset, and the subset.
*/
public Index<I> getIndex(I id) {
I response = id;
I lastResponse = null;
while (response != null && !response.equals(lastResponse)) {
if (lastResponse != null) {
log.info("Requested index of type '"
+ this.getCacheDir().getName() + "' data '"
+ lastResponse
+ "' not available. Retrying with available subset '"
+ response + "'");
}
lastResponse = response;
response = cache(lastResponse);
}
File cacheFile = getCacheFile(response);
log.info("Generated index '" + cacheFile + "' of id '" + response
+ "', request was for '" + id + "'");
return new Index<I>(cacheFile, response);
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.WebAppSpringTestConfig;
import com.imcode.imcms.components.datainitializer.CategoryDataInitializer;
import com.imcode.imcms.domain.service.CategoryService;
import com.imcode.imcms.domain.service.CategoryTypeService;
import com.imcode.imcms.model.Category;
import com.imcode.imcms.model.CategoryType;
import com.imcode.imcms.persistence.entity.CategoryJPA;
import com.imcode.imcms.persistence.entity.CategoryTypeJPA;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/**
* @see CategoryService
*/
@Transactional
public class CategoryServiceTest extends WebAppSpringTestConfig {
@Autowired
private CategoryService categoryService;
@Autowired
private CategoryTypeService categoryTypeService;
@Autowired
private CategoryDataInitializer categoryDataInitilizer;
@BeforeEach
public void setUp() {
categoryDataInitilizer.createData(4);
}
@AfterEach
public void cleanup() {
categoryDataInitilizer.cleanRepositories(); // should be done even in case of transactional
}
@Test
public void getAllExpectedEqualsCategoriesAsDtoTest() {
assertEquals(categoryDataInitilizer.getCategoriesAsDTO(), categoryService.getAll());
}
@Test
public void getById_When_Exist_Expect_NotNull() {
final Integer id = categoryDataInitilizer.getCategoriesAsDTO().get(0).getId();
assertTrue(categoryService.getById(id).isPresent());
}
@Test
public void save_When_NotExistBefore_Expect_Saved() {
final String testTypeName = "test_type_name" + System.currentTimeMillis();
final CategoryType categoryType = new CategoryTypeJPA(
null, testTypeName, 0, false, false
);
final CategoryTypeJPA savedType = new CategoryTypeJPA(categoryTypeService.save(categoryType));
final String testCategoryName = "test_category_name" + System.currentTimeMillis();
final Category category = new CategoryJPA(testCategoryName, "dummy", "", savedType);
final Category saved = categoryService.save(category);
final Optional<Category> oFound = categoryService.getById(saved.getId());
assertTrue(oFound.isPresent());
final Category found = oFound.get();
assertNotNull(found);
assertEquals(saved, found);
}
@Test
public void delete_When_Exist_Expect_Saved() {
final String testTypeName = "test_type_name" + System.currentTimeMillis();
final CategoryType categoryType = new CategoryTypeJPA(
null, testTypeName, 0, false, false
);
final CategoryTypeJPA savedType = new CategoryTypeJPA(categoryTypeService.save(categoryType));
final String testCategoryName = "test_category_name" + System.currentTimeMillis();
final Category category = new CategoryJPA(testCategoryName, "dummy", "", savedType);
final Category saved = categoryService.save(category);
final Integer savedCategoryId = saved.getId();
assertTrue(categoryService.getById(savedCategoryId).isPresent());
categoryService.delete(savedCategoryId);
assertFalse(categoryService.getById(savedCategoryId).isPresent());
}
}
|
package org.craft.world;
import java.util.*;
import org.craft.blocks.*;
public class Chunk
{
public Block[][][] blocks;
public int[][] highest;
public float[][][] lightValues;
private ChunkCoord coords;
private boolean isDirty;
private World owner;
public Chunk(World owner, ChunkCoord coords)
{
this.owner = owner;
this.coords = coords;
this.blocks = new Block[16][16][16];
this.highest = new int[16][16];
this.lightValues = new float[16][16][16];
for(int x = 0; x < 16; x++ )
{
Arrays.fill(highest[x], -1);
for(int y = 0; y < 16; y++ )
{
Arrays.fill(blocks[x][y], Blocks.air);
Arrays.fill(lightValues[x][y], 1f);
}
}
}
/**
* Returns light value in Chunk from given world space
*/
public float getLightValue(World w, int worldX, int worldY, int worldZ)
{
int x = worldX % 16;
int y = worldY % 16;
int z = worldZ % 16;
if(x < 0)
x = 16 + x;
if(y < 0)
y = 16 + y;
if(z < 0)
z = 16 + z;
return lightValues[x][y][z];
}
/**
* Returns block in Chunk from given world space
*/
public Block getBlock(World w, int worldX, int worldY, int worldZ)
{
int x = worldX % 16;
int y = worldY % 16;
int z = worldZ % 16;
if(x < 0)
x = 16 + x;
if(y < 0)
y = 16 + y;
if(z < 0)
z = 16 + z;
if(blocks[x][y][z] == null)
blocks[x][y][z] = Blocks.air;
return blocks[x][y][z];
}
/**
* Sets light value in Chunk from given world space
*/
public void setLightValue(World world, int worldX, int worldY, int worldZ, float lightValue)
{
int x = worldX % 16;
int y = worldY % 16;
int z = worldZ % 16;
if(x < 0)
x = 16 + x;
if(y < 0)
y = 16 + y;
if(z < 0)
z = 16 + z;
lightValues[x][y][z] = lightValue;
isDirty = true;
markNeighbors(x, y, z);
}
/**
* Set block in Chunk from given world space
*/
public void setBlock(World world, int worldX, int worldY, int worldZ, Block block)
{
int x = worldX % 16;
int y = worldY % 16;
int z = worldZ % 16;
if(x < 0)
x = 16 + x;
if(y < 0)
y = 16 + y;
if(z < 0)
z = 16 + z;
setChunkBlock(x, y, z, block);
}
public boolean isDirty()
{
return isDirty;
}
public ChunkCoord getCoords()
{
return coords;
}
public void markDirty()
{
isDirty = true;
}
public void cleanUpDirtiness()
{
isDirty = false;
}
public void fill(Block block)
{
for(int x = 0; x < 16; x++ )
for(int y = 0; y < 16; y++ )
{
for(int z = 0; z < 16; z++ )
{
setChunkBlock(x, y, z, block);
markNeighbors(x, y, z);
}
}
}
/**
* Returns light value in Chunk from given chunk space
*/
public float getChunkLightValue(int x, int y, int z)
{
return lightValues[x][y][z];
}
/**
* Sets light value in Chunk from given chunk space
*/
public void setChunkLightValue(int x, int y, int z, float lightValue)
{
lightValues[x][y][z] = lightValue;
markDirty();
markNeighbors(x, y, z);
}
private void markNeighbors(int x, int y, int z)
{
Chunk c = owner.getChunkProvider().get(owner, coords.x - 1, coords.y, coords.z);
if(c != null)
c.markDirty();
c = owner.getChunkProvider().get(owner, coords.x + 1, coords.y, coords.z);
if(c != null)
c.markDirty();
c = owner.getChunkProvider().get(owner, coords.x, coords.y - 1, coords.z);
if(c != null)
c.markDirty();
c = owner.getChunkProvider().get(owner, coords.x, coords.y + 1, coords.z);
if(c != null)
c.markDirty();
c = owner.getChunkProvider().get(owner, coords.x, coords.y, coords.z - 1);
if(c != null)
c.markDirty();
c = owner.getChunkProvider().get(owner, coords.x, coords.y, coords.z + 1);
if(c != null)
c.markDirty();
}
/**
* Returns block in Chunk from given chunk space
*/
public Block getChunkBlock(int x, int y, int z)
{
Block b = blocks[x][y][z];
if(b == null)
return Blocks.air;
return b;
}
/**
* Sets block in Chunk from given chunk space
*/
public void setChunkBlock(int x, int y, int z, Block block)
{
if(block == null)
block = Blocks.air;
else
blocks[x][y][z] = block;
if(y >= highest[x][z])
{
if(block != Blocks.air)
{
highest[x][z] = y;
}
else if(y == highest[x][z])
{
for(; y >= 0; --y)
{
if(getChunkBlock(x, y, z) != Blocks.air)
{
break;
}
}
highest[x][z] = y;
}
}
markDirty();
markNeighbors(x, y, z);
}
/**
* Returns highest block in Chunk from given chunk space
*/
public Block getHighestBlock(int x, int z)
{
if(highest[x][z] < 0)
return null;
return getChunkBlock(x, highest[x][z], z);
}
/**
* Returns highest y value in Chunk from given chunk space
*/
public int getHighest(int x, int z)
{
return highest[x][z];
}
}
|
package com.ryanpmartz.booktrackr.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ryanpmartz.booktrackr.authentication.JwtUtil;
import com.ryanpmartz.booktrackr.domain.User;
import com.ryanpmartz.booktrackr.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.servlet.MockMvc;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
public class UserControllerTest {
private static final String EXISTING_USER_EMAIL = "existinguser@ryanpmartz.com";
private static final String NEW_USER_EMAIL = "newuser@ryanpmartz.com";
private MockMvc mockMvc;
private ObjectMapper mapper = new ObjectMapper();
private Map<String, String> requestJsonData = new HashMap<>();
@Mock
private UserService userService;
@Mock
private PasswordEncoder passwordEncoder;
@Mock
private JwtUtil jwtUtil;
@InjectMocks
private UserController userController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = standaloneSetup(userController).build();
requestJsonData.put("firstName", "New");
requestJsonData.put("lastName", "User");
requestJsonData.put("password", "he#4!09ql)C");
requestJsonData.put("confirmPassword", "he#4!09ql)C");
when(userService.getUserByEmail(EXISTING_USER_EMAIL)).thenReturn(Optional.of(new User()));
when(userService.getUserByEmail(NEW_USER_EMAIL)).thenReturn(Optional.empty());
}
@Test
public void testCreatingAccount() throws Exception {
User expectedUser = new User();
expectedUser.setEmail(NEW_USER_EMAIL);
expectedUser.setPassword("super secret");
when(userService.createUser(any(User.class))).thenReturn(expectedUser);
requestJsonData.put("email", NEW_USER_EMAIL);
mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(requestJsonData)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.email").value(NEW_USER_EMAIL))
.andExpect(jsonPath("$.password").doesNotExist());
}
@Test
public void testCreatingAccountWithEmailInUse() throws Exception {
requestJsonData.put("email", EXISTING_USER_EMAIL);
mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(requestJsonData)))
.andExpect(status().isBadRequest());
verify(userService, never()).createUser(any(User.class));
}
@Test
public void testCreatingAccountWithMismatchedPasswords() throws Exception {
requestJsonData.put("email", NEW_USER_EMAIL);
requestJsonData.put("confirmPassword", "does not match");
mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(requestJsonData)))
.andExpect(status().isBadRequest());
verify(userService, never()).createUser(any(User.class));
}
}
|
package dr.app.beauti.treespanel;
import dr.app.beauti.options.PartitionTreeModel;
import dr.app.beauti.options.PartitionTreePrior;
import dr.app.beauti.options.TreePrior;
import dr.app.beauti.util.PanelUtils;
import dr.evomodel.coalescent.VariableDemographicModel;
import org.virion.jam.components.WholeNumberField;
import org.virion.jam.panels.OptionsPanel;
import javax.swing.*;
import java.awt.event.*;
import java.util.EnumSet;
import java.util.Set;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $
*/
public class PartitionTreePriorPanel extends OptionsPanel {
private static final long serialVersionUID = 5016996360264782252L;
private JComboBox treePriorCombo = new JComboBox(EnumSet.range(TreePrior.CONSTANT, TreePrior.BIRTH_DEATH).toArray());
private JComboBox parameterizationCombo = new JComboBox(new String[]{
"Growth Rate", "Doubling Time"});
private JComboBox bayesianSkylineCombo = new JComboBox(new String[]{
"Piecewise-constant", "Piecewise-linear"});
private WholeNumberField groupCountField = new WholeNumberField(2, Integer.MAX_VALUE);
private JComboBox extendedBayesianSkylineCombo = new JComboBox(VariableDemographicModel.Type.values());
JComboBox gmrfBayesianSkyrideCombo = new JComboBox(new String[]{
"Uniform", "Time-aware"});
// RealNumberField samplingProportionField = new RealNumberField(Double.MIN_VALUE, 1.0);
// private BeautiFrame frame = null;
// private BeautiOptions options = null;
PartitionTreePrior partitionTreePrior;
private final TreesPanel treesPanel;
private boolean settingOptions = false;
public PartitionTreePriorPanel(PartitionTreePrior parTreePrior, TreesPanel parent) {
super(12, 8);
this.partitionTreePrior = parTreePrior;
this.treesPanel = parent;
PanelUtils.setupComponent(treePriorCombo);
treePriorCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreePrior.setNodeHeightPrior((TreePrior) treePriorCombo.getSelectedItem());
setupPanel();
}
});
PanelUtils.setupComponent(parameterizationCombo);
parameterizationCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreePrior.setParameterization(parameterizationCombo.getSelectedIndex());
}
});
PanelUtils.setupComponent(groupCountField);
groupCountField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent ev) {
// move to here?
}
});
PanelUtils.setupComponent(bayesianSkylineCombo);
bayesianSkylineCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreePrior.setSkylineModel(bayesianSkylineCombo.getSelectedIndex());
}
});
PanelUtils.setupComponent(extendedBayesianSkylineCombo);
extendedBayesianSkylineCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type)
extendedBayesianSkylineCombo.getSelectedItem()).toString());
}
});
PanelUtils.setupComponent(gmrfBayesianSkyrideCombo);
gmrfBayesianSkyrideCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreePrior.setSkyrideSmoothing(gmrfBayesianSkyrideCombo.getSelectedIndex());
}
});
// samplingProportionField.addKeyListener(keyListener);
setupPanel();
}
private void setupPanel() {
removeAll();
addComponentWithLabel("Tree Prior:", treePriorCombo);
if (treePriorCombo.getSelectedItem() == TreePrior.EXPONENTIAL ||
treePriorCombo.getSelectedItem() == TreePrior.LOGISTIC ||
treePriorCombo.getSelectedItem() == TreePrior.EXPANSION) {
addComponentWithLabel("Parameterization for growth:", parameterizationCombo);//TODO Issue 93
} else if (treePriorCombo.getSelectedItem() == TreePrior.SKYLINE) {
groupCountField.setColumns(6);
addComponentWithLabel("Number of groups:", groupCountField);
addComponentWithLabel("Skyline Model:", bayesianSkylineCombo);
} else if (treePriorCombo.getSelectedItem() == TreePrior.BIRTH_DEATH) {
// samplingProportionField.setColumns(8);
// treePriorPanel.addComponentWithLabel("Proportion of taxa sampled:", samplingProportionField);
} else if (treePriorCombo.getSelectedItem() == TreePrior.EXTENDED_SKYLINE) {
addComponentWithLabel("Model Type:", extendedBayesianSkylineCombo);
treesPanel.shareSameTreePriorCheck.setSelected(true);
treesPanel.updateShareSameTreePriorChanged();
// treesPanel.getFrame().setupEBSP(); TODO
} else if (treePriorCombo.getSelectedItem() == TreePrior.GMRF_SKYRIDE) {
addComponentWithLabel("Smoothing:", gmrfBayesianSkyrideCombo);
}
if (treePriorCombo.getSelectedItem() == TreePrior.GMRF_SKYRIDE) {
//For GMRF, one tree prior has to be associated to one tree model. The validation is in BeastGenerator.checkOptions()
addLabel("For GMRF, tree model/tree prior combination not implemented by BEAST yet!" +
"\nThe shareSameTreePrior has to be unchecked using GMRF.");
treesPanel.shareSameTreePriorCheck.setSelected(false);
treesPanel.shareSameTreePriorCheck.setEnabled(false);
treesPanel.updateShareSameTreePriorChanged();
} else {
treesPanel.shareSameTreePriorCheck.setEnabled(true);
// treesPanel.shareSameTreePriorCheck.setSelected(true);
// treesPanel.updateShareSameTreePriorChanged();
}
// getOptions();
// treesPanel.treeModelPanels.get(treesPanel.currentTreeModel).setOptions();
for (PartitionTreeModel model : treesPanel.treeModelPanels.keySet()) {
if (model != null) {
treesPanel.treeModelPanels.get(model).setOptions();
}
}
// createTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0);
// fireTableDataChanged();
validate();
repaint();
}
public void setOptions() {
if (partitionTreePrior == null) {
return;
}
settingOptions = true;
treePriorCombo.setSelectedItem(partitionTreePrior.getNodeHeightPrior());
groupCountField.setValue(partitionTreePrior.getSkylineGroupCount());
//samplingProportionField.setValue(partitionTreePrior.birthDeathSamplingProportion);
parameterizationCombo.setSelectedIndex(partitionTreePrior.getParameterization());
bayesianSkylineCombo.setSelectedIndex(partitionTreePrior.getSkylineModel());
extendedBayesianSkylineCombo.setSelectedItem(partitionTreePrior.getExtendedSkylineModel());
gmrfBayesianSkyrideCombo.setSelectedIndex(partitionTreePrior.getSkyrideSmoothing());
// setupPanel();
settingOptions = false;
validate();
repaint();
}
public void getOptions() {
if (settingOptions) return;
// partitionTreePrior.setNodeHeightPrior((TreePrior) treePriorCombo.getSelectedItem());
if (partitionTreePrior.getNodeHeightPrior() == TreePrior.SKYLINE) {
Integer groupCount = groupCountField.getValue();
if (groupCount != null) {
partitionTreePrior.setSkylineGroupCount(groupCount);
} else {
partitionTreePrior.setSkylineGroupCount(5);
}
} else if (partitionTreePrior.getNodeHeightPrior() == TreePrior.BIRTH_DEATH) {
// Double samplingProportion = samplingProportionField.getValue();
// if (samplingProportion != null) {
// partitionTreePrior.birthDeathSamplingProportion = samplingProportion;
// } else {
// partitionTreePrior.birthDeathSamplingProportion = 1.0;
}
// partitionTreePrior.setParameterization(parameterizationCombo.getSelectedIndex());
// partitionTreePrior.setSkylineModel(bayesianSkylineCombo.getSelectedIndex());
// partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem()).toString());
// partitionTreePrior.setSkyrideSmoothing(gmrfBayesianSkyrideCombo.getSelectedIndex());
// the taxon list may not exist yet... this should be set when generating...
// partitionTreePrior.skyrideIntervalCount = partitionTreePrior.taxonList.getTaxonCount() - 1;
}
public void removeCertainPriorFromTreePriorCombo() {
treePriorCombo.removeItem(TreePrior.YULE);
treePriorCombo.removeItem(TreePrior.BIRTH_DEATH);
}
public void recoveryTreePriorCombo() {
if (treePriorCombo.getItemCount() < EnumSet.range(TreePrior.CONSTANT, TreePrior.BIRTH_DEATH).size()) {
treePriorCombo.addItem(TreePrior.YULE);
treePriorCombo.addItem(TreePrior.BIRTH_DEATH);
}
}
}
|
package org.febit.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import org.febit.bean.AccessFactory;
import org.febit.bean.Setter;
import org.febit.convert.Convert;
import org.febit.convert.TypeConverter;
import org.febit.lang.Defaults;
import org.febit.lang.IdentityMap;
import org.febit.util.agent.LazyAgent;
/**
* A Simple IoC.
*
* @author zqq90
*/
public class Petite {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(Petite.class);
protected static final Method[] EMPTY_METHODS = new Method[0];
protected static final Setter[] EMPTY_SETTERS = new Setter[0];
protected final TypeConverter defaultConverter;
protected final IdentityMap<Class> replaceTypes;
protected final Map<String, Object> beans;
protected final Map<String, String> replaceNames;
protected final PropsManager propsMgr;
protected final GlobalBeanManager globalBeanMgr;
protected final LazyAgent<PetiteGlobalBeanProvider[]> globalBeanProviders = new LazyAgent<PetiteGlobalBeanProvider[]>() {
@Override
protected PetiteGlobalBeanProvider[] create() {
List<PetiteGlobalBeanProvider> providerList
= CollectionUtil.read(ServiceLoader.load(PetiteGlobalBeanProvider.class));
PetiteGlobalBeanProvider[] providers
= providerList.toArray(new PetiteGlobalBeanProvider[providerList.size()]);
PriorityUtil.desc(providers);
return providers;
}
};
protected boolean inited = false;
protected Petite() {
this.defaultConverter = new BeanTypeConverter();
this.propsMgr = new PropsManager();
this.globalBeanMgr = new GlobalBeanManager();
this.beans = new HashMap<>();
this.replaceTypes = new IdentityMap<>();
this.replaceNames = new HashMap<>();
}
protected synchronized void _init() {
if (inited) {
return;
}
inited = true;
addGlobalBean(this);
initGlobals();
}
protected void initGlobals() {
//globals
Object globalRaw = this.propsMgr.get("@global");
if (globalRaw == null) {
return;
}
final String[] beanNames = StringUtil.toArray(globalRaw.toString());
if (beanNames.length == 0) {
return;
}
//In case of circular reference, create all instance at once, then inject them.
//create
final Object[] instances = new Object[beanNames.length];
for (int i = 0; i < beanNames.length; i++) {
String name = beanNames[i];
instances[i] = newInstance(resolveType(name));
addGlobalBean(instances[i]);
}
//inject
for (int i = 0; i < instances.length; i++) {
doInject(beanNames[i], instances[i]);
}
}
public String resolveBeanName(Object bean) {
if (bean instanceof Class) {
return ((Class) bean).getName();
}
return bean.getClass().getName();
}
protected Class getReplacedType(Class type) {
final Class replaceWith = replaceTypes.get(type);
return replaceWith == null ? type : replaceWith;
}
protected String getReplacedName(String name) {
final String replaceWith = replaceNames.get(name);
return replaceWith == null ? name : replaceWith;
}
public void replace(Class replace, Class with) {
this.replaceTypes.put(replace, with);
this.replace(replace.getName(), with.getName());
}
public void replace(String replace, String with) {
this.replaceNames.put(replace, with);
this.propsMgr.putProp(replace + ".@extends", with);
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> type) {
T bean = this.globalBeanMgr.get(type);
if (bean != null) {
return bean;
}
return (T) get(type.getName());
}
public Object get(final String name) {
Object bean = this.beans.get(name);
if (bean != null) {
return bean;
}
return createIfAbsent(name);
}
protected synchronized Object createIfAbsent(String name) {
Object bean = this.beans.get(name);
if (bean != null) {
return bean;
}
Class type = resolveType(name);
bean = newInstance(type);
inject(name, bean);
this.beans.put(name, bean);
return bean;
}
protected Class resolveType(String name) {
String type;
name = getReplacedName(name);
do {
type = name;
name = (String) this.propsMgr.get(name + ".@class");
} while (name != null);
try {
return ClassUtil.getClass(type);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
}
}
protected Object newInstance(Class type) {
type = getReplacedType(type);
Object bean = getFreshGlobalBeanInstance(type);
if (bean != null) {
return bean;
}
return ClassUtil.newInstance(getReplacedType(type));
}
protected Object getFreshGlobalBeanInstance(Class type) {
for (PetiteGlobalBeanProvider globalBeanProvider : this.globalBeanProviders.get()) {
if (globalBeanProvider.isSupportType(type)) {
return globalBeanProvider.getInstance(type, this);
}
}
return null;
}
public void inject(Object bean) {
inject(resolveBeanName(bean), bean);
}
public void inject(final String name, final Object bean) {
doInject(name, bean);
}
protected void doInject(final String name, final Object bean) {
final Map<String, Setter> setters = AccessFactory.resolveSetters(bean.getClass());
final Map<String, Object> params = this.propsMgr.resolveParams(name);
//Setters
for (Map.Entry<String, Setter> entry : setters.entrySet()) {
String param = entry.getKey();
Setter setter = entry.getValue();
//inject param
Object paramValue = params.get(param);
if (paramValue != null) {
if (paramValue instanceof String) {
paramValue = convert((String) paramValue, setter.getPropertyType());
}
setter.set(bean, paramValue);
continue;
}
//global
Object comp = this.globalBeanMgr.get(setter.getPropertyType());
if (comp != null) {
setter.set(bean, comp);
continue;
}
}
//Init
for (Method method : ClassUtil.getAccessableMemberMethods(bean.getClass())) {
if (method.getAnnotation(Petite.Init.class) == null) {
continue;
}
final Class[] argTypes = method.getParameterTypes();
final Object[] args;
if (argTypes.length == 0) {
args = Defaults.EMPTY_OBJECTS;
} else {
args = new Object[argTypes.length];
for (int i = 0; i < argTypes.length; i++) {
args[i] = this.globalBeanMgr.get(argTypes[i]);
}
}
try {
method.invoke(bean, args);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//shouldn't be
throw new RuntimeException(ex);
}
}
}
public void add(Object bean) {
this.beans.put(resolveBeanName(bean), bean);
}
public void add(Class type, Object bean) {
this.beans.put(resolveBeanName(type), bean);
}
public void add(String name, Object bean) {
this.beans.put(name, bean);
}
public void regist(Object bean) {
regist(resolveBeanName(bean), bean);
}
public void regist(String name, Object bean) {
inject(name, bean);
this.beans.put(name, bean);
}
protected Object convert(String string, Class cls) {
return Convert.convert(string, cls, defaultConverter);
}
protected void addProps(Props props, Map<String, ?> parameters) {
this.propsMgr.addProps(props, parameters);
}
public Object getProps(String name) {
return this.propsMgr.get(name);
}
protected void addGlobalBean(Object bean) {
this.globalBeanMgr.add(bean);
}
protected boolean isGlobalType(Class type) {
for (PetiteGlobalBeanProvider globalBeanProvider : this.globalBeanProviders.get()) {
if (globalBeanProvider.isSupportType(type)) {
return true;
}
}
return false;
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public static @interface Init {
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
protected final Petite petite;
protected Builder() {
petite = new Petite();
}
public Builder addProps(Props props) {
this.petite.addProps(props, null);
return this;
}
public Builder addProps(Props props, Map<String, ?> parameters) {
this.petite.addProps(props, parameters);
return this;
}
public Builder addProps(Map<String, ?> parameters) {
this.petite.addProps(null, parameters);
return this;
}
public Builder addGlobalBean(Object bean) {
this.petite.addGlobalBean(bean);
return this;
}
public Petite build() {
petite._init();
return petite;
}
}
protected class GlobalBeanManager {
protected final IdentityMap<Object> container = new IdentityMap<>();
//Store immature beans.
protected final IdentityMap internalCache = new IdentityMap(64);
public void add(Object bean) {
//regist all impls
Class rootType = bean.getClass();
for (Class cls : ClassUtil.impls(bean)) {
//only regist spec types
if (cls != rootType && !Petite.this.isGlobalType(cls)) {
continue;
}
this.container.put(cls, bean);
}
}
public <T> T get(Class<T> type) {
T bean = (T) this.container.get(type);
if (bean != null) {
return bean;
}
if (!Petite.this.isGlobalType(type)) {
return null;
}
return createIfAbsent(type);
}
/**
* .
* <p>
* NOTE: synchronized
* </p>
*
* @param <T>
* @param type
* @return
*/
protected synchronized <T> T createIfAbsent(final Class<T> type) {
T target;
if ((target = (T) container.get(type)) != null) {
return target;
}
if ((target = (T) internalCache.get(type)) != null) {
return target;
}
Class replacedType = getReplacedType(type);
if (replacedType != type) {
if ((target = (T) container.get(replacedType)) != null) {
return (T) container.putIfAbsent(type, target);
}
if ((target = (T) internalCache.get(replacedType)) != null) {
return (T) internalCache.putIfAbsent(type, target);
}
}
target = (T) Petite.this.newInstance(replacedType);
internalCache.put(type, target);
if (replacedType != type) {
internalCache.put(replacedType, target);
}
Petite.this.inject(target.getClass().getName(), target);
container.put(type, target);
internalCache.remove(type);
if (replacedType != type) {
container.put(replacedType, target);
internalCache.remove(replacedType);
}
add(target);
return target;
}
}
protected static final class Entry {
protected final String name;
protected final Object value;
protected final Entry next;
protected Entry(String name, Object value, Entry next) {
this.name = name;
this.value = value;
this.next = next;
}
}
protected static class PropsManager {
protected final Map<String, Object> datas;
protected final Map<String, Entry> entrys;
public PropsManager() {
this.datas = new HashMap<>();
this.entrys = new HashMap<>();
}
public Object get(String key) {
return this.datas.get(key);
}
public void putProp(String key, Object value) {
this.datas.put(key, value);
int index = key.lastIndexOf('.');
int index2;
if (index > 0
&& (index2 = index + 1) < key.length()
&& key.charAt(index2) != '@') {
String beanName = key.substring(0, index);
this.entrys.put(beanName,
new Entry(key.substring(index2), value, this.entrys.get(beanName)));
}
}
public void addProps(Props props, Map<String, ?> parameters) {
if (props == null) {
props = new Props();
}
final Map<String, Object> extras;
if (parameters != null) {
extras = new HashMap<>();
for (Map.Entry<String, ?> entry : parameters.entrySet()) {
String key = entry.getKey();
if (key == null) {
continue;
}
key = key.trim();
Object value = entry.getValue();
if (value instanceof String) {
int len = key.length();
if (len > 0) {
if (key.charAt(len - 1) == '+') {
props.append(key.substring(0, len - 1).trim(), (String) value);
} else {
props.set(key, (String) value);
}
}
} else {
extras.put(key, value);
}
}
} else {
extras = null;
}
addProps(props);
if (extras != null) {
addProps(extras);
}
}
public void addProps(Props props) {
if (props == null) {
return;
}
for (String key : props.keySet()) {
putProp(key, props.get(key));
}
}
public void addProps(Map<String, Object> map) {
if (map == null) {
return;
}
for (Map.Entry<String, Object> entrySet : map.entrySet()) {
putProp(entrySet.getKey(), entrySet.getValue());
}
}
public Map<String, Object> resolveParams(String key) {
final LinkedList<String> keys = new LinkedList<>();
do {
keys.addFirst(key);
key = (String) this.datas.get(key + ".@class");
} while (key != null);
final Map<String, Object> params = new HashMap<>();
final Set<String> injected = new HashSet<>();
for (String beanName : keys) {
resolveParams(beanName, params, injected);
}
return params;
}
protected void resolveParams(final String beanName, final Map<String, Object> params, final Set<String> injected) {
if (injected.contains(beanName)) {
return;
}
injected.add(beanName);
//inject @extends first
Object extendProfiles = datas.get(beanName.concat(".@extends"));
if (extendProfiles != null) {
for (String profile : StringUtil.toArray(String.valueOf(extendProfiles))) {
resolveParams(profile, params, injected);
}
}
Entry entry = entrys.get(beanName);
while (entry != null) {
params.put(entry.name, entry.value);
entry = entry.next;
}
}
}
protected class BeanTypeConverter implements TypeConverter {
@Override
public Object convert(String raw, Class type) {
if (raw == null) {
return null;
}
if (Object[].class.isAssignableFrom(type)) {
String[] names = StringUtil.toArrayExcludeCommit(raw);
Object[] beans = (Object[]) Array.newInstance(type.getComponentType(), names.length);
for (int i = 0; i < names.length; i++) {
beans[i] = Petite.this.get(names[i]);
}
return beans;
}
return Petite.this.get(raw);
}
}
}
|
package hr.fer.zemris.vhdllab.applets.simulations;
import hr.fer.zemris.vhdllab.vhdl.simulations.VcdParser;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.BorderLayout;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Box;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JColorChooser;
import javax.swing.DefaultListModel;
import javax.swing.SwingConstants;
class Console
{
// Create a title string from the class name:
public static String title(Object o)
{
String t = o.getClass().toString();
// Remove the word "class":
if(t.indexOf("class") != -1)
t = t.substring(6);
return t;
}
public static void
run(JFrame frame, int width, int height)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
public static void
run(JApplet applet, int width, int height)
{
JFrame frame = new JFrame(title(applet));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
public static void
run(JPanel panel, int width, int height)
{
JFrame frame = new JFrame(title(panel));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setSize(width, height);
frame.setVisible(true);
}
}
public class WaveApplet extends JApplet
{
/** glavni container */
private Container cp;
/** Panel koji sadrzi imena signala */
private SignalNamesPanel signalNames;
/** Panel koji sadrzi trenutne vrijednosti u ovisnosti o polozaju kursora */
private SignalValuesPanel signalValues;
/** Panel na kojem se crtaju valni oblici */
private WaveDrawBoard waves;
/** Panel koji sadrzi skalu */
private Scale scale;
/**
* Vertikalni scrollbar koji pomice panel s imenima signala i panel s
* valnim oblicima
*/
private JScrollBar verticalScrollbar;
/** Horizontalni scrollbar pomice panel s valnim oblicima i skalu */
private JScrollBar horizontalScrollbar;
/** Scrollbar koji pomice panel s imenima signala */
private JScrollBar signalNamesScrollbar;
/** Scrollbar koji pomice panel s trenutnim vrijednostima ovisno o kursoru */
private JScrollBar signalValuesScrollbar;
/** Textfield koji sadrzi tocnu vrijednost na kojoj se nalazi kursor misa */
private JTextField textField = new RoundField(10);
/** Search signal */
private JTextField search = new RoundField(10);
/** Vremenska razlika izmedu kursora i mouse kursora */
private JTextField interval = new RoundField(10);
/** Panel po kojem se pomice znacka kursora */
private CursorPanel cursorPanel;
/** Popup meni koji sadrzi ikone za pozicioniranje na bridove signala */
private JPopupMenu popup = new JPopupMenu();
/** Help popup */
private JPopupMenu popupHelp = new JPopupMenu();
/** Trenutna vrijednost na dvoklik misa */
private JPopupMenu showValue = new JPopupMenu();
/** Trenutna vrijednost ide u ovaj textField */
/* Bitno je ovdje ne staviti fiksnu duljinu jer ce paneli gledati tu duljinu, a ne broj znakova u textFieldu */
private JTextField currentValue = new JTextField();
/** Sadrzi rezultate simulacije. */
private GhdlResults results;
/** Help panel */
private HelpPanel helpPanel;
/** Options popup */
private JPopupMenu optionsPopup = new JPopupMenu();
/** Divider koji razdvaja panel s imenima signala i trenutnim vrijednostima */
private JPanel divider1 = new JPanel();
/** Divider koji razdvaja panel s trenutnim vrijednostima i valne oblike */
private JPanel divider2 = new JPanel();
/** Sve boje koje se koriste */
private ThemeColor themeColor = new ThemeColor();
/* ikone */
private Icon navigate = new ImageIcon(getClass().getResource("navigate.png"));
private Icon rightUpIcon = new ImageIcon(getClass().getResource("rightUp.png"));
private Icon rightDownIcon = new ImageIcon(getClass().getResource("rightDown.png"));
private Icon leftUpIcon = new ImageIcon(getClass().getResource("leftUp.png"));
private Icon leftDownIcon = new ImageIcon(getClass().getResource("leftDown.png"));
private Icon zoomInTwoIcon = new ImageIcon(getClass().getResource("+2.png"));
private Icon zoomOutTwoIcon = new ImageIcon(getClass().getResource("-2.png"));
private Icon zoomInTenIcon = new ImageIcon(getClass().getResource("+10.png"));
private Icon zoomOutTenIcon = new ImageIcon(getClass().getResource("-10.png"));
private Icon defaultIcon = new ImageIcon(getClass().getResource("default.png"));
private Icon upIcon = new ImageIcon(getClass().getResource("up.png"));
private Icon downIcon = new ImageIcon(getClass().getResource("down.png"));
private Icon helpIcon = new ImageIcon(getClass().getResource("help.png"));
private Icon optionsIcon = new ImageIcon(getClass().getResource("options.png"));
/* buttons */
/** Pokazuje popup za trazenje bridova signala */
private JButton navigateSignals = new JButton(navigate);
/** Sljedeci rastuci brid */
private JButton rightUp = new JButton(rightUpIcon);
/** Sljedeci padajuci brid */
private JButton rightDown = new JButton(rightDownIcon);
/** Prethodni rastuci brid */
private JButton leftUp = new JButton(leftUpIcon);
/** Prethodni padajuci brid */
private JButton leftDown = new JButton(leftDownIcon);
private JButton zoomInTwoButton = new JButton(zoomInTwoIcon);
private JButton zoomOutTwoButton = new JButton(zoomOutTwoIcon);
private JButton zoomInTenButton = new JButton(zoomInTenIcon);
private JButton zoomOutTenButton = new JButton(zoomOutTenIcon);
/** Vraca defaultni poredak signala */
private JButton defaultButton = new JButton(defaultIcon);
private JButton upButton = new JButton(upIcon);
private JButton downButton = new JButton(downIcon);
private JButton helpButton = new JButton(helpIcon);
private JButton optionsButton = new JButton(optionsIcon);
private JButton okButton = new JButton("Ok");
private JButton defaultTheme = new JButton("DefaultTheme");
private JButton secondTheme = new JButton("SecondTheme");
/* liste */
private DefaultListModel shapes = new DefaultListModel();
private JList listShapes = new JList(shapes);
private DefaultListModel components = new DefaultListModel();
private JList listComponents = new JList(components);
/* color chooser */
private JColorChooser colorChooser = new JColorChooser();
/* prethodno pritisnuta tipka. Potrebna za kombinaciju dviju tipki */
private char previousKey = 'A';
/** SerialVersionUID */
private static final long serialVersionUID = 2;
/**
* Listener za vertikalni scrollbar koji pomice panel s valnim oblicima i panel
* s imenima signala
*/
private AdjustmentListener verticalScrollListener = new AdjustmentListener()
{
/*
* Postavlja odgovarajuci offset na temelju trenutne vrijednosti scrollbara
* i ponovno crta obje komponente
*/
public void adjustmentValueChanged(AdjustmentEvent event)
{
waves.setVerticalOffset(verticalScrollbar.getValue());
signalNames.setVerticalOffset(verticalScrollbar.getValue());
signalValues.setVerticalOffset(verticalScrollbar.getValue());
waves.repaint();
signalNames.repaint();
signalValues.repaint();
}
};
/**
* Slusa kotacic misa i pomice vertikalni scrollbar
*/
private MouseWheelListener wheelListener = new MouseWheelListener()
{
public void mouseWheelMoved (MouseWheelEvent event)
{
int value = event.getWheelRotation() * 24;
verticalScrollbar.setValue(verticalScrollbar.getValue() + value);
}
};
/**
* Listener horizontalnog scrollbara koji scrolla panel s valnim oblicima i
* panel sa skalom
*/
private AdjustmentListener horizontalScrollListener = new AdjustmentListener()
{
/*
* Postavlja odgovarajuci offset na temelju trenutne vrijednosti scrollbara
* i ponovno crta obje komponente
*/
public void adjustmentValueChanged (AdjustmentEvent event)
{
waves.setHorizontalOffset(horizontalScrollbar.getValue());
scale.setHorizontalOffset(horizontalScrollbar.getValue());
cursorPanel.setOffset(horizontalScrollbar.getValue());
waves.repaint();
scale.repaint();
cursorPanel.repaint();
}
};
/**
* Listener horizontalnog scrollbara koji scrolla panel s valnim oblicima i
* panel sa skalom
*/
private AdjustmentListener signalNamesScrollListener = new AdjustmentListener()
{
/**
* Postavlja odgovarajuci offset na temelju trenutne vrijednosti scrollbara
* i ponovno crta obje komponente
*/
public void adjustmentValueChanged (AdjustmentEvent event)
{
signalNames.setHorizontalOffset(signalNamesScrollbar.getValue());
signalNames.repaint();
}
};
/**
* Listener horizontalnog scrollbara koji scrolla panel s trenutnim vrijednostim ovisno o
* polozaju kursora
*/
private AdjustmentListener signalValuesScrollListener = new AdjustmentListener()
{
/**
* Postavlja odgovarajuci offset na temelju trenutne vrijednosti scrollbara
* i ponovno crta obje komponente
*/
public void adjustmentValueChanged (AdjustmentEvent event)
{
signalValues.setHorizontalOffset(signalValuesScrollbar.getValue());
signalValues.repaint();
}
};
/**
* Listener buttona koji pokrece popup prozor
*/
private ActionListener showNavigation = new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
popup.show(cp, 350, 55);
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Otvara help popup
*/
private ActionListener showHelp = new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
popupHelp.show(cp, 200, 55);
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Otvara options popup
*/
private ActionListener showOptions = new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
optionsPopup.show(cp, 420, 55);
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Lista u option panelu
*/
private ListSelectionListener listListener = new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent event)
{
if (event.getSource().equals(listComponents))
{
listShapes.clearSelection();
}
else
{
listComponents.clearSelection();
}
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Promjena boje u options panelu
*/
private ActionListener okListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (listComponents.isSelectionEmpty() && listShapes.isSelectionEmpty())
{
return;
}
/* postavi index na custom boje */
themeColor.setThemeIndex(0);
int index;
/* ako je selektirana lista s komponentama */
if (!listComponents.isSelectionEmpty())
{
index = listComponents.getSelectedIndex();
switch (index)
{
case 0 :
themeColor.setSignalNames(colorChooser.getColor());
signalNames.repaint();
break;
case 1 :
themeColor.setWaves(colorChooser.getColor());
waves.repaint();
break;
case 2 :
themeColor.setScale(colorChooser.getColor());
scale.repaint();
break;
case 3:
themeColor.setCursorPanel(colorChooser.getColor());
cursorPanel.repaint();
break;
case 4 :
themeColor.setActiveCursor(colorChooser.getColor());
waves.repaint();
cursorPanel.repaint();
break;
case 5 :
themeColor.setPasiveCursor(colorChooser.getColor());
waves.repaint();
cursorPanel.repaint();
break;
case 6 :
themeColor.setLetters(colorChooser.getColor());
signalNames.repaint();
waves.repaint();
scale.repaint();
cursorPanel.repaint();
break;
}
}
else
{
index = listShapes.getSelectedIndex();
switch (index)
{
case 0 :
waves.getShapes()[3].setColor(colorChooser.getColor());
waves.getShapes()[4].setColor(colorChooser.getColor());
waves.getShapes()[5].setColor(colorChooser.getColor());
break;
case 1 :
waves.getShapes()[0].setColor(colorChooser.getColor());
waves.getShapes()[1].setColor(colorChooser.getColor());
waves.getShapes()[2].setColor(colorChooser.getColor());
break;
case 2 :
waves.getShapes()[12].setColor(colorChooser.getColor());
break;
case 3 :
waves.getShapes()[9].setColor(colorChooser.getColor());
waves.getShapes()[10].setColor(colorChooser.getColor());
waves.getShapes()[11].setColor(colorChooser.getColor());
break;
case 4 :
waves.getShapes()[13].setColor(colorChooser.getColor());
waves.getShapes()[14].setColor(colorChooser.getColor());
waves.getShapes()[15].setColor(colorChooser.getColor());
break;
case 5 :
waves.getShapes()[6].setColor(colorChooser.getColor());
waves.getShapes()[7].setColor(colorChooser.getColor());
waves.getShapes()[8].setColor(colorChooser.getColor());
break;
}
waves.repaint();
}
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Theme button listener
*/
private ActionListener themeListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource().equals(defaultTheme))
{
themeColor.setThemeIndex(1);
}
else
{
themeColor.setThemeIndex(2);
}
signalNames.repaint();
waves.repaint();
scale.repaint();
signalValues.repaint();
cursorPanel.repaint();
cp.setBackground(themeColor.getSignalNames());
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Povecava skalu i vrijednost valnih oblika za 10
*/
ActionListener zoomInTenListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
/* ako je veci od 214748364 prekoracio bi max int */
if (scale.getMaximumDurationInPixels() >= 214748364)
{
return;
}
/* postavlja nove vrijednosti i automatski podesava sve parametre */
scale.setDurationsInPixelsAfterZoom(10d);
int offset = horizontalScrollbar.getValue();
/* scrollbar ostaje na istom mjestu */
horizontalScrollbar.setValue(offset * 10);
cursorPanel.setFirstCursorStartPoint(cursorPanel.getFirstCursorStartPoint() * 10);
cursorPanel.setSecondCursorStartPoint(cursorPanel.getSecondCursorStartPoint() * 10);
waves.setFirstCursorStartPoint(waves.getFirstCursorStartPoint() * 10);
waves.setSecondCursorStartPoint(waves.getSecondCursorStartPoint() * 10);
cursorPanel.repaint();
scale.repaint();
waves.repaint();
/* nova maksimalna vrijednost scrollbara */
horizontalScrollbar.setMaximum(scale.getScaleEndPointInPixels());
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Povecava skalu i vrijednost valnih oblika za 2
*/
ActionListener zoomInTwoListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
/** Ako je veci od 1073741824, prekoracio bi max int */
if (scale.getMaximumDurationInPixels() >= 1073741824)
{
return;
}
/* postavlja nove vrijednosti i automatski podesava sve parametre */
scale.setDurationsInPixelsAfterZoom(2d);
int offset = horizontalScrollbar.getValue();
/* scrollbar ostaje na istom mjestu */
horizontalScrollbar.setValue(offset * 2);
cursorPanel.setFirstCursorStartPoint(cursorPanel.getFirstCursorStartPoint() * 2);
cursorPanel.setSecondCursorStartPoint(cursorPanel.getSecondCursorStartPoint() * 2);
waves.setFirstCursorStartPoint(waves.getFirstCursorStartPoint() * 2);
waves.setSecondCursorStartPoint(waves.getSecondCursorStartPoint() * 2);
cursorPanel.repaint();
scale.repaint();
waves.repaint();
/* nova maksimalna vrijednost scrollbara */
horizontalScrollbar.setMaximum(scale.getScaleEndPointInPixels());
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Smanjuje skalu i vrijednost valnih oblika za 10
*/
ActionListener zoomOutTenListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
/* postavlja nove vrijednosti i automatski podesava sve parametre */
scale.setDurationsInPixelsAfterZoom(0.1d);
int offset = horizontalScrollbar.getValue();
/* scrollbar ostaje na istom mjestu */
horizontalScrollbar.setValue(offset / 10);
cursorPanel.setFirstCursorStartPoint(cursorPanel.getFirstCursorStartPoint() / 10);
cursorPanel.setSecondCursorStartPoint(cursorPanel.getSecondCursorStartPoint() / 10);
waves.setFirstCursorStartPoint(waves.getFirstCursorStartPoint() / 10);
waves.setSecondCursorStartPoint(waves.getSecondCursorStartPoint() / 10);
cursorPanel.repaint();
scale.repaint();
waves.repaint();
/* nova maksimalna vrijednost scrollbara */
horizontalScrollbar.setMaximum(scale.getScaleEndPointInPixels());
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Smanjuje skalu i vrijednost valnih oblika za 2
*/
ActionListener zoomOutTwoListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
/* postavlja nove vrijednosti i automatski podesava sve parametre */
scale.setDurationsInPixelsAfterZoom(0.5d);
int offset = horizontalScrollbar.getValue();
/* scrollbar ostaje na istom mjestu */
horizontalScrollbar.setValue(offset / 2);
cursorPanel.setFirstCursorStartPoint(cursorPanel.getFirstCursorStartPoint() / 2);
cursorPanel.setSecondCursorStartPoint(cursorPanel.getSecondCursorStartPoint() / 2);
waves.setFirstCursorStartPoint(waves.getFirstCursorStartPoint() / 2);
waves.setSecondCursorStartPoint(waves.getSecondCursorStartPoint() / 2);
cursorPanel.repaint();
scale.repaint();
waves.repaint();
/* nova maksimalna vrijednost scrollbara */
horizontalScrollbar.setMaximum(scale.getScaleEndPointInPixels());
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Osluskuje 'up' button
*/
private ActionListener upListener = new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
int index = signalNames.getIndex();
boolean isClicked = signalNames.getIsClicked();
/* ako niti jedan signal nije selektiran */
if (!isClicked)
{
return;
}
/* promijeni poredak signala prema gore */
index = results.changeSignalOrderUp(index);
signalNames.setIndex(index);
waves.setIndex(index);
signalValues.setIndex(index);
/* repainta panel s imenima signala i panel s valnim oblicima */
signalNames.repaint();
waves.repaint();
signalValues.repaint();
if (index * 45 <= signalNames.getVerticalOffset())
{
verticalScrollbar.setValue(verticalScrollbar.getValue() - 200);
}
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Slusa 'down' button
*/
private ActionListener downListener = new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
int index = signalNames.getIndex();
boolean isClicked = signalNames.getIsClicked();
/* ako niti jedan signal nije selektiran */
if (!isClicked)
{
return;
}
/* promijeni poredak signala prema dolje */
index = results.changeSignalOrderDown(index);
signalNames.setIndex(index);
waves.setIndex(index);
signalValues.setIndex(index);
/* repainta panel s imenima signala i panel s valnim oblicima */
signalNames.repaint();
waves.repaint();
signalValues.repaint();
if ((index + 1) * 45 + 50 >= signalNames.getHeight() + signalNames.getVerticalOffset())
{
verticalScrollbar.setValue(verticalScrollbar.getValue() + 200);
}
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* slusa 'default' button u popup meniju
*/
private ActionListener defaultOrderListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
/* promijeni natrag na defaultni poredak */
results.setDefaultOrder();
results.setDefaultExpandedSignalNames();
/* postavlja novi objekt imena signala i njihovih vrijednosti */
signalNames.setSignalNames(results.getSignalNames());
waves.setSignalValues(results.getSignalValues());
signalNames.setIndex(0);
waves.setIndex(0);
signalValues.setIndex(0);
/* repainta panel s imenima signala i panel s valnim oblicima */
signalNames.repaint();
waves.repaint();
signalValues.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Mouse listener koji osluskuje pokrete misa i svaki pokret registrira te na
* temelju vrijednosti po X-osi i na temelju trenutnog stanja skale vraca
* preciznu vrijednost
*/
private MouseMotionListener mouseListener = new MouseMotionListener()
{
/**
* Metoda koja upravlja eventom
*/
public void mouseMoved(MouseEvent event)
{
/* trenutni offset + X-vrijednost kurosra misa */
int xValue = event.getX() + horizontalScrollbar.getValue();
/* podijeljeno s 100 jer je scaleStep za 100 piksela */
double value = xValue * scale.getScaleStepInTime() / 100;
textField.setText((Math.round(value * 100000d) / 100000d) + scale.getMeasureUnitName());
/* racuna interval izmedu kursora i trenutne pozicije misa */
double measuredTime = Math.abs(cursorPanel.getSecondValue() - cursorPanel.getFirstValue());
interval.setText((Math.round(measuredTime * 100000d) / 100000d) + scale.getMeasureUnitName());
signalNames.repaint();
}
/**
* Metoda koja upravlja kursorom
*/
public void mouseDragged(MouseEvent event)
{
if (cursorPanel.getActiveCursor() == 1)
{
waves.setFirstCursorStartPoint(event.getX() + waves.getHorizontalOffset());
cursorPanel.setFirstCursorStartPoint(event.getX() + waves.getHorizontalOffset());
}
else
{
waves.setSecondCursorStartPoint(event.getX() + waves.getHorizontalOffset());
cursorPanel.setSecondCursorStartPoint(event.getX() + waves.getHorizontalOffset());
}
int rightBorder = horizontalScrollbar.getValue() + waves.getPanelWidth();
int leftBorder = horizontalScrollbar.getValue();
if (event.getX() + waves.getHorizontalOffset () + 20 >= rightBorder)
{
horizontalScrollbar.setValue(horizontalScrollbar.getValue() + 20);
if (cursorPanel.getActiveCursor() == 1)
{
cursorPanel.setFirstCursorStartPoint(rightBorder - 20);
waves.setFirstCursorStartPoint(rightBorder - 20);
}
else
{
cursorPanel.setSecondCursorStartPoint(rightBorder - 20);
waves.setSecondCursorStartPoint(rightBorder - 20);
}
}
else if (event.getX() + waves.getHorizontalOffset () <
leftBorder && waves.getHorizontalOffset() != 0)
{
horizontalScrollbar.setValue(horizontalScrollbar.getValue() - 20);
if (cursorPanel.getActiveCursor() == 1)
{
cursorPanel.setFirstCursorStartPoint(leftBorder + 20);
waves.setFirstCursorStartPoint(leftBorder + 20);
}
else
{
cursorPanel.setSecondCursorStartPoint(leftBorder + 20);
waves.setSecondCursorStartPoint(leftBorder + 20);
}
}
/* trenutni offset + X-vrijednost kurosra misa */
int xValue;
if (cursorPanel.getActiveCursor() == 1)
{
xValue = cursorPanel.getFirstCursorStartPoint();
}
else
{
xValue = cursorPanel.getSecondCursorStartPoint();
}
/* podijeljeno s 100 jer je scaleStep za 100 piksela */
double value = xValue * scale.getScaleStepInTime() / 100;
textField.setText((Math.round(value * 100000d) / 100000d) + scale.getMeasureUnitName());
if (value <= 0)
{
value = 0;
}
if (cursorPanel.getActiveCursor() == 1)
{
cursorPanel.setFirstString((Math.round(value * 100000d) / 100000d) + scale.getMeasureUnitName());
cursorPanel.setFirstValue((Math.round(value * 100000d) / 100000d));
}
else
{
cursorPanel.setSecondString((Math.round(value * 100000d) / 100000d) + scale.getMeasureUnitName());
cursorPanel.setSecondValue((Math.round(value * 100000d) / 100000d));
}
double measuredTime = Math.abs(cursorPanel.getSecondValue() - cursorPanel.getFirstValue());
interval.setText((Math.round(measuredTime * 100000d) / 100000d) + scale.getMeasureUnitName());
/* trazi trenutni polozaj po tockama promjene */
int index = 0;
int transitionPoint = scale.getDurationInPixels()[0];
if (cursorPanel.getActiveCursor() == 1)
{
while (cursorPanel.getFirstCursorStartPoint() >= transitionPoint)
{
if (index == results.getSignalValues().get(0).length - 1)
{
break;
}
index++;
transitionPoint += scale.getDurationInPixels()[index];
}
}
else
{
while (cursorPanel.getSecondCursorStartPoint() >= transitionPoint)
{
index++;
transitionPoint += scale.getDurationInPixels()[index];
}
}
signalValues.setValueIndex(index);
waves.repaint();
cursorPanel.repaint();
signalValues.repaint();
}
};
/**
* Mouse listener koji pomice kursor na sljedeci/prethodni padajuci/rastuci
* brid
*/
private ActionListener navigateListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (signalNames.getIsClicked())
{
String presentValue;
String previousValue;
String nextValue;
int index = 0;
int transitionPoint = scale.getDurationInPixels()[0];
boolean isFound = false;
if (cursorPanel.getActiveCursor() == 1)
{
while (cursorPanel.getFirstCursorStartPoint() >= transitionPoint)
{
index++;
transitionPoint += scale.getDurationInPixels()[index];
}
}
else
{
while (cursorPanel.getSecondCursorStartPoint() >= transitionPoint)
{
index++;
transitionPoint += scale.getDurationInPixels()[index];
}
}
signalValues.setValueIndex(index - 1);
/* ako se trazi prethodni rastuci */
if (event.getSource().equals(leftUp))
{
for (--index; index >= 1;)
{
presentValue = results.getSignalValues().get(signalNames.getIndex())[index];
previousValue = results.getSignalValues().get(signalNames.getIndex())[--index];
if (presentValue.equals("1") && previousValue.equals("0"))
{
isFound = true;
break;
}
}
}
/* ako se trazi prethodni padajuci */
else if (event.getSource().equals(leftDown))
{
for (--index; index >= 1;)
{
presentValue = results.getSignalValues().get(signalNames.getIndex())[index];
previousValue = results.getSignalValues().get(signalNames.getIndex())[--index];
if (presentValue.equals("0") && previousValue.equals("1"))
{
isFound = true;
break;
}
}
}
/* ako se trazi sljedeci rastuci */
else if (event.getSource().equals(rightUp))
{
for (; index < results.getSignalValues().get(0).length - 1; index++)
{
presentValue = results.getSignalValues().get(signalNames.getIndex())[index];
nextValue = results.getSignalValues().get(signalNames.getIndex())[index + 1];
if (presentValue.equals("0") && nextValue.equals("1"))
{
isFound = true;
break;
}
}
}
/* ako se trazi sljedeci padajuci */
else if (event.getSource().equals(rightDown))
{
for (; index < results.getSignalValues().get(0).length - 1; index++)
{
presentValue = results.getSignalValues().get(signalNames.getIndex())[index];
nextValue = results.getSignalValues().get(signalNames.getIndex())[index + 1];
if (presentValue.equals("1") && nextValue.equals("0"))
{
isFound = true;
break;
}
}
}
if (isFound)
{
double value;
transitionPoint = 0;
for (; index >= 0; index
{
transitionPoint += scale.getDurationInPixels()[index];
}
if (cursorPanel.getActiveCursor() == 1)
{
cursorPanel.setFirstCursorStartPoint(transitionPoint);
waves.setFirstCursorStartPoint(transitionPoint);
value = transitionPoint * scale.getScaleStepInTime() / 100;
cursorPanel.setFirstString((Math.round(value * 100000d) / 100000d) +
scale.getMeasureUnitName());
cursorPanel.setFirstValue((Math.round(value * 100000d) / 100000d));
}
else
{
cursorPanel.setSecondCursorStartPoint(transitionPoint);
waves.setSecondCursorStartPoint(transitionPoint);
value = transitionPoint * scale.getScaleStepInTime() / 100;
cursorPanel.setSecondString((Math.round(value * 100000d) / 100000d) +
scale.getMeasureUnitName());
cursorPanel.setSecondValue((Math.round(value * 100000d) / 100000d));
}
horizontalScrollbar.setValue(transitionPoint - 100);
}
}
cursorPanel.repaint();
waves.repaint();
signalValues.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Mouse listener koji osluskuje klik misa iznad panela s kursorima i
* na temelju podrucja klika mijenja aktivni kursor
*/
private MouseListener mouseCursorListener = new MouseListener()
{
public void mousePressed(MouseEvent event)
{
;
}
public void mouseReleased(MouseEvent event)
{
;
}
public void mouseEntered(MouseEvent event)
{
;
}
public void mouseExited(MouseEvent event)
{
;
}
public void mouseClicked(MouseEvent event)
{
double value = event.getX() + horizontalScrollbar.getValue();
/* provjerava je li kliknut cursor */
if (value >= cursorPanel.getFirstCursorStartPoint() - 5 &&
value <= cursorPanel.getFirstCursorStartPoint() + 5)
{
/* postavi prvi kursor aktivnim */
cursorPanel.setActiveCursor((byte)1);
waves.setActiveCursor((byte)1);
}
else if (value >= cursorPanel.getSecondCursorStartPoint() - 5 &&
value <= cursorPanel.getSecondCursorStartPoint() + 5)
{
/*postavi drugi kursor aktivnim */
cursorPanel.setActiveCursor((byte)2);
waves.setActiveCursor((byte)2);
}
cursorPanel.repaint();
waves.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Mouse listener koji pomice divider1 i mijenja sirinu panela s imenima signala
*/
private MouseMotionListener firstDividerListener = new MouseMotionListener()
{
/**
* Metoda koja upravlja eventom
*/
public void mouseMoved(MouseEvent event)
{
;
}
/**
* Mijenja sirinu panela s imenima signala
*/
public void mouseDragged(MouseEvent event)
{
if (signalNames.getPanelWidth() <= 5 && event.getX() < 0)
{
return;
}
if (signalNames.getPanelWidth() + event.getX() <= 2 ||
signalNames.getPanelWidth() + event.getX() >= 650)
{
return;
}
signalNames.setPanelWidth(event.getX() + signalNames.getPanelWidth());
signalNames.repaint();
cp.doLayout();
}
};
/**
* Mouse listener koji pomice divider2 i mijenja sirinu panela s trenutnim vrijednostima
*/
private MouseMotionListener secondDividerListener = new MouseMotionListener()
{
/**
* Metoda koja upravlja eventom
*/
public void mouseMoved(MouseEvent event)
{
;
}
/**
* Mijenja sirinu panela s imenima signala
*/
public void mouseDragged(MouseEvent event)
{
if (signalValues.getPanelWidth() <= 5 && event.getX() < 0)
{
return;
}
if (signalValues.getPanelWidth() + event.getX() <= 2 ||
signalValues.getPanelWidth() + event.getX() >= 650)
{
return;
}
signalValues.setPanelWidth(event.getX() + signalValues.getPanelWidth());
signalValues.repaint();
cp.doLayout();
}
};
/**
* Mouse listener koji osluskuje klik misa iznad panela s imenima signala i
* panela s trenutnim vrijednostima te na temelju trenutne vrijednosti po X-osi
* mijenja background iznad trenutno oznacenog signala
*/
private MouseListener mouseClickListener = new MouseListener()
{
public void mousePressed(MouseEvent event)
{
;
}
public void mouseReleased(MouseEvent event)
{
;
}
public void mouseEntered(MouseEvent event)
{
;
}
public void mouseExited(MouseEvent event)
{
;
}
public void mouseClicked(MouseEvent event)
{
int mouseButton = event.getButton();
int value = event.getY() + verticalScrollbar.getValue();
int index = 0;
if (mouseButton == 1)
{
/* pronalazi se index signala kojeg treba oznaciti */
while (value % 45 == 0)
{
value -= 1;
}
index = value / 45;
/* postavlja se vrijednost suprotna od one koja je do sada bila */
if (waves.getIndex() == index && waves.getIsClicked() == true)
{
signalNames.setIsClicked(false);
waves.setIsClicked(false);
signalValues.setIsClicked(false);
}
else
{
signalNames.setIsClicked(true);
signalNames.setIndex(index);
waves.setIsClicked(true);
waves.setIndex(index);
signalValues.setIsClicked(true);
signalValues.setIndex(index);
}
Integer defaultVectorIndex = results.getCurrentVectorIndex().get(index);
/* provjerava je li kliknut plusic na bit-vektoru */
if (defaultVectorIndex != -1 && results.getCurrentVectorIndex().indexOf(defaultVectorIndex) == index &&
(event.getX() >= 0 && event.getX() <= 15))
{
if (!results.getExpandedSignalNames().get(defaultVectorIndex))
{
results.getExpandedSignalNames().set(defaultVectorIndex, true);
signalNames.expand(index);
waves.expand(index);
}
else
{
results.getExpandedSignalNames().set(defaultVectorIndex, false);
signalNames.collapse(index);
waves.collapse(index);
}
}
}
signalNames.repaint();
waves.repaint();
cursorPanel.repaint();
signalValues.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Mouse listener koji osluskuje klik misa iznad panela s valnim oblicima
* te na temelju trenutne vrijednosti po X-osi mijenja background
* iznad trenutno oznacenog signala
*/
private MouseListener mouseWaveListener = new MouseListener()
{
public void mousePressed(MouseEvent event)
{
;
}
public void mouseReleased(MouseEvent event)
{
;
}
public void mouseEntered(MouseEvent event)
{
;
}
public void mouseExited(MouseEvent event)
{
;
}
public void mouseClicked(MouseEvent event)
{
int mouseButton = event.getButton();
/*
* Ako je kliknuta desna tipka misa, ili srednja tipka misa,
* trenutni pasivni kursor ce se pomaknuti tocno na mjesto na kojem
* smo kliknuli misem i ostat ce pasivan
*/
if ((mouseButton == 2 || mouseButton == 3) && event.getClickCount() == 1)
{
int xValue = event.getX() + horizontalScrollbar.getValue();
double timeValue = xValue * scale.getScaleStepInTime() / 100;
if (cursorPanel.getActiveCursor() == 1)
{
cursorPanel.setSecondCursorStartPoint(xValue);
waves.setSecondCursorStartPoint(xValue);
cursorPanel.setSecondString((Math.round(timeValue * 100000d) / 100000d) + scale.getMeasureUnitName());
cursorPanel.setSecondValue((Math.round(timeValue * 100000d) / 100000d));
}
else
{
cursorPanel.setFirstCursorStartPoint(xValue);
waves.setFirstCursorStartPoint(xValue);
cursorPanel.setFirstString((Math.round(timeValue * 100000d) / 100000d) + scale.getMeasureUnitName());
cursorPanel.setFirstValue((Math.round(timeValue * 100000d) / 100000d));
}
double measuredTime = Math.abs(cursorPanel.getSecondValue() - cursorPanel.getFirstValue());
interval.setText((Math.round(measuredTime * 100000d) / 100000d) + scale.getMeasureUnitName());
}
else if (event.getClickCount() == 2)
{
int value = event.getY() + verticalScrollbar.getValue();
int index = 0;
/* pronalazi se index signala kojeg treba oznaciti */
while (value % 45 == 0)
{
value -= 1;
}
index = value / 45;
int xValue = event.getX() + horizontalScrollbar.getValue();
int valueIndex = 0;
int transitionPoint = scale.getDurationInPixels()[0];
while (xValue >= transitionPoint)
{
if (valueIndex == results.getSignalValues().get(0).length - 1)
{
break;
}
valueIndex++;
transitionPoint += scale.getDurationInPixels()[valueIndex];
}
showValue.show(cp, 610, 47);
currentValue.setText(results.getSignalValues().get(index)[valueIndex]);
}
signalNames.repaint();
waves.repaint();
cursorPanel.repaint();
signalValues.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Listener koji provjerava je li sto upisano u search
*/
private ActionListener searchListener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = search.getText();
boolean isFound = false;
int index = 0;
/* pretrazivanje imena signala */
for (int i = 0; i < results.getSignalNames().size(); i++)
{
if (results.getSignalNames().get(i).toLowerCase().equals(input.toLowerCase()))
{
isFound = true;
index = i;
break;
}
}
/* ako je nasao */
if (isFound)
{
signalNames.setIsClicked(true);
signalNames.setIndex(index);
waves.setIsClicked(true);
waves.setIndex(index);
verticalScrollbar.setValue(index * 45);
}
else
{
search.setText("Not found");
}
signalNames.repaint();
waves.repaint();
/* vraca fokus na kontejner */
cp.requestFocusInWindow();
}
};
/**
* Listener koji resetira search polje kada se klikne na njega
*/
private MouseListener searchClickListener = new MouseListener()
{
public void mousePressed(MouseEvent event)
{
;
}
public void mouseReleased(MouseEvent event)
{
;
}
public void mouseEntered(MouseEvent event)
{
;
}
public void mouseExited(MouseEvent event)
{
;
}
public void mouseClicked(MouseEvent event)
{
search.setText("");
}
};
/**
* Key listener
*/
private KeyListener keyListener = new KeyListener()
{
public void keyTyped(KeyEvent event)
{
char key = event.getKeyChar();
switch (key)
{
case '+' :
zoomInTwoButton.doClick();
break;
case '-' :
zoomOutTwoButton.doClick();
break;
case 's' :
verticalScrollbar.setValue(verticalScrollbar.getValue() + 5);
break;
case 'w' :
verticalScrollbar.setValue(verticalScrollbar.getValue() - 5);
break;
case 'd' :
horizontalScrollbar.setValue(horizontalScrollbar.getValue() + 5);
break;
case 'a' :
horizontalScrollbar.setValue(horizontalScrollbar.getValue() - 5);
break;
case 'b' :
defaultButton.doClick();
break;
case 'k' :
if (previousKey == 'l')
{
rightUp.doClick();
}
else if (previousKey == 'h')
{
leftUp.doClick();
}
break;
case 'j' :
if (previousKey == 'l')
{
rightDown.doClick();
}
else if (previousKey == 'h')
{
leftDown.doClick();
}
break;
case '(' :
zoomInTenButton.doClick();
break;
case ')' :
zoomOutTenButton.doClick();
break;
}
previousKey = key;
}
public void keyPressed(KeyEvent event)
{
int key = event.getKeyCode();
switch (key)
{
case KeyEvent.VK_UP :
verticalScrollbar.setValue(verticalScrollbar.getValue() - 5);
break;
case KeyEvent.VK_DOWN :
verticalScrollbar.setValue(verticalScrollbar.getValue() + 5);
break;
case KeyEvent.VK_RIGHT :
horizontalScrollbar.setValue(horizontalScrollbar.getValue() + 5);
break;
case KeyEvent.VK_LEFT :
horizontalScrollbar.setValue(horizontalScrollbar.getValue() - 5);
break;
case KeyEvent.VK_HOME :
verticalScrollbar.setValue(0);
break;
case KeyEvent.VK_END :
verticalScrollbar.setValue(waves.getPreferredSize().height);
break;
case KeyEvent.VK_PAGE_UP :
verticalScrollbar.setValue(verticalScrollbar.getValue() - signalNames.getPanelHeight());
break;
case KeyEvent.VK_PAGE_DOWN :
verticalScrollbar.setValue(verticalScrollbar.getValue() + signalNames.getPanelHeight());
break;
}
}
public void keyReleased(KeyEvent event)
{
;
}
};
public void init()
{
VcdParser parser = new VcdParser("./src/web/onClient/hr/fer/zemris/vhdllab/applets/simulations/adder2.vcd");
parser.parse();
textField.setEditable(false);
textField.setToolTipText("Value");
search.setText("search signal");
search.addMouseListener(searchClickListener);
search.addActionListener(searchListener);
interval.setText("Interval");
interval.setEditable(false);
interval.setToolTipText("Time-interval between cursor and mouse cursor");
/* rezultati prikazni stringom prenose se GhdlResults klasi */
results = new GhdlResults();
results.parseString(parser.getResultInString());
/* stvara se skala */
scale = new Scale(results, themeColor);
/* panel s imenima signala */
signalNames = new SignalNamesPanel(results, themeColor);
signalNames.addMouseListener(mouseClickListener);
signalNames.addMouseWheelListener(wheelListener);
/* panel s valnim oblicima */
waves = new WaveDrawBoard(results, scale, signalNames.getSignalNameSpringHeight(), themeColor);
waves.addMouseMotionListener(mouseListener);
waves.addMouseListener(mouseWaveListener);
waves.addMouseWheelListener(wheelListener);
/* panel s trenutnim vrijednostima ovisno o kursoru */
signalValues = new SignalValuesPanel(results, themeColor);
signalValues.addMouseListener(mouseClickListener);
signalValues.addMouseWheelListener(wheelListener);
/* panel u kojem klizi kursor */
cursorPanel = new CursorPanel(scale.getScaleEndPointInPixels(),
waves.getHorizontalOffset(), scale.getMeasureUnitName(), themeColor);
cursorPanel.addMouseMotionListener(mouseListener);
cursorPanel.addMouseListener(mouseCursorListener);
/* help panel */
helpPanel = new HelpPanel(waves.getShapes());
/* panel koji razdvaja imena signala i trenutne vrijednosti */
divider1.setPreferredSize(new Dimension(4, scale.getScaleEndPointInPixels()));
divider1.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
divider1.setBackground(themeColor.getDivider());
divider1.addMouseMotionListener(firstDividerListener);
/* panel koji razdvaja trenutne vrijednosti i valne oblike */
divider2.setPreferredSize(new Dimension(4, scale.getScaleEndPointInPixels()));
divider2.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
divider2.setBackground(themeColor.getDivider());
divider2.addMouseMotionListener(secondDividerListener);
/* svi scrollbarovi sadrzani u appletu */
horizontalScrollbar = new JScrollBar(SwingConstants.HORIZONTAL, 0, 0, 0,
scale.getScaleEndPointInPixels());
horizontalScrollbar.addAdjustmentListener(horizontalScrollListener);
verticalScrollbar = new JScrollBar(SwingConstants.VERTICAL, 0, 0, 0,
waves.getPreferredSize().height);
verticalScrollbar.addAdjustmentListener(verticalScrollListener);
signalNamesScrollbar = new JScrollBar(SwingConstants.HORIZONTAL, 0, 0, 0,
signalNames.getMaximumSize().width);
signalNamesScrollbar.addAdjustmentListener(signalNamesScrollListener);
signalValuesScrollbar = new JScrollBar(SwingConstants.HORIZONTAL, 0, 0, 0,
signalValues.getMaximumSize().width);
signalValuesScrollbar.addAdjustmentListener(signalValuesScrollListener);
/*
* Popup prozor koji ce izletjeti na trazenje sljedeceg/prethodnog
* padajuceg/rastuceg brid signala.
*/
rightUp.addActionListener(navigateListener);
leftUp.addActionListener(navigateListener);
rightDown.addActionListener(navigateListener);
leftDown.addActionListener(navigateListener);
rightUp.setToolTipText("Move to next right positive edge");
leftUp.setToolTipText("Move to next left positive edge");
rightDown.setToolTipText("Move to next right negative edge");
leftDown.setToolTipText("Move to next left negative edge");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(new Color(141, 176, 221));
buttonPanel.setLayout(new BoxLayout (buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.add(rightUp);
buttonPanel.add(leftUp);
buttonPanel.add(rightDown);
buttonPanel.add(leftDown);
popup.add(buttonPanel);
/* kraj popup prozora */
/* Popup koji ce izletjeti na dvoklik u panelu s valnim oblicima */
showValue.setPreferredSize(new Dimension(300, 50));
currentValue.setEditable(false);
currentValue.setBackground(themeColor.getSignalNames());
JPanel valuePanel = new JPanel();
valuePanel.setLayout(new BorderLayout());
valuePanel.setBackground(themeColor.getSignalNames());
valuePanel.add(currentValue, BorderLayout.WEST);
JScrollPane scrollPane = new JScrollPane(valuePanel);
showValue.add(scrollPane);
/* kraj popup prozora */
/* toolbar */
JPanel toolbar = new JPanel();
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.LINE_AXIS));
toolbar.setBackground(new Color(141, 176, 221));
zoomInTwoButton.addActionListener(zoomInTwoListener);
zoomOutTwoButton.addActionListener(zoomOutTwoListener);
zoomInTenButton.addActionListener(zoomInTenListener);
zoomOutTenButton.addActionListener(zoomOutTenListener);
defaultButton.addActionListener(defaultOrderListener);
upButton.addActionListener(upListener);
downButton.addActionListener(downListener);
navigateSignals.addActionListener(showNavigation);
helpButton.addActionListener(showHelp);
optionsButton.addActionListener(showOptions);
zoomInTwoButton.setToolTipText("Zoom in by two");
zoomOutTwoButton.setToolTipText("Zoom out by two");
zoomInTenButton.setToolTipText("Zoom in by ten");
zoomOutTenButton.setToolTipText("Zoom out by ten");
defaultButton.setToolTipText("Change to default order");
upButton.setToolTipText("Move signal up");
downButton.setToolTipText("Move signal down");
navigateSignals.setToolTipText("Move to next/previous right/left edge");
optionsButton.setToolTipText("Change current theme/define custom colors");
helpButton.setToolTipText("Help");
toolbar.add(zoomInTwoButton);
toolbar.add(zoomOutTwoButton);
//toolbar.add(zoomInTenButton);
//toolbar.add(zoomOutTenButton);
toolbar.add(upButton);
toolbar.add(downButton);
toolbar.add(defaultButton);
toolbar.add(navigateSignals);
toolbar.add(optionsButton);
toolbar.add(helpButton);
/* kraj toolbara */
/* popup help */
popupHelp.setPreferredSize(new Dimension(500, 600));
popupHelp.add(helpPanel);
/* popup options */
optionsPopup.setPreferredSize(new Dimension(450, 550));
optionsPopup.setBackground(new Color(238, 238, 238));
JPanel labelPanel = new JPanel ();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
JLabel titleComponents = new JLabel("Change applet components color:");
JLabel titleShapes = new JLabel("Change Shapes color:");
labelPanel.add(titleComponents);
labelPanel.add(Box.createRigidArea(new Dimension(25, 0)));
labelPanel.add(titleShapes);
labelPanel.add(Box.createRigidArea(new Dimension(358, 0)));
JPanel listPanel = new JPanel();
listPanel.setBackground(new Color(238, 238, 238));
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.LINE_AXIS));
components.addElement("Signal names background");
components.addElement("Waveforms background");
components.addElement("Scale background");
components.addElement("Cursor background");
components.addElement("Active cursor");
components.addElement("Pasive cursor");
components.addElement("Letters color");
shapes.addElement("One");
shapes.addElement("Zero");
shapes.addElement("Unknown");
shapes.addElement("High impedance");
shapes.addElement("U, L, W and H");
shapes.addElement("Bit-vector");
listComponents.addListSelectionListener(listListener);
listShapes.addListSelectionListener(listListener);
listPanel.add(Box.createRigidArea(new Dimension(7, 0)));
listPanel.add(listComponents);
listPanel.add(Box.createRigidArea(new Dimension(60, 0)));
listPanel.add(listShapes);
listPanel.add(Box.createRigidArea(new Dimension(440, 0)));
JPanel okPanel = new JPanel();
okPanel.setBackground(new Color(238, 238, 238));
okPanel.setLayout(new BoxLayout(okPanel, BoxLayout.LINE_AXIS));
okButton.addActionListener(okListener);
okPanel.add(Box.createRigidArea(new Dimension(5, 0)));
okPanel.add(okButton);
okPanel.add(Box.createRigidArea(new Dimension(120, 0)));
okPanel.add(defaultTheme);
defaultTheme.addActionListener(themeListener);
okPanel.add(Box.createRigidArea(new Dimension(20, 0)));
okPanel.add(secondTheme);
secondTheme.addActionListener(themeListener);
okPanel.add(Box.createRigidArea(new Dimension(418, 0)));
JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(new Color(238, 238, 238));
optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.PAGE_AXIS));
optionsPanel.add(colorChooser);
optionsPanel.add(labelPanel);
optionsPanel.add(Box.createRigidArea(new Dimension(0, 10)));
optionsPanel.add(listPanel);
optionsPanel.add(Box.createRigidArea(new Dimension(0, 20)));
optionsPanel.add(okPanel);
optionsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
optionsPopup.add(optionsPanel);
/* kraj popup optionsa */
/* postavljanje komponenti na applet */
cp = getContentPane();
cp.setFocusable(true);
cp.addKeyListener(keyListener);
cp.setLayout(new WaveLayoutManager());
cp.setBackground(themeColor.getSignalNames());
cp.add(toolbar, "toolbar");
cp.add(textField, "textField");
cp.add(cursorPanel, "cursorPanel");
cp.add(search, "search");
cp.add(interval, "interval");
cp.add(signalNames, "signalNames");
cp.add(divider1, "divider1");
cp.add(divider2, "divider2");
cp.add(signalValues, "signalValues");
cp.add(waves, "waves");
cp.add(scale, "scale");
cp.add(verticalScrollbar, "verticalScrollbar");
cp.add(horizontalScrollbar, "horizontalScrollbar");
cp.add(signalNamesScrollbar, "signalNamesScrollbar");
cp.add(signalValuesScrollbar, "valuesScrollbar");
}
public static void main(String[] args)
{
Console.run(new WaveApplet(), 1024, 1000);
}
}
|
package dr.evomodelxml.continuous;
import dr.evolution.tree.MultivariateTraitTree;
import dr.evomodelxml.treelikelihood.TreeTraitParserUtilities;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Parameter;
import dr.xml.*;
/**
* @author Max Tolkoff
* @author Marc Suchard
*/
public class DataFromTreeTipsParser extends AbstractXMLObjectParser {
public final static String DATA_FROM_TREE_TIPS = "dataFromTreeTips";
public final static String DATA = "data";
public static final String CONTINUOUS = "continuous";
public String getParserName() {
return DATA_FROM_TREE_TIPS;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeTraitParserUtilities utilities = new TreeTraitParserUtilities();
String traitName = (String) xo.getAttribute(TreeTraitParserUtilities.TRAIT_NAME);
MultivariateTraitTree treeModel = (MultivariateTraitTree) xo.getChild(MultivariateTraitTree.class);
TreeTraitParserUtilities.TraitsAndMissingIndices returnValue =
utilities.parseTraitsFromTaxonAttributes(xo, traitName, treeModel, true);
MatrixParameter dataParameter = MatrixParameter.recast(returnValue.traitParameter.getId(),
returnValue.traitParameter);
if (xo.hasChildNamed(TreeTraitParserUtilities.MISSING)) {
Parameter missing = (Parameter) xo.getChild(TreeTraitParserUtilities.MISSING).getChild(Parameter.class);
missing.setDimension(dataParameter.getDimension());
for (int i = 0; i < missing.getDimension(); i++) {
if (returnValue.missingIndices.contains(i)) {
missing.setParameterValue(i, 1);
} else {
missing.setParameterValue(i, 0);
}
}
}
return dataParameter;
}
private static final XMLSyntaxRule[] rules = {
new ElementRule(MultivariateTraitTree.class),
AttributeRule.newStringRule(TreeTraitParserUtilities.TRAIT_NAME),
new ElementRule(TreeTraitParserUtilities.TRAIT_PARAMETER, new XMLSyntaxRule[]{
new ElementRule(Parameter.class)
}),
new ElementRule(TreeTraitParserUtilities.MISSING, new XMLSyntaxRule[]{
new ElementRule(Parameter.class)
}, true),
};
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
@Override
public String getParserDescription() {
return "Takes the data from the tips of a tree and puts it into a MatrixParameter";
}
@Override
public Class getReturnType() {
return MatrixParameter.class;
}
}
|
package dr.inference.trace;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import dr.util.Attribute;
import dr.util.FileHelpers;
import dr.xml.*;
/**
* @author Guy Baele
*/
public class SteppingStoneSamplingAnalysis {
public static final String STEPPING_STONE_SAMPLING_ANALYSIS = "steppingStoneSamplingAnalysis";
public static final String LIKELIHOOD_COLUMN = "likelihoodColumn";
public static final String THETA_COLUMN = "thetaColumn";
public static final String FORMAT = "%5.5g";
private final String logLikelihoodName;
private final List<Double> logLikelihoodSample;
private final List<Double> thetaSample;
private boolean logBayesFactorCalculated = false;
private double logBayesFactor;
private List<Double> maxLogLikelihood;
private List<Double> mlContribution;
private List<Double> orderedTheta;
public SteppingStoneSamplingAnalysis(String logLikelihoodName, List<Double> logLikelihoodSample, List<Double> thetaSample) {
this.logLikelihoodSample = logLikelihoodSample;
this.logLikelihoodName = logLikelihoodName;
this.thetaSample = thetaSample;
}
public double getLogBayesFactor() {
if (!logBayesFactorCalculated) {
calculateBF();
}
return logBayesFactor;
}
private void calculateBF() {
Map<Double, List<Double>> map = new HashMap<Double, List<Double>>();
orderedTheta = new ArrayList<Double>();
//only the log-likelihoods are needed to calculate the marginal likelihood
for (int i = 0; i < logLikelihoodSample.size(); i++) {
if (!map.containsKey(thetaSample.get(i))) {
map.put(thetaSample.get(i), new ArrayList<Double>());
orderedTheta.add(thetaSample.get(i));
}
map.get(thetaSample.get(i)).add(logLikelihoodSample.get(i));
}
//sort into ascending order
Collections.sort(orderedTheta);
//a list with the maxima of the log-likelihood values is constructed
maxLogLikelihood = new ArrayList<Double>();
for (double t : orderedTheta) {
List<Double> values = map.get(t);
maxLogLikelihood.add(Collections.max(values));
}
mlContribution = new ArrayList<Double>();
logBayesFactor = 0.0;
for (int i = 1; i < orderedTheta.size(); i++) {
double contribution = (orderedTheta.get(i) - orderedTheta.get(i-1)) * maxLogLikelihood.get(i-1);
logBayesFactor += contribution;
mlContribution.add(contribution);
//System.out.println(i + ": " + maxLogLikelihood.get(i-1));
}
//System.out.println(logBayesFactor);
for (int i = 1; i < orderedTheta.size(); i++) {
double internalSum = 0.0;
for (int j = 0; j < map.get(orderedTheta.get(i-1)).size(); j++) {
internalSum += Math.exp((orderedTheta.get(i) - orderedTheta.get(i-1)) * (map.get(orderedTheta.get(i-1)).get(j) - maxLogLikelihood.get(i-1)));
}
internalSum /= map.get(orderedTheta.get(i-1)).size();
//System.out.print(orderedTheta.get(i) + "-" + orderedTheta.get(i-1) + ": " + Math.log(internalSum));
logBayesFactor += Math.log(internalSum);
mlContribution.set(i-1, mlContribution.get(i-1) + Math.log(internalSum));
}
logBayesFactorCalculated = true;
}
public String toString() {
double bf = getLogBayesFactor();
StringBuffer sb = new StringBuffer();
sb.append("PathParameter\tMaxPathLikelihood\tMLContribution\n");
for (int i = 0; i < orderedTheta.size(); ++i) {
sb.append(String.format(FORMAT, orderedTheta.get(i)));
sb.append("\t");
sb.append(String.format(FORMAT, maxLogLikelihood.get(i)));
sb.append("\t");
if (i != (orderedTheta.size()-1)) {
sb.append(String.format(FORMAT, mlContribution.get(i)));
}
sb.append("\n");
}
sb.append("\nlog marginal likelihood (using stepping stone sampling) from " + logLikelihoodName + " = " + bf + "\n");
return sb.toString();
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return STEPPING_STONE_SAMPLING_ANALYSIS;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
StringTokenizer tokenFileName = new StringTokenizer(fileName);
int numberOfFiles = tokenFileName.countTokens();
System.out.println(numberOfFiles + " file(s) found with marginal likelihood samples");
try {
String likelihoodName = "";
List sampleLogLikelihood = null;
List sampleTheta = null;
for (int j = 0; j < numberOfFiles; j++) {
File file = new File(tokenFileName.nextToken());
String name = file.getName();
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, name);
fileName = file.getAbsolutePath();
XMLObject cxo = xo.getChild(LIKELIHOOD_COLUMN);
likelihoodName = cxo.getStringAttribute(Attribute.NAME);
cxo = xo.getChild(THETA_COLUMN);
String thetaName = cxo.getStringAttribute(Attribute.NAME);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int burnin = 0;
traces.setBurnIn(burnin);
int traceIndexLikelihood = -1;
int traceIndexTheta = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(likelihoodName)) {
traceIndexLikelihood = i;
}
if (traceName.trim().equals(thetaName)) {
traceIndexTheta = i;
}
}
if (traceIndexLikelihood == -1) {
throw new XMLParseException("Column '" + likelihoodName + "' can not be found for " + getParserName() + " element.");
}
if (traceIndexTheta == -1) {
throw new XMLParseException("Column '" + thetaName + "' can not be found for " + getParserName() + " element.");
}
if (sampleLogLikelihood == null && sampleTheta == null) {
sampleLogLikelihood = traces.getValues(traceIndexLikelihood);
sampleTheta = traces.getValues(traceIndexTheta);
} else {
sampleLogLikelihood.addAll(traces.getValues(traceIndexLikelihood));
sampleTheta.addAll(traces.getValues(traceIndexTheta));
}
}
SteppingStoneSamplingAnalysis analysis = new SteppingStoneSamplingAnalysis(likelihoodName, sampleLogLikelihood, sampleTheta);
System.out.println(analysis.toString());
return analysis;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
|
package org.opennars.main;
import org.apache.commons.lang3.StringUtils;
import org.opennars.entity.*;
import org.opennars.interfaces.Timable;
import org.opennars.interfaces.pub.Reasoner;
import org.opennars.io.ConfigReader;
import org.opennars.io.Narsese;
import org.opennars.io.Parser;
import org.opennars.io.Symbols;
import org.opennars.io.events.AnswerHandler;
import org.opennars.io.events.EventEmitter;
import org.opennars.io.events.EventEmitter.EventObserver;
import org.opennars.io.events.Events;
import org.opennars.io.events.Events.CyclesEnd;
import org.opennars.io.events.Events.CyclesStart;
import org.opennars.io.events.OutputHandler.ERR;
import org.opennars.language.Inheritance;
import org.opennars.language.SetExt;
import org.opennars.language.Tense;
import org.opennars.language.Term;
import org.opennars.operator.Operator;
import org.opennars.plugin.Plugin;
import org.opennars.plugin.perception.SensoryChannel;
import org.opennars.storage.Bag;
import org.opennars.storage.Memory;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opennars.language.SetInt;
import org.opennars.plugin.mental.Emotions;
import org.opennars.plugin.mental.InternalExperience;
/**
* Non-Axiomatic Reasoner
*
* Instances of this represent a reasoner connected to a Memory, and set of Input and Output channels.
*
* All state is contained within Memory. A Nar is responsible for managing I/O channels and executing
* memory operations. It executesa series sof cycles in two possible modes:
* * step mode - controlled by an outside system, such as during debugging or testing
* * thread mode - runs in a pausable closed-loop at a specific maximum framerate.
*
* @author Pei Wang
* @author Patrick Hammer
*/
public class Nar extends SensoryChannel implements Reasoner, Serializable, Runnable {
public Parameters narParameters = new Parameters();
/* System clock, relatively defined to guarantee the repeatability of behaviors */
private Long cycle = new Long(0);
/**
* The information about the version and date of the project.
*/
public static final String VERSION = "Open-NARS v3.0.2";
/**
* The project web sites.
*/
public static final String WEBSITE =
" Open-NARS website: http://code.google.com/p/open-org.opennars/ \n"
+ " NARS website: http://sites.google.com/site/narswang/ \n" +
" Github website: http://github.com/opennars/ \n" +
" IRC: http://webchat.freenode.net/?channels=org.opennars \n";
private transient Thread[] threads = null;
protected transient Map<Term,SensoryChannel> sensoryChannels = new LinkedHashMap<>();
public void addSensoryChannel(final String term, final SensoryChannel channel) {
try {
sensoryChannels.put(new Narsese(this).parseTerm(term), channel);
} catch (final Parser.InvalidInputException ex) {
Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException("Could not add sensory channel.", ex);
}
}
public void SaveToFile(final String name) throws IOException {
final FileOutputStream outStream = new FileOutputStream(name);
final ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(this);
outStream.close();
}
public static Nar LoadFromFile(final String name) throws IOException, ClassNotFoundException,
IllegalAccessException, ParseException, ParserConfigurationException, SAXException,
NoSuchMethodException, InstantiationException, InvocationTargetException {
final FileInputStream inStream = new FileInputStream(name);
final ObjectInputStream stream = new ObjectInputStream(inStream);
final Nar ret = (Nar) stream.readObject();
ret.memory.event = new EventEmitter();
ret.plugins = new ArrayList<>();
ret.sensoryChannels = new LinkedHashMap<>();
List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(ret.usedConfigFilePath, ret, ret.narParameters);
for(Plugin p : pluginsToAdd) {
ret.addPlugin(p);
}
return ret;
}
volatile long minCyclePeriodMS;
/**
* The name of the reasoner
*/
protected String name;
/**
* The memory of the reasoner
*/
public final Memory memory;
public class PluginState implements Serializable {
final public Plugin plugin;
boolean enabled = false;
public PluginState(final Plugin plugin) {
this(plugin,true);
}
public PluginState(final Plugin plugin, final boolean enabled) {
this.plugin = plugin;
setEnabled(enabled);
}
public void setEnabled(final boolean enabled) {
if (this.enabled == enabled) return;
plugin.setEnabled(Nar.this, enabled);
this.enabled = enabled;
emit(Events.PluginsChange.class, plugin, enabled);
}
public boolean isEnabled() {
return enabled;
}
}
protected transient List<PluginState> plugins = new ArrayList<>(); //was CopyOnWriteArrayList
/** Flag for running continuously */
private transient boolean running = false;
/** used by stop() to signal that a running loop should be interrupted */
private transient boolean stopped = false;
private transient boolean threadYield;
public static final String DEFAULTCONFIG_FILEPATH = "./config/defaultConfig.xml";
/** constructs the NAR and loads a config from the default filepath
*
* @param narId inter NARS id of this NARS instance
*/
public Nar(long narId) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException,
ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException {
this(narId, DEFAULTCONFIG_FILEPATH);
}
public String usedConfigFilePath = "";
/** constructs the NAR and loads a config from the filepath
*
* @param narId inter NARS id of this NARS instance
* @param relativeConfigFilePath (relative) path of the XML encoded config file
*/
public Nar(long narId, String relativeConfigFilePath) throws IOException, InstantiationException, InvocationTargetException,
NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException {
List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(relativeConfigFilePath, this, this.narParameters);
final Memory m = new Memory(this.narParameters,
new Bag(narParameters.CONCEPT_BAG_LEVELS, narParameters.CONCEPT_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.NOVEL_TASK_BAG_LEVELS, narParameters.NOVEL_TASK_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.SEQUENCE_BAG_LEVELS, narParameters.SEQUENCE_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.OPERATION_BAG_LEVELS, narParameters.OPERATION_BAG_SIZE, this.narParameters));
this.memory = m;
this.memory.narId = narId;
this.usedConfigFilePath = relativeConfigFilePath;
for(Plugin p : pluginsToAdd) { //adding after memory is constructed, as memory depends on the loaded params!!
this.addPlugin(p);
}
}
/** constructs the NAR and loads a config from the filepath
*
* @param narId inter NARS id of this NARS instance
* @param relativeConfigFilePath (relative) path of the XML encoded config file
* @param parameterOverrides (overwritten) parameters of a Reasoner
*/
public Nar(long narId, String relativeConfigFilePath, final Map<String, Object> parameterOverrides) throws IOException, InstantiationException, InvocationTargetException,
NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException {
List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(relativeConfigFilePath, this, this.narParameters);
overrideParameters(narParameters, parameterOverrides);
final Memory m = new Memory(this.narParameters,
new Bag(narParameters.CONCEPT_BAG_LEVELS, narParameters.CONCEPT_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.NOVEL_TASK_BAG_LEVELS, narParameters.NOVEL_TASK_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.SEQUENCE_BAG_LEVELS, narParameters.SEQUENCE_BAG_SIZE, this.narParameters),
new Bag<>(narParameters.OPERATION_BAG_LEVELS, narParameters.OPERATION_BAG_SIZE, this.narParameters));
this.memory = m;
this.memory.narId = narId;
this.usedConfigFilePath = relativeConfigFilePath;
for(Plugin p : pluginsToAdd) { //adding after memory is constructed, as memory depends on the loaded params!!
this.addPlugin(p);
}
}
/** constructs the NAR and loads a config from the filepath
*
* @param relativeConfigFilePath (relative) path of the XML encoded config file
*/
public Nar(String relativeConfigFilePath) throws IOException, InstantiationException, InvocationTargetException,
NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException {
this(java.util.UUID.randomUUID().getLeastSignificantBits(), relativeConfigFilePath);
}
/** constructs the NAR and loads a config from the filepath
*
* @param relativeConfigFilePath (relative) path of the XML encoded config file
* @param parameterOverrides (overwritten) parameters of a Reasoner
*/
public Nar(String relativeConfigFilePath, final Map<String, Object> parameterOverrides) throws IOException, InstantiationException, InvocationTargetException,
NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException {
this(java.util.UUID.randomUUID().getLeastSignificantBits(), relativeConfigFilePath, parameterOverrides);
}
/** constructs the NAR and loads a config from the default filepath
*
* Assigns a random id to the instance
*/
public Nar() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException {
this(DEFAULTCONFIG_FILEPATH);
}
/** constructs the NAR and loads a config from the default filepath
*
* Assigns a random id to the instance
*
* @param parameterOverrides (overwritten) parameters of a Reasoner
*/
public Nar(final Map<String, Object> parameterOverrides) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException {
this(DEFAULTCONFIG_FILEPATH, parameterOverrides);
}
/**
* Reset the system with an empty memory and reset clock. Called locally.
*/
public void reset() {
cycle = (long) 0;
memory.reset();
}
/**
* Generally the text will consist of Task's to be parsed in Narsese, but
* may contain other commands recognized by the system. The creationTime
* will be set to the current memory cycle time, but may be processed by
* memory later according to the length of the input queue.
*/
private boolean addMultiLineInput(final String text) {
final String[] lines = text.split("\n");
for(final String s : lines) {
addInput(s);
if(!running) {
this.cycle();
}
}
return true;
}
private boolean addCommand(final String text) throws IOException {
if(text.startsWith("**")) {
this.reset();
return true;
}
else
if(text.startsWith("*decisionthreshold=")) { //TODO use reflection for narParameters, allow to set others too
final Double value = Double.valueOf(text.split("decisionthreshold=")[1]);
narParameters.DECISION_THRESHOLD = value.floatValue();
return true;
}
else
if(text.startsWith("*volume=")) {
final Integer value = Integer.valueOf(text.split("volume=")[1]);
narParameters.VOLUME = value;
return true;
}
else
if(text.startsWith("*threads=")) {
final Integer value = Integer.valueOf(text.split("threads=")[1]);
narParameters.THREADS_AMOUNT = value;
return true;
}
else
if(text.startsWith("*save=")) {
final String filename = text.split("save=")[1];
boolean wasRunning = this.isRunning();
if(wasRunning) {
this.stop();
}
this.SaveToFile(filename);
if(wasRunning) {
this.start(this.minCyclePeriodMS);
}
return true;
}
else
if(text.startsWith("*speed=")) {
final Integer value = Integer.valueOf(text.split("speed=")[1]);
this.minCyclePeriodMS = value;
return true;
}
else
if(StringUtils.isNumeric(text)) {
final Integer retVal = Integer.parseInt(text);
if(!running) {
for(int i=0;i<retVal;i++) {
this.cycle();
}
}
return true;
} else {
return false;
}
}
public void addInput(String text) {
text = text.trim();
final Parser narsese = new Narsese(this);
if (text.contains("\n") && addMultiLineInput(text)) {
return;
}
//Ignore any input that is just a comment
if(text.startsWith("\'") || text.startsWith("//") || text.trim().length() <= 0) {
if(text.trim().length() > 0) {
emit(org.opennars.io.events.OutputHandler.ECHO.class, text);
}
return;
}
try {
if(addCommand(text)) {
return;
}
} catch (IOException ex) {
throw new IllegalStateException("I/O command failed: " + text, ex);
}
Task task = null;
try {
task = narsese.parseTask(text);
} catch (final Parser.InvalidInputException e) {
if(MiscFlags.SHOW_INPUT_ERRORS) {
emit(ERR.class, e);
}
if(!MiscFlags.INPUT_ERRORS_CONTINUE) {
throw new IllegalStateException("Invalid input: " + text, e);
}
return;
}
// check if it should go to a sensory channel and dispatch to it instead
if (dispatchToSensoryChannel(task)) {
return;
}
//else input into NARS directly:
this.memory.inputTask(this, task);
}
/**
* dispatches the task to the sensory channel if necessary
* @param task dispatched task
* @return was it dispatched to a sensory channel?
*/
private boolean dispatchToSensoryChannel(Task task) {
final Term t = task.getTerm();
if(t != null) {
Term predicate = null;
if(t instanceof Inheritance) {
predicate = ((Inheritance) t).getPredicate();
} else {
predicate = SetInt.make(new Term("OBSERVED"));
}
if(this.sensoryChannels.containsKey(predicate)) {
// transform to channel-specific coordinate if available.
int channelWidth = this.sensoryChannels.get(predicate).width;
int channelHeight = this.sensoryChannels.get(predicate).height;
if(channelWidth != 0 && channelHeight != 0 && (t instanceof Inheritance) &&
(((Inheritance )t).getSubject() instanceof SetExt)) {
final SetExt subj = (SetExt) ((Inheritance) t).getSubject();
// map to pei's -1 to 1 indexing schema
if(subj.term[0].term_indices == null) {
final String variable = subj.toString().split("\\[")[0];
final String[] vals = subj.toString().split("\\[")[1].split("\\]")[0].split(",");
final double height = Double.parseDouble(vals[0]);
final double width = Double.parseDouble(vals[1]);
final int wval = (int) Math.round((width+1.0f)/2.0f*(this.sensoryChannels.get(predicate).width-1));
final int hval = (int) Math.round(((height+1.0f)/2.0f*(this.sensoryChannels.get(predicate).height-1)));
final String ev = task.sentence.isEternal() ? " " : " :|: ";
final String newInput = "<"+variable+"["+hval+","+wval+"]} --> " + predicate + ">" +
task.sentence.punctuation + ev + task.sentence.truth.toString();
//this.emit(OutputHandler.IN.class, task); too expensive to print each input task, consider vision :)
this.addInput(newInput);
return true;
}
}
this.sensoryChannels.get(predicate).addInput(task, this);
return true;
}
}
return false;
}
public void addInputFile(final String s) {
try (final BufferedReader br = new BufferedReader(new FileReader(s))) {
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) {
//Loading experience file lines, or else just normal input lines
if(line.matches("([A-Za-z])+:(.*)")) {
//Extract creation time:
if(!line.startsWith("IN:")) {
continue; //ignore
}
String[] spl = line.replace("IN:", "").split("\\{");
int creationTime = Integer.parseInt(spl[spl.length-1].split(" :")[0].split("\\|")[0]);
while(this.time() < creationTime) {
this.cycles(1);
}
String lineReconstructed = ""; //the line but without the stamp info at the end
for(int i=0; i<spl.length-1; i++) {
lineReconstructed += spl[i] + "{";
}
lineReconstructed = lineReconstructed.substring(0, lineReconstructed.length()-1);
this.addInput(lineReconstructed.trim());
} else {
this.addInput(line);
}
}
}
} catch (final Exception ex) {
Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException("Loading experience file failed ", ex);
}
}
/** gets a concept if it exists, or returns null if it does not */
public Concept concept(final String concept) throws Parser.InvalidInputException {
return memory.concept(new Narsese(this).parseTerm(concept));
}
public Nar ask(final String termString, final AnswerHandler answered) throws Parser.InvalidInputException {
final Sentence sentenceForNewTask = new Sentence(
new Narsese(this).parseTerm(termString),
Symbols.QUESTION_MARK,
null,
new Stamp(this, memory, Tense.Eternal));
final BudgetValue budget = new BudgetValue(
narParameters.DEFAULT_QUESTION_PRIORITY,
narParameters.DEFAULT_QUESTION_DURABILITY,
1, narParameters);
final Task t = new Task(sentenceForNewTask, budget, Task.EnumType.INPUT);
addInput(t, this);
if (answered!=null) {
answered.start(t, this);
}
return this;
}
public Nar askNow(final String termString, final AnswerHandler answered) throws Parser.InvalidInputException {
final Sentence sentenceForNewTask = new Sentence(
new Narsese(this).parseTerm(termString),
Symbols.QUESTION_MARK,
null,
new Stamp(this, memory, Tense.Present));
final BudgetValue budgetForNewTask = new BudgetValue(
narParameters.DEFAULT_QUESTION_PRIORITY,
narParameters.DEFAULT_QUESTION_DURABILITY,
1, narParameters);
final Task t = new Task(sentenceForNewTask, budgetForNewTask, Task.EnumType.INPUT);
addInput(t, this);
if (answered!=null) {
answered.start(t, this);
}
return this;
}
public Nar addInput(final Task t, final Timable time) {
this.memory.inputTask(this, t);
return this;
}
/** attach event handler */
public void on(final Class c, final EventObserver o) {
memory.event.on(c, o);
}
/** remove event handler */
public void off(final Class c, final EventObserver o) {
memory.event.off(c, o);
}
/** set an event handler. useful for multiple events. */
public void event(final EventObserver e, final boolean enabled, final Class... events) {
memory.event.set(e, enabled, events);
}
public void addPlugin(final Plugin p) {
if(p instanceof SensoryChannel) {
this.addSensoryChannel(((SensoryChannel) p).getName(), (SensoryChannel) p);
}
else
if (p instanceof Operator) {
memory.addOperator((Operator)p);
}
else
if(p instanceof Emotions) {
memory.emotion = (Emotions) p;
}
else
if(p instanceof InternalExperience) {
memory.internalExperience = (InternalExperience) p;
}
final PluginState ps = new PluginState(p);
plugins.add(ps);
emit(Events.PluginsChange.class, p, null);
}
public void removePlugin(final PluginState ps) {
if (plugins.remove(ps)) {
final Plugin p = ps.plugin;
if (p instanceof Operator) {
memory.removeOperator((Operator)p);
}
if (p instanceof SensoryChannel) {
sensoryChannels.remove(p);
}
//TODO sensory channels can be plugins
ps.setEnabled(false);
emit(Events.PluginsChange.class, null, p);
}
}
public List<PluginState> getPlugins() {
return Collections.unmodifiableList(plugins);
}
public void start(final long minCyclePeriodMS) {
this.minCyclePeriodMS = minCyclePeriodMS;
if (threads == null) {
int n_threads = narParameters.THREADS_AMOUNT;
threads = new Thread[n_threads];
for(int i=0;i<n_threads;i++) {
threads[i] = new Thread(this, "Inference"+i);
threads[i].start();
}
}
running = true;
}
public void start() {
start(narParameters.MILLISECONDS_PER_STEP);
}
/**
* Stop the inference process, killing its thread.
*/
public void stop() {
if (threads!=null) {
for(Thread thread : threads) {
thread.interrupt();
}
threads = null;
}
stopped = true;
running = false;
}
/** Execute a fixed number of cycles.*/
public void cycles(final int cycles) {
memory.allowExecution = true;
emit(CyclesStart.class);
final boolean wasRunning = running;
running = true;
stopped = false;
for(int i=0;i<cycles;i++) {
cycle();
}
running = wasRunning;
emit(CyclesEnd.class);
}
/** Main loop executed by the Thread. Should not be called directly. */
@Override public void run() {
stopped = false;
while (running && !stopped) {
emit(CyclesStart.class);
cycle();
emit(CyclesEnd.class);
if (minCyclePeriodMS > 0) {
try {
Thread.sleep(minCyclePeriodMS);
} catch (final InterruptedException e) {
}
}
else if (threadYield) {
Thread.yield();
}
}
}
public void emit(final Class c, final Object... o) {
memory.event.emit(c, o);
}
/**
* A frame, consisting of one or more Nar memory cycles
*/
public void cycle() {
try {
memory.cycle(this);
synchronized (cycle) {
cycle++;
}
}
catch (final Exception e) {
if(MiscFlags.SHOW_REASONING_ERRORS) {
emit(ERR.class, e);
}
if(!MiscFlags.REASONING_ERRORS_CONTINUE) {
throw new IllegalStateException("Reasoning error:\n", e);
}
}
}
@Override
public String toString() {
return memory.toString();
}
public long time() {
if(narParameters.STEPS_CLOCK) {
return cycle;
} else {
return System.currentTimeMillis();
}
}
public boolean isRunning() {
return running;
}
public long getMinCyclePeriodMS() {
return minCyclePeriodMS;
}
/** When b is true, Nar will call Thread.yield each run() iteration that minCyclePeriodMS==0 (no delay).
* This is for improving program responsiveness when Nar is run with no delay.
*/
public void setThreadYield(final boolean b) {
this.threadYield = b;
}
/**
* overrides parameter values by name
* @param parameters (overwritten) parameters of a Reasoner
* @param overrides specific override values by parameter name
*/
private static void overrideParameters(Parameters parameters, Map<String, Object> overrides) {
for (final Map.Entry<String, Object> iOverride : overrides.entrySet()) {
final String propertyName = iOverride.getKey();
final Object value = iOverride.getValue();
try {
final Field fieldOfProperty = Parameters.class.getField(propertyName);
fieldOfProperty.set(parameters, value);
} catch (NoSuchFieldException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
}
}
}
}
|
package edu.washington.escience.myria.operator;
import java.util.Arrays;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.MyriaConstants;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.TupleBatch;
import edu.washington.escience.myria.TupleBatchBuffer;
import edu.washington.escience.myria.TupleBuffer;
import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.column.Column;
import edu.washington.escience.myria.column.ColumnBuilder;
import edu.washington.escience.myria.parallel.QueryExecutionMode;
import edu.washington.escience.myria.parallel.TaskResourceManager;
import edu.washington.escience.myria.util.MyriaArrayUtils;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TIntProcedure;
/**
* This is an implementation of hash equal join. The same as in DupElim, this implementation does not keep the
* references to the incoming TupleBatches in order to get better memory performance.
*/
public final class LocalJoin extends BinaryOperator {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/**
* The result schema.
*/
private Schema outputSchema;
/**
* The names of the output columns.
*/
private final ImmutableList<String> outputColumns;
/**
* The column indices for comparing of child 1.
*/
private final int[] leftCompareIndx;
/**
* The column indices for comparing of child 2.
*/
private final int[] rightCompareIndx;
/**
* A hash table for tuples from child 1. {Hashcode -> List of tuple indices with the same hash code}
*/
private transient TIntObjectMap<TIntList> leftHashTableIndices;
/**
* A hash table for tuples from child 2. {Hashcode -> List of tuple indices with the same hash code}
*/
private transient TIntObjectMap<TIntList> rightHashTableIndices;
/**
* The buffer holding the valid tuples from left.
*/
private transient TupleBuffer hashTable1;
/**
* The buffer holding the valid tuples from right.
*/
private transient TupleBuffer hashTable2;
/**
* The buffer holding the results.
*/
private transient TupleBatchBuffer ans;
/** Which columns in the left child are to be output. */
private final int[] leftAnswerColumns;
/** Which columns in the right child are to be output. */
private final int[] rightAnswerColumns;
/**
* Traverse through the list of tuples with the same hash code.
* */
private final class JoinProcedure implements TIntProcedure {
/**
* Hash table.
* */
private TupleBuffer joinAgainstHashTable;
private int[] inputCmpColumns;
/**
* the columns to compare against.
* */
private int[] joinAgainstCmpColumns;
/**
* row index of the tuple.
* */
private int row;
/**
* input TupleBatch.
* */
private TupleBatch inputTB;
/**
* if the tuple which is comparing against the list of tuples with the same hash code is from left child.
* */
private boolean fromLeft;
@Override
public boolean execute(final int index) {
if (inputTB.tupleEquals(row, joinAgainstHashTable, index, inputCmpColumns, joinAgainstCmpColumns)) {
addToAns(inputTB, row, joinAgainstHashTable, index, fromLeft);
}
return true;
}
};
/**
* Traverse through the list of tuples.
* */
private transient JoinProcedure doJoin;
public LocalJoin(final Operator left, final Operator right, final int[] compareIndx1, final int[] compareIndx2) {
this(null, left, right, compareIndx1, compareIndx2);
}
public LocalJoin(final Operator left, final Operator right, final int[] compareIndx1, final int[] compareIndx2,
final int[] answerColumns1, final int[] answerColumns2) {
this(null, left, right, compareIndx1, compareIndx2, answerColumns1, answerColumns2);
}
public LocalJoin(final List<String> outputColumns, final Operator left, final Operator right,
final int[] compareIndx1, final int[] compareIndx2, final int[] answerColumns1, final int[] answerColumns2) {
super(left, right);
Preconditions.checkArgument(compareIndx1.length == compareIndx2.length);
if (outputColumns != null) {
Preconditions.checkArgument(outputColumns.size() == answerColumns1.length + answerColumns2.length,
"length mismatch between output column names and columns selected for output");
Preconditions.checkArgument(ImmutableSet.copyOf(outputColumns).size() == outputColumns.size(),
"duplicate column names in outputColumns");
this.outputColumns = ImmutableList.copyOf(outputColumns);
} else {
this.outputColumns = null;
}
leftCompareIndx = MyriaArrayUtils.checkSet(compareIndx1);
rightCompareIndx = MyriaArrayUtils.checkSet(compareIndx2);
leftAnswerColumns = MyriaArrayUtils.checkSet(answerColumns1);
rightAnswerColumns = MyriaArrayUtils.checkSet(answerColumns2);
if (left != null && right != null) {
generateSchema();
}
}
public LocalJoin(final List<String> outputColumns, final Operator left, final Operator right,
final int[] compareIndx1, final int[] compareIndx2) {
this(outputColumns, left, right, compareIndx1, compareIndx2, range(left.getSchema().numColumns()), range(right
.getSchema().numColumns()));
}
/**
* Helper function that generates an array of the numbers 0..max-1.
*
* @param max the size of the array.
* @return an array of the numbers 0..max-1.
*/
private static int[] range(final int max) {
int[] ret = new int[max];
for (int i = 0; i < max; ++i) {
ret[i] = i;
}
return ret;
}
/**
* Generate the proper output schema from the parameters.
*/
private void generateSchema() {
final Operator left = getLeft();
final Operator right = getRight();
ImmutableList.Builder<Type> types = ImmutableList.builder();
ImmutableList.Builder<String> names = ImmutableList.builder();
for (int i : leftAnswerColumns) {
types.add(left.getSchema().getColumnType(i));
names.add(left.getSchema().getColumnName(i));
}
for (int i : rightAnswerColumns) {
types.add(right.getSchema().getColumnType(i));
names.add(right.getSchema().getColumnName(i));
}
if (outputColumns != null) {
outputSchema = new Schema(types.build(), outputColumns);
} else {
outputSchema = new Schema(types, names);
}
}
/**
* @param cntTB current TB
* @param row current row
* @param hashTable the buffer holding the tuples to join against
* @param index the index of hashTable, which the cntTuple is to join with
* @param fromLeft if the tuple is from child 1
*/
protected void addToAns(final TupleBatch cntTB, final int row, final TupleBuffer hashTable, final int index,
final boolean fromLeft) {
List<Column<?>> tbColumns = cntTB.getDataColumns();
final int rowInColumn = cntTB.getValidIndices().get(row);
Column<?>[] hashTblColumns = hashTable.getColumns(index);
ColumnBuilder<?>[] hashTblColumnBuilders = null;
if (hashTblColumns == null) {
hashTblColumnBuilders = hashTable.getColumnBuilders(index);
}
int tupleIdx = hashTable.getTupleIndexInContainingTB(index);
if (fromLeft) {
for (int i = 0; i < leftAnswerColumns.length; ++i) {
ans.put(i, tbColumns.get(leftAnswerColumns[i]), rowInColumn);
}
for (int i = 0; i < rightAnswerColumns.length; ++i) {
if (hashTblColumns != null) {
ans.put(i + leftAnswerColumns.length, hashTblColumns[rightAnswerColumns[i]], tupleIdx);
} else {
ans.put(i + leftAnswerColumns.length, hashTblColumnBuilders[rightAnswerColumns[i]], tupleIdx);
}
}
} else {
for (int i = 0; i < leftAnswerColumns.length; ++i) {
if (hashTblColumns != null) {
ans.put(i, hashTblColumns[leftAnswerColumns[i]], tupleIdx);
} else {
ans.put(i, hashTblColumnBuilders[leftAnswerColumns[i]], tupleIdx);
}
}
for (int i = 0; i < rightAnswerColumns.length; ++i) {
ans.put(i + leftAnswerColumns.length, tbColumns.get(rightAnswerColumns[i]), rowInColumn);
}
}
}
@Override
protected void cleanup() throws DbException {
hashTable1 = null;
hashTable2 = null;
ans = null;
}
/**
* In blocking mode, asynchronous EOI semantic may make system hang. Only synchronous EOI semantic works.
*
* @return result TB.
* @throws DbException if any error occurs.
*/
private TupleBatch fetchNextReadySynchronousEOI() throws DbException {
final Operator left = getLeft();
final Operator right = getRight();
TupleBatch nexttb = ans.popFilled();
while (nexttb == null) {
boolean hasnewtuple = false;
if (!left.eos() && !childrenEOI[0]) {
TupleBatch tb = left.nextReady();
if (tb != null) {
hasnewtuple = true;
processChildTB(tb, true);
} else {
if (left.eoi()) {
left.setEOI(false);
childrenEOI[0] = true;
}
}
}
if (!right.eos() && !childrenEOI[1]) {
TupleBatch tb = right.nextReady();
if (tb != null) {
hasnewtuple = true;
processChildTB(tb, false);
} else {
if (right.eoi()) {
right.setEOI(false);
childrenEOI[1] = true;
}
}
}
nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
if (!hasnewtuple) {
break;
}
}
if (nexttb == null) {
if (ans.numTuples() > 0) {
nexttb = ans.popAny();
}
checkEOSAndEOI();
}
return nexttb;
}
@Override
public void checkEOSAndEOI() {
final Operator left = getLeft();
final Operator right = getRight();
if (left.eos() && right.eos()) {
setEOS();
return;
}
// EOS could be used as an EOI
if ((childrenEOI[0] || left.eos()) && (childrenEOI[1] || right.eos())) {
setEOI(true);
Arrays.fill(childrenEOI, false);
}
}
/**
* Recording the EOI status of the children.
*/
private final boolean[] childrenEOI = new boolean[2];
@Override
protected TupleBatch fetchNextReady() throws DbException {
if (!nonBlocking) {
return fetchNextReadySynchronousEOI();
}
TupleBatch nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
if (eoi()) {
return ans.popAny();
}
final Operator left = getLeft();
final Operator right = getRight();
TupleBatch leftTB = null;
TupleBatch rightTB = null;
int numEOS = 0;
int numNoData = 0;
while (numEOS < 2 && numNoData < 2) {
numEOS = 0;
if (left.eos()) {
numEOS += 1;
}
if (right.eos()) {
numEOS += 1;
}
numNoData = numEOS;
leftTB = null;
rightTB = null;
if (!left.eos()) {
leftTB = left.nextReady();
if (leftTB != null) { // data
processChildTB(leftTB, true);
nexttb = ans.popAnyUsingTimeout();
if (nexttb != null) {
return nexttb;
}
} else {
// eoi or eos or no data
if (left.eoi()) {
left.setEOI(false);
childrenEOI[0] = true;
checkEOSAndEOI();
if (eoi()) {
break;
}
} else if (left.eos()) {
numEOS++;
} else {
numNoData++;
}
}
}
if (!right.eos()) {
rightTB = right.nextReady();
if (rightTB != null) {
processChildTB(rightTB, false);
nexttb = ans.popAnyUsingTimeout();
if (nexttb != null) {
return nexttb;
}
} else {
if (right.eoi()) {
right.setEOI(false);
childrenEOI[1] = true;
checkEOSAndEOI();
if (eoi()) {
break;
}
} else if (right.eos()) {
numEOS++;
} else {
numNoData++;
}
}
}
}
Preconditions.checkArgument(numEOS <= 2);
Preconditions.checkArgument(numNoData <= 2);
checkEOSAndEOI();
if (eoi() || eos()) {
nexttb = ans.popAny();
}
return nexttb;
}
@Override
public Schema getSchema() {
if (outputSchema == null) {
generateSchema();
}
return outputSchema;
}
@Override
public void init(final ImmutableMap<String, Object> execEnvVars) throws DbException {
final Operator left = getLeft();
final Operator right = getRight();
leftHashTableIndices = new TIntObjectHashMap<TIntList>();
rightHashTableIndices = new TIntObjectHashMap<TIntList>();
if (outputSchema == null) {
generateSchema();
}
hashTable1 = new TupleBuffer(left.getSchema());
hashTable2 = new TupleBuffer(right.getSchema());
ans = new TupleBatchBuffer(outputSchema);
TaskResourceManager qem = (TaskResourceManager) execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_TASK_RESOURCE_MANAGER);
nonBlocking = qem.getExecutionMode() == QueryExecutionMode.NON_BLOCKING;
doJoin = new JoinProcedure();
}
/**
* The query execution mode is nonBlocking.
*/
private transient boolean nonBlocking = true;
/**
* @param tb the incoming TupleBatch for processing join.
* @param fromLeft if the tb is from left.
*/
protected void processChildTB(final TupleBatch tb, final boolean fromLeft) {
final Operator left = getLeft();
final Operator right = getRight();
if (left.eos() && rightHashTableIndices != null) {
/*
* delete right child's hash table if the left child is EOS, since there will be no incoming tuples from right as
* it will never be probed again.
*/
rightHashTableIndices = null;
hashTable2 = null;
}
if (right.eos() && leftHashTableIndices != null) {
/*
* delete left child's hash table if the right child is EOS, since there will be no incoming tuples from left as
* it will never be probed again.
*/
leftHashTableIndices = null;
hashTable1 = null;
}
TupleBuffer hashTable1Local = null;
TIntObjectMap<TIntList> hashTable1IndicesLocal = null;
TIntObjectMap<TIntList> hashTable2IndicesLocal = null;
if (fromLeft) {
hashTable1Local = hashTable1;
doJoin.joinAgainstHashTable = hashTable2;
hashTable1IndicesLocal = leftHashTableIndices;
hashTable2IndicesLocal = rightHashTableIndices;
doJoin.inputCmpColumns = leftCompareIndx;
doJoin.joinAgainstCmpColumns = rightCompareIndx;
} else {
hashTable1Local = hashTable2;
doJoin.joinAgainstHashTable = hashTable1;
hashTable1IndicesLocal = rightHashTableIndices;
hashTable2IndicesLocal = leftHashTableIndices;
doJoin.inputCmpColumns = rightCompareIndx;
doJoin.joinAgainstCmpColumns = leftCompareIndx;
}
doJoin.fromLeft = fromLeft;
doJoin.inputTB = tb;
for (int row = 0; row < tb.numTuples(); ++row) {
final int cntHashCode = tb.hashCode(row, doJoin.inputCmpColumns);
TIntList tuplesWithHashCode = hashTable2IndicesLocal.get(cntHashCode);
if (tuplesWithHashCode != null) {
doJoin.row = row;
tuplesWithHashCode.forEach(doJoin);
}
if (hashTable1Local != null) {
// only build hash table on two sides if none of the children is EOS
addToHashTable(tb, row, hashTable1Local, hashTable1IndicesLocal, cntHashCode);
}
}
}
/**
* @param tb the source TupleBatch
* @param row the row number to get added to hash table
* @param hashTable the target hash table
* @param hashTable1IndicesLocal hash table 1 indices local
* @param hashCode the hashCode of the tb.
* */
private void addToHashTable(final TupleBatch tb, final int row, final TupleBuffer hashTable,
final TIntObjectMap<TIntList> hashTable1IndicesLocal, final int hashCode) {
final int nextIndex = hashTable.numTuples();
TIntList tupleIndicesList = hashTable1IndicesLocal.get(hashCode);
if (tupleIndicesList == null) {
tupleIndicesList = new TIntArrayList();
hashTable1IndicesLocal.put(hashCode, tupleIndicesList);
}
tupleIndicesList.add(nextIndex);
List<Column<?>> inputColumns = tb.getDataColumns();
int inColumnRow = tb.getValidIndices().get(row);
for (int column = 0; column < tb.numColumns(); column++) {
hashTable.put(column, inputColumns.get(column), inColumnRow);
}
}
}
|
package com.salesforce.dva.argus.entity;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.salesforce.dva.argus.entity.TSDBEntity.ReservedField;
/**
* Time series Metatags object. This entity encapsulates all meta tags for a given timeseries
* The following tag names are reserved. If these reserved tag names are used as metatags, they will be ignored.
*
* <ul>
* <li>metric</li>
* <li>displayName</li>
* <li>units</li>
* </ul>
*
* @author Kunal Nawale (knawale@salesforce.com)
*/
public class MetatagsRecord {
private Map<String, String> _metatags = new HashMap<>(0);
private String _key = null;
/**
* Creates a MetatagsRecord object.
*
* @param metatags A key-value pairs of metatags. Cannot be null or empty.
* @param key A unique identifier to be used while indexing this metatags into a schema db.
*/
public MetatagsRecord(Map<String, String> metatags, String key) {
setMetatags(metatags, key);
}
/**
* Returns an unmodifiable collection of metatags associated with the metric.
*
* @return The metatags for a metric. Will never be null but may be empty.
*/
public Map<String, String> getMetatags() {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : _metatags.entrySet()) {
String key = entry.getKey();
if (!ReservedField.isReservedField(key)) {
result.put(key, entry.getValue());
}
}
return Collections.unmodifiableMap(result);
}
/**
* Replaces the metatags for a metric. Metatags cannot use any of the reserved tag names.
*
*
* @param metatags A key-value pairs of metatags. Cannot be null or empty.
* @param key A unique identifier to be used while indexing this metatags into a schema db.
*/
public void setMetatags(Map<String, String> metatags, String key) {
if (metatags != null) {
TSDBEntity.validateTags(metatags);
_metatags.clear();
_metatags.putAll(metatags);
_key = key;
}
}
/**
* Sets the key identifier
* @param key A unique identifier to be used while indexing this metatags into a schema db.
*/
public void setKey(String key) {
_key = key;
}
/**
* Returns the key identifier
*/
public String getKey() {
return _key;
}
}
|
package edu.wheaton.simulator.statistics;
import java.util.HashMap;
import com.google.common.collect.ImmutableMap;
import edu.wheaton.simulator.entity.Agent;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.entity.Slot;
/**
* This class will create the Snapshots to be put into the Database
*
* @author akonwi and Daniel Gill
*/
public class SnapshotFactory {
public static AgentSnapshot makeAgentSnapshot(Agent agent, Integer step) {
// Sort out with the Agent guys just wtf is up with fields.
return null; // TODO
}
public static SlotSnapshot makeSlotSnapshot(Slot slot, Integer step) {
return null; // TODO
}
public static FieldSnapshot makeFieldSnapshot(String name, String value) {
return new FieldSnapshot(name, value);
}
public static ImmutableMap<String, FieldSnapshot> makeFieldSnapshots(HashMap<String, String> fields) {
ImmutableMap.Builder<String, FieldSnapshot> builder =
new ImmutableMap.Builder<String, FieldSnapshot>();
for (String name : fields.keySet()) {
String value = fields.get(name);
builder.put(name, makeFieldSnapshot(name, value));
}
return builder.build();
}
public static PrototypeSnapshot makePrototypeSnapshot(Prototype prototype,
Integer step) {
return null; // TODO
}
private SnapshotFactory() {
}
}
|
package emergencylanding.k.library.debug;
import java.io.*;
import emergencylanding.k.library.util.LUtils;
public class InputStreamTest {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
String path =
LUtils.getELTop() + "/res/test2.zip/txt.txt" // txt.txt
.replace('/', '\\');
InputStream is = LUtils.getInputStream(path);
System.err.println("Got " + is + " for " + path);
if (is == null) {
System.err.println("No InputStream, no data?");
return;
}
System.err.println("The result text file contains this message:");
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[bis.available()];
bis.read(data);
System.err.println(new String(data));
is.close();
}
}
|
package site;
import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;
/**
* Declares an instance of the asset controller to server $basedir/documentation.
* The goal is to have the external documentation (reference, mojo and javadoc) structured as follows:
* <p/>
* {@literal documentation/reference/0.4}
* {@literal documentation/reference/0.5-SNAPSHOT}
* {@literal documentation/wisdom-maven-plugin/0.4}
* {@literal documentation/wisdom-maven-plugin/0.5-SNAPSHOT}
* {@literal documentation/apidocs/0.4}
* {@literal documentation/apidocs/0.5-SNAPSHOT}
* ...
*/
@Configuration
public class DocConfiguration {
/**
* Declares the instance of resource controller serving resources from 'basedir/documentation'.
*/
public static Instance declareTheDocumentationController() {
return Instance.instance().of("org.wisdom.resources.AssetController")
.named("Documentation-Resources")
.with("path").setto("documentation");
}
}
|
package tigase.server;
import java.util.List;
import java.util.LinkedList;
import java.util.logging.Logger;
import tigase.xml.Element;
import tigase.xmpp.StanzaType;
/**
* Describe enum Command here.
*
*
* Created: Thu Feb 9 20:52:02 2006
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public enum Command {
STREAM_OPENED,
STREAM_CLOSED,
STARTTLS,
GETFEATURES,
GETDISCO,
CLOSE,
GETSTATS,
USER_STATUS,
BROADCAST_TO_ONLINE,
BROADCAST_TO_ALL,
REDIRECT,
VHOSTS_RELOAD,
VHOSTS_UPDATE,
VHOSTS_REMOVE,
OTHER;
public enum Status {
executing,
completed,
canceled,
other;
}
public enum Action {
execute,
cancel,
prev,
next,
complete,
other;
}
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger("tigase.server.Command");
public static final String XMLNS = "http://jabber.org/protocol/commands";
public static Command valueof(String cmd) {
try {
return Command.valueOf(cmd);
} catch (Exception e) {
return OTHER;
} // end of try-catch
}
public Packet getPacket(final String from, final String to,
final StanzaType type, final String id) {
Element elem =
createIqCommand(from, to, type, id, this.toString(), null);
return new Packet(elem);
}
public Packet getPacket(final String from, final String to,
final StanzaType type, final String id, final String data_type) {
Element elem =
createIqCommand(from, to, type, id, this.toString(), data_type);
return new Packet(elem);
}
public static Element createIqCommand(final String from, final String to,
final StanzaType type, final String id, final String node,
final String data_type) {
Element iq = new Element("iq",
new String[] {"from", "to", "type", "id"},
new String[] {from, to, type.toString(), id});
Element command = new Element("command",
new String[] {"xmlns", "node"},
new String[] {XMLNS, node});
if (data_type != null) {
Element x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", data_type});
command.addChild(x);
if (data_type.equals("result")) {
command.setAttribute("status", Status.completed.toString());
}
}
iq.addChild(command);
return iq;
}
public static void setStatus(final Packet packet, final Status status) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
command.setAttribute("status", status.toString());
}
public static void addAction(final Packet packet, final Action action) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element actions = command.getChild("actions");
if (actions == null) {
actions = new Element("actions",
new String[] {Action.execute.toString()},
new String[] {action.toString()});
command.addChild(actions);
}
actions.addChild(new Element(action.toString()));
}
public static Action getAction(final Packet packet) {
String action = packet.getElement().getAttribute("/iq/command", "action");
try {
return Action.valueOf(action);
} catch (Exception e) {
return Action.other;
}
}
public static void addNote(final Packet packet, final String note) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element notes = command.getChild("note");
if (notes == null) {
notes = new Element("note",
new String[] {"type"},
new String[] {"info"});
command.addChild(notes);
}
notes.setCData(note);
}
public static void addFieldValue(final Packet packet,
final String f_name, final String f_value) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new Element[] {new Element("value", f_value)},
new String[] {"var"},
new String[] {f_name});
x.addChild(field);
}
public static void addFieldMultiValue(final Packet packet,
final String f_name, final List<String> f_value) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
if (f_value != null && f_value.size() > 0) {
Element field = new Element("field",
new String[] {"var", "type"},
new String[] {f_name, "text-multi"});
for (String val: f_value) {
Element value = new Element("value", val);
field.addChild(value);
}
x.addChild(field);
}
}
public static void addFieldValue(final Packet packet,
final String f_name, final String f_value, final String label,
final String[] labels, final String[] options) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new Element[] {new Element("value", f_value)},
new String[] {"var", "type", "label"},
new String[] {f_name, "list-single", label});
for (int i = 0; i < labels.length; i++) {
field.addChild(new Element("option",
new Element[] {new Element("value", options[i])},
new String[] {"label"},
new String[] {labels[i]}));
}
x.addChild(field);
}
public static void addFieldValue(final Packet packet,
final String f_name, final String[] f_values, final String label,
final String[] labels, final String[] options) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new String[] {"var", "type", "label"},
new String[] {f_name, "list-multi", label});
for (int i = 0; i < labels.length; i++) {
field.addChild(new Element("option",
new Element[] {new Element("value", options[i])},
new String[] {"label"},
new String[] {labels[i]}));
}
for (int i = 0; i < f_values.length; i++) {
field.addChild(new Element("value", f_values[i]));
}
x.addChild(field);
}
public static void addFieldValue(final Packet packet,
final String f_name, final String f_value, final String label,
final String[] labels, final String[] options, final String type) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new Element[] {new Element("value", f_value)},
new String[] {"var", "type", "label"},
new String[] {f_name, type, label});
for (int i = 0; i < labels.length; i++) {
field.addChild(new Element("option",
new Element[] {new Element("value", options[i])},
new String[] {"label"},
new String[] {labels[i]}));
}
x.addChild(field);
}
public static void addFieldValue(final Packet packet,
final String f_name, final String f_value, final String type) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new Element[] {new Element("value", f_value)},
new String[] {"var", "type"},
new String[] {f_name, type});
x.addChild(field);
}
public static void addFieldValue(final Packet packet,
final String f_name, final String f_value,
final String type, final String label) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
x = new Element("x",
new String[] {"xmlns", "type"},
new String[] {"jabber:x:data", "submit"});
command.addChild(x);
}
Element field = new Element("field",
new Element[] {new Element("value", f_value)},
new String[] {"var", "type", "label"},
new String[] {f_name, type, label});
x.addChild(field);
}
public static void setData(final Packet packet, final Element data) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
command.addChild(data);
}
public static void setData(final Packet packet,
final List<Element> data) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
command.addChildren(data);
}
public static String getFieldValue(final Packet packet,
final String f_name) {
Element iq = packet.getElement();
Element command = iq.getChild("command", XMLNS);
Element x = command.getChild("x", "jabber:x:data");
if (x != null) {
List<Element> children = x.getChildren();
if (children != null) {
for (Element child: children) {
if (child.getName().equals("field")
&& child.getAttribute("var").equals(f_name)) {
return child.getChildCData("/field/value");
}
}
}
}
return null;
}
public static String[] getFieldValues(final Packet packet,
final String f_name) {
Element iq = packet.getElement();
Element command = iq.getChild("command", XMLNS);
Element x = command.getChild("x", "jabber:x:data");
if (x != null) {
List<Element> children = x.getChildren();
if (children != null) {
for (Element child: children) {
if (child.getName().equals("field")
&& child.getAttribute("var").equals(f_name)) {
List<String> values = new LinkedList<String>();
List<Element> val_children = child.getChildren();
for (Element val_child: val_children) {
if (val_child.getName().equals("value")) {
values.add(val_child.getCData());
}
}
return values.toArray(new String[0]);
}
}
}
}
return null;
}
public static boolean removeFieldValue(final Packet packet,
final String f_name) {
Element iq = packet.getElement();
Element command = iq.getChild("command", XMLNS);
Element x = command.getChild("x", "jabber:x:data");
if (x != null) {
List<Element> children = x.getChildren();
if (children != null) {
for (Element child: children) {
if (child.getName().equals("field")
&& child.getAttribute("var").equals(f_name)) {
return x.removeChild(child);
}
}
}
}
return false;
}
public static String getFieldValue(final Packet packet,
final String f_name, boolean debug) {
Element iq = packet.getElement();
log.info("Command iq: " + iq.toString());
Element command = iq.getChild("command", XMLNS);
log.info("Command command: " + command.toString());
Element x = command.getChild("x", "jabber:x:data");
if (x == null) {
log.info("Command x: NULL");
return null;
}
log.info("Command x: " + x.toString());
List<Element> children = x.getChildren();
for (Element child: children) {
log.info("Command form child: " + child.toString());
if (child.getName().equals("field")
&& child.getAttribute("var").equals(f_name)) {
log.info("Command found: field=" + f_name
+ ", value=" + child.getChildCData("/field/value"));
return child.getChildCData("value");
} else {
log.info("Command not found: field=" + f_name
+ ", value=" + child.getChildCData("/field/value"));
}
}
return null;
}
public static List<Element> getData(final Packet packet) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
return command.getChildren();
}
public static Element getData(final Packet packet, final String el_name,
final String xmlns) {
Element iq = packet.getElement();
Element command = iq.getChild("command");
return command.getChild(el_name, xmlns);
}
} // Command
|
package be.ugent.zeus.resto.client.data.services;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import be.ugent.zeus.resto.client.data.NewsItem;
import be.ugent.zeus.resto.client.util.NewsXmlParser;
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class NewsIntentService extends HTTPIntentService {
public NewsIntentService() {
super("NewsIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("blub", "handle intent");
final ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER_EXTRA);
final Bundle bundle = new Bundle();
try {
String xml = fetch(HYDRA_BASE_URL + "versions.xml");
ArrayList<NewsItem> list = new ArrayList<NewsItem>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList nodeList = doc.getFirstChild().getChildNodes();
NewsXmlParser parser = new NewsXmlParser();
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String path = node.getAttributes().getNamedItem("path").getTextContent();
if(path.startsWith("News")) {
try {
Log.i("[NewsIntentService]", "Downloading " + path);
String clubXML = fetch(HYDRA_BASE_URL + path);
// TODO: filter based on user preferences
list.addAll(parser.parse(clubXML));
} catch (Exception e) {
Log.e("[NewIntentService]", e.getMessage());
}
}
}
bundle.putSerializable("newsItemList", list);
} catch (Exception e) {
Log.e("[NewsIntentService]", e.getMessage());
}
receiver.send(STATUS_FINISHED, bundle);
}
}
|
package com.ilis.memoryoptimizer.service;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.view.View;
import android.widget.RemoteViews;
import com.ilis.memoryoptimizer.R;
import com.ilis.memoryoptimizer.activity.MainActivity;
import com.ilis.memoryoptimizer.modle.ProcessInfo;
import com.ilis.memoryoptimizer.util.ProcessInfoProvider;
import com.ilis.memoryoptimizer.util.ToastUtil;
import com.ilis.memoryoptimizer.widget.ProcessManagerWidget;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
public class WidgetUpdateService extends Service {
private static final String ACTION_CLEAR = "com.ilis.memoryoptimizer.CLEAR_ALL";
private AppWidgetManager appWidgetManager;
private Timer timer;
private CleanUpActionReceiver receiver;
private ActivityManager activityManager;
private ComponentName componentName;
private RemoteViews views;
private Disposable disposable;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
appWidgetManager = AppWidgetManager.getInstance(this);
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
componentName = new ComponentName(this, ProcessManagerWidget.class);
initWidgetView();
bindRemoteView();
timer = new Timer();
timer.schedule(new UpdateTimerTask(), 0, 60 * 1000);
receiver = new CleanUpActionReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_CLEAR);
registerReceiver(receiver, filter);
}
@Override
public void onDestroy() {
timer.cancel();
unBindRemoteView();
unregisterReceiver(receiver);
super.onDestroy();
}
@Override
public void onLowMemory() {
cleanupProcesses();
}
private void initWidgetView() {
views = new RemoteViews(getPackageName(), R.layout.widget_manager_view);
Intent intentBroadcast = new Intent(ACTION_CLEAR);
PendingIntent pendingIntentBroadcast
= PendingIntent.getBroadcast(this, 0, intentBroadcast, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.cleanup, pendingIntentBroadcast);
Intent intentActivity = new Intent(this, MainActivity.class);
intentActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntentActivity
= PendingIntent.getActivity(this, 0, intentActivity, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widgetLayout, pendingIntentActivity);
}
private void bindRemoteView() {
disposable = ProcessInfoProvider.getProvider()
.subscribe(new Consumer<List<ProcessInfo>>() {
@Override
public void accept(List<ProcessInfo> processInfos) throws Exception {
int processCount = ProcessInfoProvider.getProcessCount();
String memStatus = ProcessInfoProvider.getSystemMemStatus();
int totalMemory = ProcessInfoProvider.getTotalMemory();
int usedMemory = ProcessInfoProvider.getUsedMemory();
views.setTextViewText(R.id.processCount, String.format(getString(R.string.process_count), processCount));
views.setTextViewText(R.id.memoryStatus, String.format(getString(R.string.memory_status), memStatus));
views.setProgressBar(R.id.availPercent, totalMemory, usedMemory, false);
views.setViewVisibility(R.id.cleanup, View.VISIBLE);
views.setViewVisibility(R.id.clearingView, View.GONE);
try {
appWidgetManager.updateAppWidget(componentName, views);
} catch (RuntimeException e) {
initWidgetView();
System.gc();
}
}
});
}
private void unBindRemoteView() {
if (disposable != null && !disposable.isDisposed()) {
disposable.dispose();
}
}
private void cleanupProcesses() {
Observable
.create(new ObservableOnSubscribe<Void>() {
@Override
public void subscribe(ObservableEmitter<Void> e) throws Exception {
List<ProcessInfo> processInfoList = ProcessInfoProvider.getProcessInfo();
for (ProcessInfo info : processInfoList) {
if (info.getPackName().equals(getPackageName())) {
continue;
}
activityManager.killBackgroundProcesses(info.getPackName());
}
e.onComplete();
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<Void>() {
@Override
public void onNext(Void value) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
ProcessInfoProvider.update();
ToastUtil.showToast(",");
}
});
}
private class UpdateTimerTask extends TimerTask {
@Override
public void run() {
ProcessInfoProvider.update();
}
}
private class CleanUpActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
views.setViewVisibility(R.id.cleanup, View.INVISIBLE);
views.setViewVisibility(R.id.clearingView, View.VISIBLE);
views.setTextViewText(R.id.processCount, "...");
appWidgetManager.updateAppWidget(componentName, views);
cleanupProcesses();
}
}
}
|
package com.wolandsoft.sss.activity.fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.wolandsoft.sss.R;
import com.wolandsoft.sss.entity.SecretEntry;
import com.wolandsoft.sss.storage.SQLiteStorage;
import com.wolandsoft.sss.storage.StorageException;
import com.wolandsoft.sss.util.LogEx;
import java.util.List;
/**
* @author Alexander Shulgin /alexs20@gmail.com/
*/
public class EntriesFragment extends Fragment implements SearchView.OnQueryTextListener {
private SQLiteStorage mStorage;
private SecretEntriesAdapter mRecyclerViewAdapter;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mStorage = new SQLiteStorage(context);
SecretEntriesAdapter.OnSecretEntryClickListener icl = new SecretEntriesAdapter.OnSecretEntryClickListener() {
@Override
public void onSecretEntryClick(SecretEntry entry) {
EntriesFragment.this.onSecretEntryClick(entry);
}
};
mRecyclerViewAdapter = new SecretEntriesAdapter(icl, mStorage);
} catch (StorageException e) {
LogEx.e(e.getMessage(), e);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_entries, container, false);
//init recycler view
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rvEntriesList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mRecyclerViewAdapter);
//connect to add button
FloatingActionButton btnAdd = (FloatingActionButton) view.findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onAddClicked();
}
});
//restore title
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null)
actionBar.setTitle(R.string.app_name);
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//enabling search icon
setHasOptionsMenu(true);
}
private void onAddClicked() {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = EntryFragment.newInstance(null);
transaction.replace(R.id.content_fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void onSecretEntryClick(SecretEntry entry) {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = EntryFragment.newInstance(entry);
transaction.replace(R.id.content_fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onDetach() {
super.onDetach();
if (mStorage != null) {
mStorage.close();
mStorage = null;
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_entries_options_menu, menu);
//attaching search view
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
LogEx.d(newText);
return false;
}
static class SecretEntriesAdapter extends RecyclerView.Adapter<SecretEntriesAdapter.ViewHolder> {
private int mCount;
private SparseArray<SecretEntry> mEntries;
private OnSecretEntryClickListener mOnClickListener;
private SQLiteStorage mStorage;
SecretEntriesAdapter(OnSecretEntryClickListener onClickListener, SQLiteStorage storage) {
mOnClickListener = onClickListener;
mStorage = storage;
mEntries = new SparseArray<>();
try {
mCount = mStorage.count(null);
} catch (StorageException e) {
LogEx.e(e.getMessage(), e);
}
}
@Override
public SecretEntriesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View card = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_entries_include_card, parent, false);
return new ViewHolder(card);
}
@Override
public void onBindViewHolder(SecretEntriesAdapter.ViewHolder holder, int position) {
final SecretEntry entry = getItem(position);
if (entry != null) {
holder.mTxtTitle.setText(entry.get(0).getValue());
holder.mImgIcon.setImageResource(R.mipmap.img24dp_lock_g);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnClickListener.onSecretEntryClick(entry);
}
});
} else {
holder.mTxtTitle.setText(R.string.label_loading_ellipsis);
holder.mImgIcon.setImageResource(R.mipmap.img24dp_wait_g);
}
}
@Override
public int getItemCount() {
return mCount;
}
@Nullable
SecretEntry getItem(int position) {
SecretEntry entry = mEntries.get(position);
//on-demand loading items if not available
if (entry == null) {
new AsyncTask<Integer, Void, Integer>() {
@Override
protected Integer doInBackground(Integer... params) {
try {
int pos = params[0];
List<SecretEntry> entryList = mStorage.find(null, true, pos, 1);
if (!entryList.isEmpty()) {
mEntries.put(pos, entryList.get(0));
return pos;
}
} catch (StorageException e) {
LogEx.e(e.getMessage(), e);
}
return -1;
}
@Override
protected void onPostExecute(Integer pos) {
if (pos != -1) {
SecretEntriesAdapter.this.notifyItemChanged(pos);
}
}
}.execute(position);
}
return mEntries.get(position);
}
interface OnSecretEntryClickListener {
void onSecretEntryClick(SecretEntry entry);
}
class ViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView mTxtTitle;
ImageView mImgIcon;
ViewHolder(View view) {
super(view);
mView = view;
mTxtTitle = (TextView) view.findViewById(R.id.txtTitle);
mImgIcon = (ImageView) view.findViewById(R.id.imgIcon);
}
}
}
}
|
package in.testpress.testpress.models.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import in.testpress.models.greendao.Attempt;
import in.testpress.models.greendao.Chapter;
import in.testpress.models.greendao.Content;
import in.testpress.models.greendao.Course;
import in.testpress.models.greendao.CourseAttempt;
import in.testpress.models.greendao.Exam;
import in.testpress.models.greendao.Video;
import in.testpress.models.greendao.VideoAttempt;
import in.testpress.testpress.models.Category;
import in.testpress.testpress.models.Post;
public class DashboardResponse {
private List<DashboardSection> dashboardSections = new ArrayList<>();
private List<Content> chapterContents = new ArrayList<>();
private List<CourseAttempt> chapterContentAttempts = new ArrayList<>();
private List<Post> posts = new ArrayList<>();
private List<Banner> bannerAds = new ArrayList<>();
private List<LeaderboardItem> leaderboardItems = new ArrayList<>();
private List<Chapter> chapters = new ArrayList<>();
private List<Category> categories = new ArrayList<>();
private List<Course> courses = new ArrayList<>();
private List<UserStats> userStatuses = new ArrayList<>();
private List<Exam> exams = new ArrayList<>();
private List<Attempt> assessments = new ArrayList<>();
private List<VideoAttempt> user_videos = new ArrayList<>();
private HashMap<Long, Chapter> chapterHashMap = new HashMap<>();
private HashMap<Long, Content> contentHashMap = new HashMap<>();
private HashMap<Long, Exam> examHashMap = new HashMap<>();
private HashMap<Long, Video> videoHashMap = new HashMap<>();
public List<DashboardSection> getDashboardSections() {
return dashboardSections;
}
public List<Content> getContents() {
return chapterContents;
}
public List<CourseAttempt> getContentAttempts() {
return chapterContentAttempts;
}
public List<Post> getPosts() {
return posts;
}
public List<Banner> getBanners() {
return bannerAds;
}
public List<LeaderboardItem> getLeaderboardItems() {
return leaderboardItems;
}
public List<Chapter> getChapters() {
return chapters;
}
public List<Category> getCategories() {
return categories;
}
public List<Course> getCourses() {
return courses;
}
public List<UserStats> getUserStatuses() {
return userStatuses;
}
public List<Exam> getExams() {
return exams;
}
public List<Attempt> getAssessments() {
return assessments;
}
public List<VideoAttempt> getUser_videos() {
return user_videos;
}
public HashMap<Long, Chapter> getChapterHashMap() {
if (chapterHashMap.isEmpty()) {
for(Chapter chapter : chapters) {
chapterHashMap.put(chapter.getId(), chapter);
}
}
return chapterHashMap;
}
public HashMap<Long, Content> getContentHashMap() {
if (contentHashMap.isEmpty()) {
for(Content content : chapterContents) {
contentHashMap.put(content.getId(), content);
}
}
return contentHashMap;
}
public HashMap<Long, Exam> getExamHashMap() {
if (examHashMap.isEmpty()) {
for(Exam exam : exams) {
examHashMap.put(exam.getId(), exam);
}
}
return examHashMap;
}
}
|
package org.stepic.droid.view.fragments;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;
import org.stepic.droid.R;
import org.stepic.droid.base.FragmentBase;
import org.stepic.droid.concurrency.tasks.UpdateCourseTask;
import org.stepic.droid.events.instructors.FailureLoadInstructorsEvent;
import org.stepic.droid.events.instructors.OnResponseLoadingInstructorsEvent;
import org.stepic.droid.events.instructors.StartLoadingInstructorsEvent;
import org.stepic.droid.events.joining_course.FailJoinEvent;
import org.stepic.droid.events.joining_course.SuccessJoinEvent;
import org.stepic.droid.model.Course;
import org.stepic.droid.model.CourseProperty;
import org.stepic.droid.model.User;
import org.stepic.droid.model.Video;
import org.stepic.droid.store.operations.DatabaseFacade;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.util.ProgressHelper;
import org.stepic.droid.util.ThumbnailParser;
import org.stepic.droid.view.adapters.CoursePropertyAdapter;
import org.stepic.droid.view.adapters.InstructorAdapter;
import org.stepic.droid.view.custom.LoadingProgressDialog;
import org.stepic.droid.web.UserStepicResponse;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class CourseDetailFragment extends FragmentBase {
public static CourseDetailFragment newInstance(Course course) {
Bundle args = new Bundle();
args.putSerializable(AppConstants.KEY_COURSE_BUNDLE, course);
CourseDetailFragment fragment = new CourseDetailFragment();
fragment.setArguments(args);
return fragment;
}
//can be -1 if address is incorrect
public static CourseDetailFragment newInstance (long courseId) {
Bundle args = new Bundle();
args.putLong(AppConstants.KEY_COURSE_LONG_ID, courseId);
CourseDetailFragment fragment = new CourseDetailFragment();
fragment.setArguments(args);
return fragment;
}
@Bind(R.id.root_view)
View mRootView;
@Bind(R.id.toolbar)
Toolbar mToolbar;
private WebView mIntroView;
private TextView mCourseNameView;
private RecyclerView mInstructorsCarousel;
private ProgressBar mInstructorsProgressBar;
@Bind(R.id.join_course_layout)
View mJoinCourseView;
ProgressDialog mJoinCourseSpinner;
@BindString(R.string.join_course_impossible)
String joinCourseImpossible;
@BindString(R.string.join_course_exception)
String joinCourseException;
@BindString(R.string.join_course_web_exception)
String joinCourseWebException;
@Bind(R.id.list_of_course_property)
ListView mCoursePropertyListView;
@BindDrawable(R.drawable.video_placeholder)
Drawable mVideoPlaceholder;
ImageView mThumbnail;
View mPlayer;
private List<CourseProperty> mCoursePropertyList;
private Course mCourse;
private List<User> mUserList;
private InstructorAdapter mInstructorAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_course_detailed, container, false);
ButterKnife.bind(this, v);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mJoinCourseSpinner = new LoadingProgressDialog(getActivity());
mCourse = (Course) (getArguments().getSerializable(AppConstants.KEY_COURSE_BUNDLE));
mCoursePropertyList = mCoursePropertyResolver.getSortedPropertyList(mCourse);
View footer = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.fragment_course_detailed_footer, null, false);
mCoursePropertyListView.addFooterView(footer);
mInstructorsCarousel = ButterKnife.findById(footer, R.id.instructors_carousel);
mInstructorsProgressBar = ButterKnife.findById(footer, R.id.load_progressbar);
View header = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.fragment_course_detailed_header, null, false);
mCoursePropertyListView.addHeaderView(header);
mIntroView = ButterKnife.findById(header, R.id.intro_video);
mThumbnail = ButterKnife.findById(header, R.id.player_thumbnail);
mPlayer = ButterKnife.findById(header, R.id.player_layout);
mPlayer.setVisibility(View.GONE);
mCourseNameView = ButterKnife.findById(header, R.id.course_name);
mCoursePropertyListView.setAdapter(new CoursePropertyAdapter(getActivity(), mCoursePropertyList));
if (mCourse.getTitle() != null && !mCourse.getTitle().equals("")) {
mCourseNameView.setText(mCourse.getTitle());
} else {
mCourseNameView.setVisibility(View.GONE);
}
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
mIntroView.getLayoutParams().width = width;
mIntroView.getLayoutParams().height = (9 * width) / 16;
getActivity().overridePendingTransition(R.anim.slide_in_from_end, R.anim.slide_out_to_start);
hideSoftKeypad();
setUpIntroVideo();
mUserList = new ArrayList<>();
mInstructorAdapter = new InstructorAdapter(mUserList, getActivity());
mInstructorsCarousel.setAdapter(mInstructorAdapter);
RecyclerView.LayoutManager layoutManager =
new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false);//// TODO: 30.09.15 determine right-to-left-mode
mInstructorsCarousel.setLayoutManager(layoutManager);
}
@Override
public void onStart() {
super.onStart();
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (mCourse.getEnrollment() != 0) {
mJoinCourseView.setVisibility(View.GONE);
} else {
mJoinCourseView.setVisibility(View.VISIBLE);
mJoinCourseView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
joinCourse();
}
});
}
bus.register(this);
fetchInstructors();
}
private void fetchInstructors() {
if (mCourse.getInstructors() != null && mCourse.getInstructors().length != 0) {
bus.post(new StartLoadingInstructorsEvent(mCourse));
mShell.getApi().getUsers(mCourse.getInstructors()).enqueue(new Callback<UserStepicResponse>() {
@Override
public void onResponse(Response<UserStepicResponse> response, Retrofit retrofit) {
if (response.isSuccess()) {
if (response.body() == null) {
bus.post(new FailureLoadInstructorsEvent(mCourse, null));
} else {
bus.post(new OnResponseLoadingInstructorsEvent(mCourse, response, retrofit));
}
} else {
bus.post(new FailureLoadInstructorsEvent(mCourse, null));
}
}
@Override
public void onFailure(Throwable t) {
bus.post(new FailureLoadInstructorsEvent(mCourse, t));
}
});
}
}
private void setUpIntroVideo() {
String urlToVideo;
Video newTypeVideo = mCourse.getIntro_video();
if (newTypeVideo != null && newTypeVideo.getUrls() != null && !newTypeVideo.getUrls().isEmpty()) {
urlToVideo = newTypeVideo.getUrls().get(0).getUrl();
showNewStyleVideo(urlToVideo, newTypeVideo.getThumbnail());
} else {
urlToVideo = mCourse.getIntro();
showOldStyleVideo(urlToVideo);
}
}
private void showNewStyleVideo(final String urlToVideo, String pathThumbnail) {
mIntroView.setVisibility(View.GONE);
if (urlToVideo == null || urlToVideo.equals("") || pathThumbnail == null || pathThumbnail.equals("")) {
mIntroView.setVisibility(View.GONE);
mPlayer.setVisibility(View.GONE);
} else {
setThumbnail(pathThumbnail);
mPlayer.setVisibility(View.VISIBLE);
mPlayer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mShell.getScreenProvider().showVideo(getActivity(), urlToVideo);
}
});
}
}
private void showOldStyleVideo(String urlToVideo) {
mPlayer.setVisibility(View.GONE);
if (urlToVideo == null || urlToVideo.equals("")) {
mIntroView.setVisibility(View.GONE);
mPlayer.setVisibility(View.GONE);
} else {
WebSettings webSettings = mIntroView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setPluginState(WebSettings.PluginState.ON);
mIntroView.setWebChromeClient(new WebChromeClient());
mIntroView.clearFocus();
mRootView.requestFocus();
mIntroView.loadUrl(urlToVideo);
mIntroView.setVisibility(View.VISIBLE);
}
}
@Subscribe
public void onStartLoadingInstructors(StartLoadingInstructorsEvent e) {
if (e.getCourse() != null && mCourse != null & e.getCourse().getCourseId() == mCourse.getCourseId()) {
ProgressHelper.activate(mInstructorsProgressBar);
}
}
@Subscribe
public void onResponseLoadingInstructors(OnResponseLoadingInstructorsEvent e) {
if (e.getCourse() != null && mCourse != null & e.getCourse().getCourseId() == mCourse.getCourseId()) {
List<User> users = e.getResponse().body().getUsers();
mUserList.clear();
mUserList.addAll(users);
mInstructorsCarousel.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
mInstructorsCarousel.getViewTreeObserver().removeOnPreDrawListener(this);
centeringRecycler();
return true;
}
});
mInstructorAdapter.notifyDataSetChanged();
ProgressHelper.dismiss(mInstructorsProgressBar);
}
}
private void centeringRecycler() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int widthOfScreen = size.x;
int widthOfAllItems = mInstructorsCarousel.getMeasuredWidth();
if (widthOfScreen > widthOfAllItems) {
int padding = (int) (widthOfScreen - widthOfAllItems) / 2;
mInstructorsCarousel.setPadding(padding, 0, padding, 0);
}
}
@Subscribe
public void onFinishLoading(FailureLoadInstructorsEvent e) {
if (e.getCourse() != null && mCourse != null & e.getCourse().getCourseId() == mCourse.getCourseId()) {
ProgressHelper.dismiss(mInstructorsProgressBar);
}
}
@Override
public void onPause() {
super.onPause();
mIntroView.onPause();
}
@Override
public void onStop() {
super.onStop();
bus.unregister(this);
}
@Override
public void onDestroyView() {
mIntroView.destroy();
mIntroView = null;
mInstructorAdapter = null;
super.onDestroyView();
mCourse = null;
}
public void finish() {
Intent intent = new Intent();
intent.putExtra(AppConstants.COURSE_ID_KEY, (Parcelable) mCourse);
intent.putExtra(AppConstants.ENROLLMENT_KEY, mCourse.getEnrollment());
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
getActivity().overridePendingTransition(R.anim.slide_in_from_start, R.anim.slide_out_to_end);
}
private void joinCourse() {
mJoinCourseView.setEnabled(false);
ProgressHelper.activate(mJoinCourseSpinner);
mShell.getApi().tryJoinCourse(mCourse).enqueue(new Callback<Void>() {
private final Course localCopy = mCourse;
@Override
public void onResponse(Response<Void> response, Retrofit retrofit) {
if (response.isSuccess()) {
localCopy.setEnrollment((int) localCopy.getCourseId());
UpdateCourseTask updateCourseTask = new UpdateCourseTask(DatabaseFacade.Table.enrolled, localCopy);
updateCourseTask.executeOnExecutor(mThreadPoolExecutor);
UpdateCourseTask updateCourseFeaturedTask = new UpdateCourseTask(DatabaseFacade.Table.featured, localCopy);
updateCourseFeaturedTask.executeOnExecutor(mThreadPoolExecutor);
bus.post(new SuccessJoinEvent(localCopy));
} else {
bus.post(new FailJoinEvent(response));
}
}
@Override
public void onFailure(Throwable t) {
bus.post(new FailJoinEvent());
}
});
}
@Subscribe
public void onSuccessJoin(SuccessJoinEvent e) {
e.getCourse().setEnrollment((int) e.getCourse().getCourseId());
mShell.getScreenProvider().showSections(getActivity(), mCourse);
finish();
ProgressHelper.dismiss(mJoinCourseSpinner);
}
@Subscribe
public void onFailJoin(FailJoinEvent e) {
if (e.getResponse() != null && e.getResponse().code() == 403) {
Toast.makeText(getActivity(), joinCourseWebException, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), joinCourseException,
Toast.LENGTH_LONG).show();
}
ProgressHelper.dismiss(mJoinCourseSpinner);
mJoinCourseView.setEnabled(true);
}
private void setThumbnail(String thumbnail) {
Uri uri = ThumbnailParser.getUriForThumbnail(thumbnail);
Picasso.with(getActivity())
.load(uri)
.placeholder(mVideoPlaceholder)
.error(mVideoPlaceholder)
.into(mThumbnail);
}
}
|
package org.intermine.bio.dataconversion;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.collections.keyvalue.MultiKey;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.SAXParser;
import org.intermine.metadata.StringUtil;
import org.intermine.metadata.Util;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ReferenceList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* DataConverter to parse psi data into items
*
* Experiments and interactions appear in different files, so we have to keep all experiments
* until all interactions are processed.
*
* @author Julie Sullivan
*/
public class PsiConverter extends BioFileConverter
{
private static final Logger LOG = Logger.getLogger(PsiConverter.class);
private static final String PROP_FILE = "psi-intact_config.properties";
private Map<String, String> pubs = new HashMap<String, String>();
private Map<String, Object> experimentNames = new HashMap<String, Object>();
private Map<String, String> terms = new HashMap<String, String>();
private Map<String, String> regions = new HashMap<String, String>();
private String termId = null;
private static final String INTERACTION_TYPE = "physical";
private Map<String, String[]> config = new HashMap<String, String[]>();
private Set<String> taxonIds = null;
private Map<String, String> genes = new HashMap<String, String>();
private Map<MultiKey, Item> interactions = new HashMap<MultiKey, Item>();
private static final String ALIAS_TYPE = "gene name";
private static final String SPOKE_MODEL = "prey"; // don't store if all roles prey
private static final String DEFAULT_IDENTIFIER = "symbol";
private static final String DEFAULT_DATASOURCE = "";
private static final String BINDING_SITE = "MI:0117";
private static final Set<String> INTERESTING_COMMENTS = new HashSet<String>();
protected IdResolver rslv;
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public PsiConverter(ItemWriter writer, Model model) {
super(writer, model, "IntAct", "IntAct interactions data set");
readConfig();
try {
termId = getTerm(BINDING_SITE);
} catch (SAXException e) {
throw new RuntimeException("couldn't save ontology term");
}
}
static {
INTERESTING_COMMENTS.add("exp-modification");
INTERESTING_COMMENTS.add("curation depth");
INTERESTING_COMMENTS.add("library used");
INTERESTING_COMMENTS.add("data-processing");
INTERESTING_COMMENTS.add("comment");
INTERESTING_COMMENTS.add("caution");
INTERESTING_COMMENTS.add("last-imex assigned");
INTERESTING_COMMENTS.add("imex-range assigned");
INTERESTING_COMMENTS.add("imex-range requested");
}
/**
* {@inheritDoc}
*/
@Override
public void process(Reader reader) throws Exception {
// init reslover
if (rslv == null) {
rslv = IdResolverService.getIdResolverByOrganism(taxonIds);
}
PsiHandler handler = new PsiHandler();
try {
SAXParser.parse(new InputSource(reader), handler);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private void readConfig() {
Properties props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream(PROP_FILE));
} catch (IOException e) {
throw new RuntimeException("Problem loading properties '" + PROP_FILE + "'", e);
}
for (Map.Entry<Object, Object> entry: props.entrySet()) {
String key = (String) entry.getKey();
String value = ((String) entry.getValue()).trim();
String[] attributes = key.split("\\.");
if (attributes.length == 0) {
throw new RuntimeException("Problem loading properties '" + PROP_FILE + "' on line "
+ key);
}
String organism = attributes[0];
String[] configs = config.get(organism);
if (configs == null) {
configs = new String[2];
configs[0] = DEFAULT_IDENTIFIER;
configs[1] = DEFAULT_DATASOURCE;
config.put(organism, configs);
}
if ("identifier".equals(attributes[1])) {
configs[0] = value;
} else if ("datasource".equals(attributes[1])) {
configs[1] = value.toLowerCase();
} else {
String msg = "Problem processing properties '" + PROP_FILE + "' on line " + key
+ ". This line has not been processed.";
LOG.error(msg);
}
}
}
/**
* Sets the list of taxonIds that should be imported if using split input files.
*
* @param taxonIds a space-separated list of taxonIds
*/
public void setIntactOrganisms(String taxonIds) {
this.taxonIds = new HashSet<String>(Arrays.asList(StringUtil.split(taxonIds, " ")));
}
/**
* Handles xml file
*/
class PsiHandler extends DefaultHandler
{
private Map<String, ExperimentHolder> experimentIds
= new HashMap<String, ExperimentHolder>();
// current interaction being processed
private InteractionHolder holder = null;
// current experiment being processed
private ExperimentHolder experimentHolder = null;
// current gene being processed
private InteractorHolder interactorHolder = null;
private Item comment = null;
private String experimentId = null, interactorId = null;
private String regionName = null;
private Stack<String> stack = new Stack<String>();
private String attName = null;
private StringBuffer attValue = null;
// intactId to temporary holding object
private Map<String, InteractorHolder> intactIdToHolder
= new HashMap<String, InteractorHolder>();
// per gene - list of identifiers
private Map<String, Set<String>> geneIdentifiers = new HashMap<String, Set<String>>();
/**
* {@inheritDoc}
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
attName = null;
// <experimentList><experimentDescription>
if ("experimentDescription".equals(qName)) {
experimentId = attrs.getValue("id");
// <experimentList><experimentDescription id="2"><names><shortLabel>
} else if ("shortLabel".equals(qName) && "names".equals(stack.peek())
&& stack.search("experimentDescription") == 2) {
attName = "experimentName";
// <experimentList><experimentDescription id="2"><names><fullName>
} else if ("fullName".equals(qName) && "names".equals(stack.peek())
&& stack.search("experimentDescription") == 2) {
attName = "experimentDescr";
//<experimentList><experimentDescription><bibref><xref><primaryRef>
} else if ("primaryRef".equals(qName) && "xref".equals(stack.peek())
&& stack.search("bibref") == 2
&& stack.search("experimentDescription") == 3) {
experimentHolder.setPublication(attrs.getValue("id"));
//<experimentList><experimentDescription><attributeList><attribute>
} else if ("attribute".equals(qName) && "attributeList".equals(stack.peek())
&& stack.search("experimentDescription") == 2) {
String name = attrs.getValue("name");
if (experimentHolder.experiment != null && name != null
&& INTERESTING_COMMENTS.contains(name)) {
comment = createItem("Comment");
comment.setAttribute("type", name);
attName = "experimentAttribute";
}
// <hostOrganismList><hostOrganism ncbiTaxId="9534"><names><fullName>
} else if ("hostOrganism".equals(qName)) {
attName = "hostOrganism";
//<interactionDetectionMethod><xref><primaryRef>
} else if ("primaryRef".equals(qName) && "xref".equals(stack.peek())
&& stack.search("interactionDetectionMethod") == 2) {
String termItemId = getTerm(attrs.getValue("id"));
experimentHolder.setMethod("interactionDetectionMethods", termItemId);
//<participantIdentificationMethod><xref> <primaryRef>
} else if ("primaryRef".equals(qName) && "xref".equals(stack.peek())
&& stack.search("participantIdentificationMethod") == 2) {
String termItemId = getTerm(attrs.getValue("id"));
experimentHolder.setMethod("participantIdentificationMethods", termItemId);
// <interactorList><interactor id="4">
} else if ("interactor".equals(qName) && "interactorList".equals(stack.peek())) {
interactorId = attrs.getValue("id");
// <interactorList><interactor id="4"><names><fullName>F15C11.2</fullName>
} else if (("fullName".equals(qName) || "shortLabel".equals(qName))
&& stack.search("interactor") == 2) {
attName = qName;
// <interactorList><interactor id="4"><xref>
// <secondaryRef db="sgd" dbAc="MI:0484" id="S000006331" secondary="YPR127W"/>
} else if (("primaryRef".equals(qName) || "secondaryRef".equals(qName))
&& stack.search("interactor") == 2 && attrs.getValue("db") != null) {
Util.addToSetMap(geneIdentifiers, attrs.getValue("db").toLowerCase(),
attrs.getValue("id"));
// <interactorList><interactor id="4"><organism ncbiTaxId="7227">
} else if ("organism".equals(qName) && "interactor".equals(stack.peek())) {
String taxId = attrs.getValue("ncbiTaxId");
if (StringUtils.isNotEmpty(taxId) && ((taxonIds == null || taxonIds.isEmpty())
|| taxonIds.contains(taxId))) {
try {
processGene(taxId, interactorId);
} catch (ObjectStoreException e) {
throw new RuntimeException("failed storing gene");
}
}
// reset list of identifiers, this list is only per gene
geneIdentifiers = new HashMap<String, Set<String>>();
// <interactorList><interactor id="4"><names>
// <alias type="locus name" typeAc="MI:0301">HSC82</alias>
} else if ("alias".equals(qName) && "names".equals(stack.peek())
&& stack.search("interactor") == 2) {
String type = attrs.getValue("type");
if (ALIAS_TYPE.equals(type)) {
attName = type;
}
// <interactorList><interactor id="4"><sequence>
} else if ("sequence".equals(qName) && "interactor".equals(stack.peek())) {
attName = "sequence";
//<interactionList><interaction id="1"><names><shortLabel>
} else if ("shortLabel".equals(qName) && "names".equals(stack.peek())
&& stack.search("interaction") == 2) {
attName = "interactionName";
//<interaction><confidenceList><confidence><unit><names><shortLabel>
} else if ("shortLabel".equals(qName) && "names".equals(stack.peek())
&& stack.search("confidence") == 3) {
attName = "confidenceUnit";
//<interactionList><interaction><confidenceList><confidence><value>
} else if ("value".equals(qName) && "confidence".equals(stack.peek())) {
attName = "confidence";
//<interactionList><interaction>
//<participantList><participant id="5"><interactorRef>
} else if ("interactorRef".equals(qName) && "participant".equals(stack.peek())) {
attName = "participantId";
// <participantList><participant id="5"><experimentalRole><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("experimentalRole") == 2) {
attName = "proteinRole";
//<interactionList><interaction><experimentList><experimentRef>
} else if ("experimentRef".equals(qName) && "experimentList".equals(stack.peek())) {
attName = "experimentRef";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><startStatus><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("startStatus") == 2) {
attName = "startStatus";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><endStatus><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("endStatus") == 2) {
attName = "endStatus";
// <featureList><feature id="24"><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("feature") == 2) {
attName = "regionName";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureType><xref><primaryRef db="psi-mi" dbAc="MI:0488" id="MI:0117"
} else if ("primaryRef".equals(qName) && stack.search("featureType") == 2
&& BINDING_SITE.equals(attrs.getValue("id"))
&& interactorHolder != null) {
interactorHolder.isRegionFeature = true;
interactorHolder.regionName1 = regionName;
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><begin position="470"/>
} else if ("begin".equals(qName) && "featureRange".equals(stack.peek())
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.setStart(attrs.getValue("position"));
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><end position="470"/>
} else if ("end".equals(qName) && "featureRange".equals(stack.peek())
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.setEnd(attrs.getValue("position"));
//<interaction><interactionType><names><shortLabel>physical association
} else if ("shortLabel".equals(qName) && stack.search("interactionType") == 2) {
attName = "relationshipType";
}
super.startElement(uri, localName, qName, attrs);
stack.push(qName);
attValue = new StringBuffer();
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
stack.pop();
// <experimentList><experimentDescription><attributeList><attribute/>
// <attribute name="publication-year">2006</attribute>
if (attName != null && "experimentAttribute".equals(attName)
&& "attribute".equals(qName)) {
String s = attValue.toString();
if (comment != null && StringUtils.isNotEmpty(s)) {
processComment(s);
comment = null;
}
// <experimentList><experimentDescription><names><shortLabel>
} else if (attName != null && "experimentName".equals(attName)
&& "shortLabel".equals(qName)) {
String shortLabel = attValue.toString();
if (StringUtils.isNotEmpty(shortLabel)) {
experimentHolder = getExperiment(shortLabel);
experimentIds.put(experimentId, experimentHolder);
experimentHolder.setName(shortLabel);
} else {
LOG.error("Experiment " + experimentId + " doesn't have a shortLabel");
}
// <experimentList><experimentDescription><names><fullName>
} else if (attName != null && "experimentDescr".equals(attName)
&& "fullName".equals(qName)) {
String descr = attValue.toString();
if (StringUtils.isNotEmpty(descr)) {
experimentHolder.setDescription(descr);
}
// <hostOrganismList><hostOrganism ncbiTaxId="9534"><names><fullName>
} else if (attName != null && "hostOrganism".equals(attName)
&& "fullName".equals(qName)) {
// organism must be a string because several entries are in vivo or in vitro, with
// a taxonid of -1 or -2
String hostOrganism = attValue.toString();
if (StringUtils.isNotEmpty(hostOrganism)) {
experimentHolder.setHostOrganism(hostOrganism);
}
// <interactorList><interactor id="4"><names><fullName>
} else if (("fullName".equals(qName) || "shortLabel".equals(qName))
&& stack.search("interactor") == 2) {
String name = attValue.toString();
if (StringUtils.isNotEmpty(name)) {
Util.addToSetMap(geneIdentifiers, qName, name);
}
// <interactorList><interactor id="4"><names><alias>
} else if ("alias".equals(qName)) {
String identifier = attValue.toString();
if (StringUtils.isNotEmpty(identifier)) {
Util.addToSetMap(geneIdentifiers, attName, formatString(identifier));
}
//<interactionList><interaction><participantList><participant id="5"><interactorRef>
} else if ("interactorRef".equals(qName) && "participant".equals(stack.peek())) {
String id = attValue.toString();
interactorHolder = intactIdToHolder.get(id);
if (interactorHolder != null) {
holder.addInteractor(interactorHolder);
} else {
holder.isValid = false;
}
// <interactionList><interaction><names><shortLabel>
} else if ("shortLabel".equals(qName) && attName != null
&& "interactionName".equals(attName)) {
holder = new InteractionHolder(attValue.toString());
//<interactionList><interaction><experimentList><experimentRef>
} else if ("experimentRef".equals(qName) && "experimentList".equals(stack.peek())) {
String experimentRef = attValue.toString();
if (experimentIds.get(experimentRef) != null) {
holder.setExperiment(experimentIds.get(experimentRef));
} else {
LOG.error("Bad experiment: [" + experimentRef + "] of "
+ experimentIds.size() + " experiments");
}
//<interaction><confidenceList><confidence><unit><names><shortLabel>
} else if ("shortLabel".equals(qName) && attName != null
&& "confidenceUnit".equals(attName) && holder != null) {
String shortLabel = attValue.toString();
if (StringUtils.isNotEmpty(shortLabel)) {
holder.confidenceUnit = shortLabel;
}
//<interactionList><interaction><confidenceList><confidence><value>
} else if ("value".equals(qName) && attName != null && "confidence".equals(attName)
&& holder != null) {
if (holder.confidenceUnit.equals("author-confidence")) {
holder.setConfidence(attValue.toString());
}
// <interactionList><interaction><participantList><participant id="5">
// <experimentalRole><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("experimentalRole") == 2
&& interactorHolder != null) {
interactorHolder.role = attValue.toString();
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><startStatus><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("startStatus") == 2
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.startStatus = attValue.toString();
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><endStatus><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("endStatus") == 2
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.endStatus = attValue.toString();
// <featureList><feature id="24"><names><shortLabel>
} else if ("shortLabel".equals(qName) && stack.search("feature") == 2
&& attName != null && "regionName".equals(attName)) {
regionName = attValue.toString();
//<interaction><interactionType><names><shortLabel>physical association
} else if (attName != null && "relationshipType".equals(attName)
&& "shortLabel".equals(qName) && stack.search("interactionType") == 2) {
holder.setRelationshipType(attValue.toString());
// <interactionList><interaction>
} else if ("interaction".equals(qName) && holder != null) {
if (holder.isValid) {
try {
storeAll(holder);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
holder = null;
interactorHolder = null;
}
}
}
private Item getInteraction(String refId, String gene2RefId) throws ObjectStoreException {
MultiKey key = new MultiKey(refId, gene2RefId);
Item interaction = interactions.get(key);
if (interaction == null) {
interaction = createItem("Interaction");
interaction.setReference("participant1", refId);
interaction.setReference("participant2", gene2RefId);
interactions.put(key, interaction);
store(interaction);
}
return interaction;
}
private void storeAll(InteractionHolder h) throws ObjectStoreException {
// for every gene in interaction store interaction pair
for (InteractorHolder gene1Interactor: h.interactors) {
ReferenceList allInteractors = getAllRefIds(h.interactors);
Set<InteractorHolder> gene2Interactors
= new HashSet<InteractorHolder>(h.interactors);
gene2Interactors.remove(gene1Interactor);
// protein interactions may have more than one gene ID (not usually though)
for (String gene1RefId : gene1Interactor.geneRefIds) {
storeDetails(h, gene1Interactor, gene2Interactors, gene1RefId, allInteractors);
}
/* store all experiment-related items */
ExperimentHolder eh = h.eh;
if (!eh.isStored) {
if (eh.comments != null && !eh.comments.isEmpty()) {
eh.experiment.setCollection("comments", eh.comments);
}
store(eh.experiment);
eh.isStored = true;
}
}
}
// get all the gene ref IDs for an interaction
private ReferenceList getAllRefIds(Set<InteractorHolder> allIds) {
ReferenceList allInteractors = new ReferenceList("allInteractors");
for (InteractorHolder ih : allIds) {
// only multiple IDs for proteins
for (String refId : ih.geneRefIds) {
allInteractors.addRefId(refId);
}
}
return allInteractors;
}
private void storeDetails(InteractionHolder h, InteractorHolder gene1Interactor,
Set<InteractorHolder> gene2Interactors, String gene1RefId,
ReferenceList allInteractors)
throws ObjectStoreException {
// for each interaction pair, store details
for (InteractorHolder gene2Interactor : gene2Interactors) {
// interactor (if protein) may have 2 genes
for (String gene2RefId : gene2Interactor.geneRefIds) {
String role1 = gene1Interactor.role;
String role2 = gene2Interactor.role;
if (SPOKE_MODEL.equalsIgnoreCase(role1)
&& SPOKE_MODEL.equalsIgnoreCase(role2)) {
// spoke! not storing prey - prey, only bait - prey
continue;
}
Item interaction = getInteraction(gene1RefId, gene2RefId);
Item interactionDetail = createItem("InteractionDetail");
String shortName = h.shortName;
interactionDetail.setAttribute("name", shortName);
interactionDetail.setAttribute("role1", role1);
interactionDetail.setAttribute("role2", role2);
interactionDetail.setAttribute("type", INTERACTION_TYPE);
if (h.confidence != null) {
interactionDetail.setAttribute("confidence", h.confidence.toString());
}
if (h.confidenceText != null) {
interactionDetail.setAttribute("confidenceText", h.confidenceText);
}
if (StringUtils.isNotEmpty(h.relationshipType)) {
interactionDetail.setAttribute("relationshipType", h.relationshipType);
}
interactionDetail.setReference("experiment", h.eh.experiment.getIdentifier());
interactionDetail.setReference("interaction", interaction);
processRegions(h, interactionDetail, gene1Interactor, shortName, gene1RefId);
interactionDetail.addCollection(allInteractors);
store(interactionDetail);
}
}
}
private void processRegions(InteractionHolder interactionHolder,
Item interactionDetail, InteractorHolder ih, String shortName, String geneRefId)
throws ObjectStoreException {
if (ih.isRegionFeature()) {
String refId = getRegion(ih, interactionDetail.getIdentifier(), shortName,
geneRefId);
interactionDetail.addToCollection("interactingRegions", refId);
}
}
private boolean locationValid(InteractorHolder ih) {
boolean isValid = false;
String start = ih.start;
String end = ih.end;
if (start != null && end != null && (!"0".equals(start) || !"0".equals(end))
&& !start.equals(end)) {
/*
* Per kmr's instructions, or else the bioseg postprocess will fail.
* -- Start needs to be 1 if it is zero
* -- start/end should be switched if start > end.
*/
int c;
try {
Integer a = new Integer(start);
Integer b = new Integer(end);
c = a.compareTo(b);
} catch (NumberFormatException e) {
return false;
}
if (c == 0) {
return false;
} else if (c > 0) {
String tmp = start;
start = end;
end = tmp;
}
if ("0".equals(start)) {
start = "1";
}
ih.start = start;
ih.end = end;
isValid = true;
} else {
isValid = false;
}
return isValid;
}
private void processGene(String taxonId, String intactId)
throws ObjectStoreException, SAXException {
if (config.get(taxonId) == null) {
LOG.error("gene not processed. configuration not found for taxonId: " + taxonId);
return;
}
String field = config.get(taxonId)[0];
// if empty, use gene name
String datasource = config.get(taxonId)[1];
Set<String> identifiers = geneIdentifiers.get(datasource);
Set<String> refIds = new HashSet<String>();
StringBuilder sb = null;
if (identifiers == null || identifiers.isEmpty()) {
LOG.error("gene not processed. no valid identifiers found for " + datasource);
return;
}
for (String identifier : identifiers) {
String newIdentifier = resolveGeneIdentifier(taxonId, datasource, identifier);
if (StringUtils.isNotEmpty(newIdentifier)) {
String refId = storeGene(field, newIdentifier, taxonId);
refIds.add(refId);
if (sb == null) {
sb = new StringBuilder();
sb.append(newIdentifier);
} else {
sb.append("_" + newIdentifier);
}
}
}
if (sb == null) {
return;
}
InteractorHolder ih = intactIdToHolder.get(intactId);
if (ih == null) {
ih = new InteractorHolder(refIds);
ih.identifier = sb.toString();
intactIdToHolder.put(intactId, ih);
} else {
throw new RuntimeException("interactor ID found twice in same file: " + intactId);
}
}
private String resolveGeneIdentifier(String taxonId, String datasource, String id) {
if (rslv != null) {
String identifier = id;
int resCount = rslv.countResolutions(taxonId, identifier);
if (resCount != 1) {
LOG.info("RESOLVER: failed to resolve gene to one identifier, "
+ "ignoring gene: " + identifier + " count: " + resCount + " : "
+ rslv.resolveId(taxonId, identifier));
return null;
}
identifier = rslv.resolveId(taxonId, identifier).iterator().next();
return identifier;
}
return id;
}
private String storeGene(String field, String identifier, String taxonId)
throws SAXException, ObjectStoreException {
String itemId = genes.get(identifier);
if (itemId == null) {
Item item = createItem("Gene");
item.setAttribute(field, identifier);
item.setReference("organism", getOrganism(taxonId));
try {
store(item);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
itemId = item.getIdentifier();
genes.put(identifier, itemId);
}
return itemId;
}
private String getPub(String pubMedId)
throws SAXException {
String itemId = pubs.get(pubMedId);
if (itemId == null) {
Item pub = createItem("Publication");
pub.setAttribute("pubMedId", pubMedId);
itemId = pub.getIdentifier();
pubs.put(pubMedId, itemId);
try {
store(pub);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
return itemId;
}
private ExperimentHolder getExperiment(String name) {
ExperimentHolder eh = (ExperimentHolder) experimentNames.get(name);
if (eh == null) {
eh = new ExperimentHolder(createItem("InteractionExperiment"));
experimentNames.put(name, eh);
}
return eh;
}
private String getRegion(InteractorHolder ih, String interactionRefId,
String interactionName, String geneRefId)
throws ObjectStoreException {
String refId = regions.get(ih.regionName1);
if (refId == null) {
Item region = createItem("InteractionRegion");
refId = region.getIdentifier();
region.setReference("ontologyTerm", termId);
if (ih.startStatus != null) {
region.setAttribute("startStatus", ih.startStatus);
}
if (ih.endStatus != null) {
region.setAttribute("endStatus", ih.endStatus);
}
region.setReference("interaction", interactionRefId);
regions.put(regionName, refId);
if (locationValid(ih)) {
Item location = createItem("Location");
location.setAttribute("start", ih.start);
location.setAttribute("end", ih.end);
location.setReference("locatedOn", geneRefId);
location.setReference("feature", refId);
store(location);
}
store(region);
}
return refId;
}
private void processComment(String s) {
comment.setAttribute("description", s);
try {
store(comment);
} catch (ObjectStoreException e) {
throw new RuntimeException("Couldn't store comment: ", e);
}
experimentHolder.comments.add(comment.getIdentifier());
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char[] ch, int start, int length) {
int st = start;
int l = length;
if (attName != null) {
// DefaultHandler may call this method more than once for a single
// attribute content -> hold text & create attribute in endElement
while (l > 0) {
boolean whitespace = false;
switch(ch[st]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) {
break;
}
++st;
--l;
}
if (l > 0) {
StringBuffer s = new StringBuffer();
s.append(ch, st, l);
attValue.append(s);
}
}
}
/**
* Holder object for ProteinInteraction. Holds all information about an interaction until
* it's verified that all organisms are in the list given.
* @author Julie Sullivan
*/
protected class InteractionHolder
{
private String shortName;
private ExperimentHolder eh;
private Double confidence;
private String confidenceText;
String confidenceUnit;
private Set<InteractorHolder> interactors = new LinkedHashSet<InteractorHolder>();
boolean isValid = true;
private Set<String> regionIds = new HashSet<String>();
private String relationshipType;
/**
* Constructor
* @param shortName name of this interaction
*/
public InteractionHolder(String shortName) {
this.shortName = shortName;
}
/**
*
* @param experimentHolder object holding experiment object
*/
protected void setExperiment(ExperimentHolder experimentHolder) {
this.eh = experimentHolder;
}
/**
*
* @param confidence confidence score for interaction
*/
protected void setConfidence(String confidence) {
try {
this.confidence = new Double(confidence);
} catch (NumberFormatException e) {
confidenceText = (confidenceText != null
? confidenceText + ' ' + confidence : confidence);
}
}
/**
* @param ih object holding interactor
*/
protected void addInteractor(InteractorHolder ih) {
interactors.add(ih);
}
/**
* @param regionId Id of ProteinInteractionRegion object
*/
protected void addRegion(String regionId) {
regionIds.add(regionId);
}
/**
* @param interactionType type of interaction, e.g. physical association
*/
protected void setRelationshipType(String interactionType) {
this.relationshipType = interactionType;
}
}
/**
* Holder object for Interaction. Holds all information about a gene in an
* interaction until it's verified that all organisms are in the list given.
*/
protected class InteractorHolder
{
// collection because some proteins have multiple gene IDs. can't find an example
// though
private Set<String> geneRefIds = new HashSet<String>();
private String role;
private String regionName1; // for storage later
private String startStatus, start;
private String endStatus, end;
private String identifier;
/* we only want to process the binding site feature. this flag is FALSE until
*
* <participantList><participant id="6919"><featureList>
* <feature id="6920"><featureType><xref>
* <primaryRef db="psi-mi" dbAc="MI:0488" id="MI:0117"
* id="MI:0117" (the id for binding site)
*
* then the flag is set to TRUE until </feature>
*/
private boolean isRegionFeature;
/**
* Constructor
* @param refIds list of IDs representing gene objects for this interactor
*/
public InteractorHolder(Set<String> refIds) {
setGeneRefIds(refIds);
}
private void setGeneRefIds(Set<String> geneRefIds) {
this.geneRefIds = geneRefIds;
}
/**
* @return list of IDs that represent the gene objects for this interactor
*/
protected Set<String> getGeneRefIds() {
return geneRefIds;
}
/**
* @param start start position of region
*/
protected void setStart(String start) {
this.start = start;
}
/**
* @param end the end position of the region
*/
protected void setEnd(String end) {
this.end = end;
}
/**
* @return the endStatus
*/
protected String getEndStatus() {
return endStatus;
}
/**
* @param endStatus the endStatus to set
*/
protected void setEndStatus(String endStatus) {
this.endStatus = endStatus;
}
/**
* @return the identifier
*/
protected String getIdentifier() {
return identifier;
}
/**
* @param identifier the identifier to set
*/
protected void setIdentifier(String identifier) {
this.identifier = identifier;
}
/**
* @return the isRegionFeature
*/
protected boolean isRegionFeature() {
return isRegionFeature;
}
/**
* @param isRegionFeature the isRegionFeature to set
*/
protected void setRegionFeature(boolean isRegionFeature) {
this.isRegionFeature = isRegionFeature;
}
/**
* @return the role
*/
protected String getRole() {
return role;
}
/**
* @param role the role to set
*/
protected void setRole(String role) {
this.role = role;
}
/**
* @return the startStatus
*/
protected String getStartStatus() {
return startStatus;
}
/**
* @param startStatus the startStatus to set
*/
protected void setStartStatus(String startStatus) {
this.startStatus = startStatus;
}
/**
* @return the end
*/
protected String getEnd() {
return end;
}
/**
* @return the start
*/
protected String getStart() {
return start;
}
}
/**
* Holder object for ProteinInteraction. Holds all information about an experiment until
* an interaction is verified to have only valid organisms
* @author Julie Sullivan
*/
protected class ExperimentHolder
{
@SuppressWarnings("unused")
private String name, description;
private Item experiment;
private List<String> comments = new ArrayList<String>();
private boolean isStored = false;
/**
* Constructor
* @param experiment experiment where this interaction was observed
*/
public ExperimentHolder(Item experiment) {
this.experiment = experiment;
}
/**
*
* @param name name of experiment
*/
protected void setName(String name) {
experiment.setAttribute("name", name);
this.name = name;
}
/**
* @param description description of experiment
*/
protected void setDescription(String description) {
experiment.setAttribute("description", description);
}
/**
* @param pubMedId of this experiment
* @throws SAXException if publication can't be stored
*/
protected void setPublication(String pubMedId)
throws SAXException {
if (StringUtil.allDigits(pubMedId)) {
String pubRefId = getPub(pubMedId);
experiment.setReference("publication", pubRefId);
}
}
/**
* @param collectionname method
* @param termItemId termID
*/
protected void setMethod(String collectionname, String termItemId) {
experiment.addToCollection(collectionname, termItemId);
}
/**
*
* @param ref name of organism
*/
protected void setHostOrganism(String ref) {
experiment.setAttribute("hostOrganism", ref);
}
}
}
/**
* create and store protein interaction terms
* @param identifier identifier for interaction term
* @return id representing term object
* @throws SAXException if term can't be stored
*/
private String getTerm(String identifier) throws SAXException {
String itemId = terms.get(identifier);
if (itemId == null) {
try {
Item term = createItem("InteractionTerm");
term.setAttribute("identifier", identifier);
itemId = term.getIdentifier();
terms.put(identifier, itemId);
store(term);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
return itemId;
}
private String formatString(String ident) {
String identifier = ident;
if (identifier.startsWith("Dmel_")) {
identifier = identifier.substring(5);
}
if (identifier.startsWith("cg")) {
identifier = "CG" + identifier.substring(2);
}
return identifier;
}
}
|
package gov.nih.nci.calab.dto.particle;
/**
* @author Zeng
*
*/
public class MetalParticleBean extends ParticleBean {
private String core;
private String shell;
private String composition;
private String coating;
public MetalParticleBean() {
}
public String getCore() {
return core;
}
public void setCore(String core) {
this.core = core;
}
public String getShell() {
return shell;
}
public void setShell(String shell) {
this.shell = shell;
}
public String getComposition() {
return composition;
}
public void setComposition(String composition) {
this.composition = composition;
}
public String getCoating() {
return coating;
}
public void setCoating(String coating) {
this.coating = coating;
}
}
|
package gov.nih.nci.eagle.web.struts;
import java.util.List;
import org.apache.struts.validator.ValidatorForm;
public class ClassComparisonForm extends ValidatorForm{
private String [] existingCovariates;
private String [] selectedCovariates;
private String covariate;
private List existingGroups;
private String [] selectedGroups;
private String baseline;
private String analysisName;
private String statisticalMethod;
private String foldChange;
private String pvalue;
private String platform;
public String getAnalysisName() {
return analysisName;
}
public void setAnalysisName(String analysisName) {
this.analysisName = analysisName;
}
public String getBaseline() {
return baseline;
}
public void setBaseline(String baseline) {
this.baseline = baseline;
}
public String[] getExistingCovariates() {
return existingCovariates;
}
public void setExistingCovariates(String[] existingCovariates) {
this.existingCovariates = existingCovariates;
}
public String getCovariate() {
return covariate;
}
public void setCovariate(String covariate) {
this.covariate = covariate;
}
public List getExistingGroups() {
return existingGroups;
}
public void setExistingGroups(List existingGroups) {
this.existingGroups = existingGroups;
}
public String getFoldChange() {
return foldChange;
}
public void setFoldChange(String foldChange) {
this.foldChange = foldChange;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getPvalue() {
return pvalue;
}
public void setPvalue(String pvalue) {
this.pvalue = pvalue;
}
public String[] getSelectedCovariates() {
return selectedCovariates;
}
public void setSelectedCovariates(String[] selectedCovariates) {
this.selectedCovariates = selectedCovariates;
}
public String[] getSelectedGroups() {
return selectedGroups;
}
public void setSelectedGroups(String[] selectedGroups) {
this.selectedGroups = selectedGroups;
}
public String getStatisticalMethod() {
return statisticalMethod;
}
public void setStatisticalMethod(String statisticalMethod) {
this.statisticalMethod = statisticalMethod;
}
}
|
package com.intellij.codeInsight.editorActions;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.lang.jsp.JspxFileViewProvider;
import com.intellij.lexer.StringLiteralLexer;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.jsp.jspJava.JspCodeBlock;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.jsp.el.ELExpressionHolder;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.xml.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import java.util.ArrayList;
import java.util.List;
/**
* @author Mike
*/
public class SelectWordUtil {
static Selectioner[] SELECTIONERS = new Selectioner[]{
new LineCommentSelectioner(),
new LiteralSelectioner(),
new DocCommentSelectioner(),
new ListSelectioner(),
new CodeBlockOrInitializerSelectioner(),
new FinallyBlockSelectioner(),
new MethodOrClassSelectioner(),
new FieldSelectioner(),
new ReferenceSelectioner(),
new DocTagSelectioner(),
new IfStatementSelectioner(),
new TypeCastSelectioner(),
new JavaTokenSelectioner(),
new WordSelectioner(),
new StatementGroupSelectioner(),
new CaseStatementsSelectioner(),
new HtmlSelectioner(),
new XmlTagSelectioner(),
new XmlCDATAContentSelectioner(),
new DtdSelectioner(),
new XmlElementSelectioner(),
new XmlTokenSelectioner(),
new ScriptletSelectioner(),
new PlainTextLineSelectioner(),
new ELExpressionHolderSelectioner()
};
public static void registerSelectioner(Selectioner selectioner) {
SELECTIONERS = ArrayUtil.append(SELECTIONERS, selectioner);
}
private static int findOpeningBrace(PsiElement[] children) {
int start = 0;
for (int i = 0; i < children.length; i++) {
PsiElement child = children[i];
if (child instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)child;
if (token.getTokenType() == JavaTokenType.LBRACE) {
int j = i + 1;
while (children[j] instanceof PsiWhiteSpace) {
j++;
}
start = children[j].getTextRange().getStartOffset();
}
}
}
return start;
}
private static int findClosingBrace(PsiElement[] children) {
int end = children[children.length - 1].getTextRange().getEndOffset();
for (int i = 0; i < children.length; i++) {
PsiElement child = children[i];
if (child instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)child;
if (token.getTokenType() == JavaTokenType.RBRACE) {
int j = i - 1;
while (children[j] instanceof PsiWhiteSpace) {
j
}
end = children[j].getTextRange().getEndOffset();
}
}
}
return end;
}
private static boolean isDocCommentElement(PsiElement element) {
return element instanceof PsiDocTag;
}
static List<TextRange> expandToWholeLine(CharSequence text, TextRange range, boolean isSymmetric) {
int textLength = text.length();
List<TextRange> result = new ArrayList<TextRange>();
if (range == null) {
return result;
}
boolean hasNewLines = false;
for (int i = range.getStartOffset(); i < range.getEndOffset(); i++) {
char c = text.charAt(i);
if (c == '\r' || c == '\n') {
hasNewLines = true;
break;
}
}
if (!hasNewLines) {
result.add(range);
}
int startOffset = range.getStartOffset();
int endOffset = range.getEndOffset();
int index1 = CharArrayUtil.shiftBackward(text, startOffset - 1, " \t");
if (endOffset > startOffset && text.charAt(endOffset - 1) == '\n' || text.charAt(endOffset - 1) == '\r') {
endOffset
}
int index2 = Math.min(textLength, CharArrayUtil.shiftForward(text, endOffset, " \t"));
if (index1 < 0
|| text.charAt(index1) == '\n'
|| text.charAt(index1) == '\r'
|| index2 == textLength
|| text.charAt(index2) == '\n'
|| text.charAt(index2) == '\r') {
if (!isSymmetric) {
if (index1 < 0 || text.charAt(index1) == '\n' || text.charAt(index1) == '\r') {
startOffset = index1 + 1;
}
if (index2 == textLength || text.charAt(index2) == '\n' || text.charAt(index2) == '\r') {
endOffset = index2;
if (endOffset < textLength) {
endOffset++;
if (endOffset < textLength && text.charAt(endOffset - 1) == '\r' && text.charAt(endOffset) == '\n') {
endOffset++;
}
}
}
result.add(new TextRange(startOffset, endOffset));
}
else {
if ((index1 < 0 || text.charAt(index1) == '\n' || text.charAt(index1) == '\r') &&
(index2 == textLength || text.charAt(index2) == '\n' || text.charAt(index2) == '\r')) {
startOffset = index1 + 1;
endOffset = index2;
if (endOffset < textLength) {
endOffset++;
if (endOffset < textLength && text.charAt(endOffset - 1) == '\r' && text.charAt(endOffset) == '\n') {
endOffset++;
}
}
result.add(new TextRange(startOffset, endOffset));
}
else {
result.add(range);
}
}
}
else {
result.add(range);
}
return result;
}
private static List<TextRange> expandToWholeLine(CharSequence text, TextRange range) {
return expandToWholeLine(text, range, true);
}
public static interface Selectioner {
boolean canSelect(PsiElement e);
List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor);
}
private static class BasicSelectioner implements Selectioner {
protected boolean canSelectXml(PsiElement e) {
return !(e instanceof XmlToken) && !(e instanceof XmlElement);
}
public boolean canSelect(PsiElement e) {
return
!(e instanceof PsiWhiteSpace) &&
!(e instanceof PsiComment) &&
!(e instanceof PsiCodeBlock) &&
!(e instanceof PsiArrayInitializerExpression) &&
!(e instanceof PsiParameterList) &&
!(e instanceof PsiExpressionList) &&
!(e instanceof PsiBlockStatement) &&
!(e instanceof PsiJavaCodeReferenceElement) &&
!(e instanceof PsiJavaToken && !(e instanceof PsiKeyword)) &&
canSelectXml(e) &&
!isDocCommentElement(e);
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
final TextRange originalRange = e.getTextRange();
List<TextRange> ranges = expandToWholeLine(editorText, originalRange, true);
if (ranges.size() == 1 && ranges.contains(originalRange)) {
ranges = expandToWholeLine(editorText, originalRange, false);
}
List<TextRange> result = new ArrayList<TextRange>();
result.addAll(ranges);
return result;
}
}
static class WordSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return super.canSelect(e) ||
e instanceof PsiJavaToken && ((PsiJavaToken)e).getTokenType() == JavaTokenType.IDENTIFIER;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> ranges;
if (super.canSelect(e)) {
ranges = super.select(e, editorText, cursorOffset, editor);
}
else {
ranges = new ArrayList<TextRange>();
}
addWordSelection(editor.getSettings().isCamelWords(), editorText, cursorOffset, ranges);
return ranges;
}
}
public static void addWordSelection(boolean camel, CharSequence editorText, int cursorOffset, List<TextRange> ranges) {
TextRange camelRange = camel ? getCamelSelectionRange(editorText, cursorOffset) : null;
if (camelRange != null) {
ranges.add(camelRange);
}
TextRange range = getWordSelectionRange(editorText, cursorOffset);
if (range != null && !range.equals(camelRange)) {
ranges.add(range);
}
}
private static TextRange getCamelSelectionRange(CharSequence editorText, int cursorOffset) {
if (cursorOffset > 0 && !Character.isJavaIdentifierPart(editorText.charAt(cursorOffset)) &&
Character.isJavaIdentifierPart(editorText.charAt(cursorOffset - 1))) {
cursorOffset
}
if (Character.isJavaIdentifierPart(editorText.charAt(cursorOffset))) {
int start = cursorOffset;
int end = cursorOffset + 1;
final int textLen = editorText.length();
while (start > 0 && Character.isJavaIdentifierPart(editorText.charAt(start - 1))) {
final char prevChar = editorText.charAt(start - 1);
final char curChar = editorText.charAt(start);
final char nextChar = start + 1 < textLen ? editorText.charAt(start + 1) : 0; // 0x00 is not lowercase.
if (Character.isLowerCase(prevChar) && Character.isUpperCase(curChar) || prevChar == '_' && curChar != '_' ||
Character.isUpperCase(prevChar) && Character.isUpperCase(curChar) && Character.isLowerCase(nextChar)) {
break;
}
start
}
while (end < textLen && Character.isJavaIdentifierPart(editorText.charAt(end))) {
final char prevChar = editorText.charAt(end - 1);
final char curChar = editorText.charAt(end);
final char nextChar = end + 1 < textLen ? editorText.charAt(end + 1) : 0; // 0x00 is not lowercase
if (Character.isLowerCase(prevChar) && Character.isUpperCase(curChar) || prevChar != '_' && curChar == '_' ||
Character.isUpperCase(prevChar) && Character.isUpperCase(curChar) && Character.isLowerCase(nextChar)) {
break;
}
end++;
}
if (start + 1 < end) {
return new TextRange(start, end);
}
}
return null;
}
private static TextRange getWordSelectionRange(CharSequence editorText, int cursorOffset) {
if (editorText.length() == 0) return null;
if (cursorOffset > 0 && !Character.isJavaIdentifierPart(editorText.charAt(cursorOffset)) &&
Character.isJavaIdentifierPart(editorText.charAt(cursorOffset - 1))) {
cursorOffset
}
if (Character.isJavaIdentifierPart(editorText.charAt(cursorOffset))) {
int start = cursorOffset;
int end = cursorOffset;
while (start > 0 && Character.isJavaIdentifierPart(editorText.charAt(start - 1))) {
start
}
while (end < editorText.length() && Character.isJavaIdentifierPart(editorText.charAt(end))) {
end++;
}
return new TextRange(start, end);
}
return null;
}
private static class LineCommentSelectioner extends WordSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiComment && !(e instanceof PsiDocComment);
}
public List<TextRange> select(PsiElement element, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(element, editorText, cursorOffset, editor);
PsiElement firstComment = element;
PsiElement e = element;
while (e.getPrevSibling() != null) {
if (e instanceof PsiComment) {
firstComment = e;
}
else if (!(e instanceof PsiWhiteSpace)) {
break;
}
e = e.getPrevSibling();
}
PsiElement lastComment = element;
e = element;
while (e.getNextSibling() != null) {
if (e instanceof PsiComment) {
lastComment = e;
}
else if (!(e instanceof PsiWhiteSpace)) {
break;
}
e = e.getNextSibling();
}
result.addAll(expandToWholeLine(editorText, new TextRange(firstComment.getTextRange().getStartOffset(),
lastComment.getTextRange().getEndOffset())));
return result;
}
}
private static class DocCommentSelectioner extends LineCommentSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiDocComment;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
PsiElement[] children = e.getChildren();
int startOffset = e.getTextRange().getStartOffset();
int endOffset = e.getTextRange().getEndOffset();
for (PsiElement child : children) {
if (child instanceof PsiDocToken) {
PsiDocToken token = (PsiDocToken)child;
if (token.getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) {
char[] chars = token.getText().toCharArray();
if (CharArrayUtil.shiftForward(chars, 0, " *\n\t\r") != chars.length) {
break;
}
}
}
startOffset = child.getTextRange().getEndOffset();
}
for (PsiElement child : children) {
if (child instanceof PsiDocToken) {
PsiDocToken token = (PsiDocToken)child;
if (token.getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) {
char[] chars = token.getText().toCharArray();
if (CharArrayUtil.shiftForward(chars, 0, " *\n\t\r") != chars.length) {
endOffset = child.getTextRange().getEndOffset();
}
}
}
}
startOffset = CharArrayUtil.shiftBackward(editorText, startOffset - 1, "* \t") + 1;
result.add(new TextRange(startOffset, endOffset));
return result;
}
}
private static class ListSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiParameterList || e instanceof PsiExpressionList;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
PsiElement[] children = e.getChildren();
int start = 0;
int end = 0;
for (PsiElement child : children) {
if (child instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)child;
if (token.getTokenType() == JavaTokenType.LPARENTH) {
start = token.getTextOffset() + 1;
}
if (token.getTokenType() == JavaTokenType.RPARENTH) {
end = token.getTextOffset();
}
}
}
List<TextRange> result = new ArrayList<TextRange>();
result.add(new TextRange(start, end));
return result;
}
}
private static class LiteralSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
PsiElement parent = e.getParent();
return
isStringLiteral(e) || isStringLiteral(parent);
}
private static boolean isStringLiteral(PsiElement element) {
return element instanceof PsiLiteralExpression &&
((PsiLiteralExpression)element).getType().equalsToText("java.lang.String") && element.getText().startsWith("\"") && element.getText().endsWith("\"");
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
TextRange range = e.getTextRange();
final StringLiteralLexer lexer = new StringLiteralLexer('\"', JavaTokenType.STRING_LITERAL);
lexer.start(editorText, range.getStartOffset(), range.getEndOffset(),0);
while (lexer.getTokenType() != null) {
if (lexer.getTokenStart() <= cursorOffset && cursorOffset < lexer.getTokenEnd()) {
if (StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(lexer.getTokenType())) {
result.add(new TextRange(lexer.getTokenStart(), lexer.getTokenEnd()));
}
else {
TextRange word = getWordSelectionRange(editorText, cursorOffset);
if (word != null) {
result.add(new TextRange(Math.max(word.getStartOffset(), lexer.getTokenStart()),
Math.min(word.getEndOffset(), lexer.getTokenEnd())));
}
}
break;
}
lexer.advance();
}
result.add(new TextRange(range.getStartOffset() + 1, range.getEndOffset() - 1));
return result;
}
}
private static class FinallyBlockSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiKeyword && PsiKeyword.FINALLY.equals(e.getText());
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
final PsiElement parent = e.getParent();
if (parent instanceof PsiTryStatement) {
final PsiTryStatement tryStatement = (PsiTryStatement)parent;
final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock != null) {
result.add(new TextRange(e.getTextRange().getStartOffset(), finallyBlock.getTextRange().getEndOffset()));
}
}
return result;
}
}
private static class CodeBlockOrInitializerSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiCodeBlock || e instanceof PsiArrayInitializerExpression;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
PsiElement[] children = e.getChildren();
int start = findOpeningBrace(children);
int end = findClosingBrace(children);
result.add(e.getTextRange());
result.addAll(expandToWholeLine(editorText, new TextRange(start, end)));
return result;
}
}
private static class MethodOrClassSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiClass && !(e instanceof PsiTypeParameter) || e instanceof PsiMethod;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
PsiElement firstChild = e.getFirstChild();
PsiElement[] children = e.getChildren();
if (firstChild instanceof PsiDocComment) {
int i = 1;
while (children[i] instanceof PsiWhiteSpace) {
i++;
}
TextRange range = new TextRange(children[i].getTextRange().getStartOffset(), e.getTextRange().getEndOffset());
result.addAll(expandToWholeLine(editorText, range));
range = new TextRange(firstChild.getTextRange().getStartOffset(), firstChild.getTextRange().getEndOffset());
result.addAll(expandToWholeLine(editorText, range));
}
else if (firstChild instanceof PsiComment) {
int i = 1;
while (children[i] instanceof PsiComment || children[i] instanceof PsiWhiteSpace) {
i++;
}
PsiElement last = children[i - 1] instanceof PsiWhiteSpace ? children[i - 2] : children[i - 1];
TextRange range = new TextRange(firstChild.getTextRange().getStartOffset(), last.getTextRange().getEndOffset());
if (range.contains(cursorOffset)) {
result.addAll(expandToWholeLine(editorText, range));
}
range = new TextRange(children[i].getTextRange().getStartOffset(), e.getTextRange().getEndOffset());
result.addAll(expandToWholeLine(editorText, range));
}
if (e instanceof PsiClass) {
int start = findOpeningBrace(children);
int end = findClosingBrace(children);
result.addAll(expandToWholeLine(editorText, new TextRange(start, end)));
}
return result;
}
}
private static class StatementGroupSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiStatement || e instanceof PsiComment && !(e instanceof PsiDocComment);
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
PsiElement parent = e.getParent();
if (!(parent instanceof PsiCodeBlock) && !(parent instanceof PsiBlockStatement) || parent instanceof JspCodeBlock) {
return result;
}
PsiElement startElement = e;
PsiElement endElement = e;
while (startElement.getPrevSibling() != null) {
PsiElement sibling = startElement.getPrevSibling();
if (sibling instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)sibling;
if (token.getTokenType() == JavaTokenType.LBRACE) {
break;
}
}
if (sibling instanceof PsiWhiteSpace) {
PsiWhiteSpace whiteSpace = (PsiWhiteSpace)sibling;
String[] strings = LineTokenizer.tokenize(whiteSpace.getText().toCharArray(), false);
if (strings.length > 2) {
break;
}
}
startElement = sibling;
}
while (startElement instanceof PsiWhiteSpace) {
startElement = startElement.getNextSibling();
}
while (endElement.getNextSibling() != null) {
PsiElement sibling = endElement.getNextSibling();
if (sibling instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)sibling;
if (token.getTokenType() == JavaTokenType.RBRACE) {
break;
}
}
if (sibling instanceof PsiWhiteSpace) {
PsiWhiteSpace whiteSpace = (PsiWhiteSpace)sibling;
String[] strings = LineTokenizer.tokenize(whiteSpace.getText().toCharArray(), false);
if (strings.length > 2) {
break;
}
}
endElement = sibling;
}
while (endElement instanceof PsiWhiteSpace) {
endElement = endElement.getPrevSibling();
}
result.addAll(expandToWholeLine(editorText, new TextRange(startElement.getTextRange().getStartOffset(),
endElement.getTextRange().getEndOffset())));
return result;
}
}
private static class ReferenceSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiJavaCodeReferenceElement;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
PsiElement endElement = e;
while (endElement instanceof PsiJavaCodeReferenceElement && endElement.getNextSibling() != null) {
endElement = endElement.getNextSibling();
}
if (!(endElement instanceof PsiJavaCodeReferenceElement) &&
!(endElement.getPrevSibling() instanceof PsiReferenceExpression && endElement instanceof PsiExpressionList)) {
endElement = endElement.getPrevSibling();
}
PsiElement element = e;
List<TextRange> result = new ArrayList<TextRange>();
while (element instanceof PsiJavaCodeReferenceElement) {
PsiElement firstChild = element.getFirstChild();
PsiElement referenceName = ((PsiJavaCodeReferenceElement)element).getReferenceNameElement();
if (referenceName != null) {
result.addAll(expandToWholeLine(editorText, new TextRange(referenceName.getTextRange().getStartOffset(),
endElement.getTextRange().getEndOffset())));
if (endElement instanceof PsiJavaCodeReferenceElement) {
final PsiElement endReferenceName = ((PsiJavaCodeReferenceElement)endElement).getReferenceNameElement();
if (endReferenceName != null) {
result.addAll(expandToWholeLine(editorText, new TextRange(referenceName.getTextRange().getStartOffset(),
endReferenceName.getTextRange().getEndOffset())));
}
}
}
if (firstChild == null) break;
element = firstChild;
}
// if (element instanceof PsiMethodCallExpression) {
result.addAll(expandToWholeLine(editorText, new TextRange(element.getTextRange().getStartOffset(),
endElement.getTextRange().getEndOffset())));
if (!(e.getParent() instanceof PsiJavaCodeReferenceElement)) {
if (e.getNextSibling() instanceof PsiJavaToken ||
e.getNextSibling() instanceof PsiWhiteSpace ||
e.getNextSibling() instanceof PsiExpressionList) {
result.addAll(super.select(e, editorText, cursorOffset, editor));
}
}
return result;
}
}
private static class DocTagSelectioner extends WordSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiDocTag;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
TextRange range = e.getTextRange();
int endOffset = range.getEndOffset();
int startOffset = range.getStartOffset();
PsiElement[] children = e.getChildren();
for (int i = children.length - 1; i >= 0; i
PsiElement child = children[i];
int childStartOffset = child.getTextRange().getStartOffset();
if (childStartOffset <= cursorOffset) {
break;
}
if (child instanceof PsiDocToken) {
PsiDocToken token = (PsiDocToken)child;
IElementType type = token.getTokenType();
char[] chars = token.textToCharArray();
int shift = CharArrayUtil.shiftForward(chars, 0, " \t\n\r");
if (shift != chars.length && type != JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) {
break;
}
}
else if (!(child instanceof PsiWhiteSpace)) {
break;
}
endOffset = Math.min(childStartOffset, endOffset);
}
startOffset = CharArrayUtil.shiftBackward(editorText, startOffset - 1, "* \t") + 1;
result.add(new TextRange(startOffset, endOffset));
return result;
}
}
private static class FieldSelectioner extends WordSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiField;
}
private static void addRangeElem(final List<TextRange> result,
CharSequence editorText,
final PsiElement first,
final int end) {
if (first != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(first.getTextRange().getStartOffset(), end)));
}
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
final PsiField field = (PsiField)e;
final TextRange range = field.getTextRange();
final PsiIdentifier first = field.getNameIdentifier();
final TextRange firstRange = first.getTextRange();
final PsiElement last = field.getInitializer();
final int end = last == null ? firstRange.getEndOffset() : last.getTextRange().getEndOffset();
addRangeElem(result, editorText, first, end);
//addRangeElem (result, editorText, field, textLength, field.getTypeElement(), end);
addRangeElem(result, editorText, field.getModifierList(), range.getEndOffset());
//addRangeElem (result, editorText, field, textLength, field.getDocComment(), end);
result.addAll(expandToWholeLine(editorText, range));
return result;
}
}
private static class JavaTokenSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiJavaToken && !(e instanceof PsiKeyword) && !(e.getParent()instanceof PsiCodeBlock);
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
PsiJavaToken token = (PsiJavaToken)e;
if (token.getTokenType() != JavaTokenType.SEMICOLON && token.getTokenType() != JavaTokenType.LPARENTH) {
return super.select(e, editorText, cursorOffset, editor);
}
else {
return null;
}
}
}
static class IfStatementSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiIfStatement;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
result.addAll(expandToWholeLine(editorText, e.getTextRange(), false));
PsiIfStatement statement = (PsiIfStatement)e;
final PsiKeyword elseKeyword = statement.getElseElement();
if (elseKeyword != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(elseKeyword.getTextRange().getStartOffset(),
statement.getTextRange().getEndOffset()),
false));
final PsiStatement branch = statement.getElseBranch();
if (branch instanceof PsiIfStatement) {
PsiIfStatement elseIf = (PsiIfStatement)branch;
final PsiKeyword element = elseIf.getElseElement();
if (element != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(elseKeyword.getTextRange().getStartOffset(),
elseIf.getThenBranch().getTextRange().getEndOffset()),
false));
}
}
}
return result;
}
}
static class TypeCastSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiTypeCastExpression;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
result.addAll(expandToWholeLine(editorText, e.getTextRange(), false));
PsiTypeCastExpression expression = (PsiTypeCastExpression)e;
PsiElement[] children = expression.getChildren();
PsiElement lParen = null;
PsiElement rParen = null;
for (PsiElement child : children) {
if (child instanceof PsiJavaToken) {
PsiJavaToken token = (PsiJavaToken)child;
if (token.getTokenType() == JavaTokenType.LPARENTH) lParen = token;
if (token.getTokenType() == JavaTokenType.RPARENTH) rParen = token;
}
}
if (lParen != null && rParen != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(lParen.getTextRange().getStartOffset(),
rParen.getTextRange().getEndOffset()),
false));
}
return result;
}
}
static class DtdSelectioner implements Selectioner {
public boolean canSelect(PsiElement e) {
return e instanceof XmlAttlistDecl || e instanceof XmlElementDecl;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
PsiElement[] children = e.getChildren();
PsiElement first = null;
PsiElement last = null;
for (PsiElement child : children) {
if (child instanceof XmlToken) {
XmlToken token = (XmlToken)child;
if (token.getTokenType() == XmlTokenType.XML_TAG_END) {
last = token;
break;
}
if (token.getTokenType() == XmlTokenType.XML_ELEMENT_DECL_START ||
token.getTokenType() == XmlTokenType.XML_ATTLIST_DECL_START
) {
first = token;
}
}
}
List<TextRange> result = new ArrayList<TextRange>(1);
if (first != null && last != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(first.getTextRange().getStartOffset(),
last.getTextRange().getEndOffset() + 1),
false));
}
return result;
}
}
static class XmlCDATAContentSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof CompositePsiElement &&
((CompositePsiElement)e).getElementType() == XmlElementType.XML_CDATA;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
PsiElement[] children = e.getChildren();
PsiElement first = null;
PsiElement last = null;
for (PsiElement child : children) {
if (child instanceof XmlToken) {
XmlToken token = (XmlToken)child;
if (token.getTokenType() == XmlTokenType.XML_CDATA_START) {
first = token.getNextSibling();
}
if (token.getTokenType() == XmlTokenType.XML_CDATA_END) {
last = token.getPrevSibling();
break;
}
}
}
if (first != null && last != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(first.getTextRange().getStartOffset(),
last.getTextRange().getEndOffset()),
false));
}
return result;
}
}
static class XmlTagSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof XmlTag;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
PsiElement[] children = e.getChildren();
addTagContentSelection(children, result, editorText);
PsiElement prev = e.getPrevSibling();
while (prev instanceof PsiWhiteSpace || prev instanceof XmlText || prev instanceof XmlComment) {
if (prev instanceof XmlText && prev.getText().trim().length() > 0) break;
if (prev instanceof XmlComment) {
result.addAll(expandToWholeLine(editorText,
new TextRange(prev.getTextRange().getStartOffset(),
e.getTextRange().getEndOffset()),
false));
}
prev = prev.getPrevSibling();
}
return result;
}
private static void addTagContentSelection(final PsiElement[] children, final List<TextRange> result, final CharSequence editorText) {
PsiElement first = null;
PsiElement last = null;
for (PsiElement child : children) {
if (child instanceof XmlToken) {
XmlToken token = (XmlToken)child;
if (token.getTokenType() == XmlTokenType.XML_TAG_END) {
first = token.getNextSibling();
}
if (token.getTokenType() == XmlTokenType.XML_END_TAG_START) {
last = token.getPrevSibling();
break;
}
}
}
if (first != null && last != null) {
result.addAll(expandToWholeLine(editorText,
new TextRange(first.getTextRange().getStartOffset(),
last.getTextRange().getEndOffset()),
false));
}
}
}
static class CaseStatementsSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e.getParent() instanceof PsiCodeBlock &&
e.getParent().getParent() instanceof PsiSwitchStatement;
}
public List<TextRange> select(PsiElement statement, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> result = new ArrayList<TextRange>();
PsiElement caseStart = statement;
PsiElement caseEnd = statement;
if (statement instanceof PsiSwitchLabelStatement ||
statement instanceof PsiSwitchStatement) {
return result;
}
PsiElement sibling = statement.getPrevSibling();
while(sibling != null && !(sibling instanceof PsiSwitchLabelStatement)) {
if (!(sibling instanceof PsiWhiteSpace)) caseStart = sibling;
sibling = sibling.getPrevSibling();
}
sibling = statement.getNextSibling();
while(sibling != null && !(sibling instanceof PsiSwitchLabelStatement)) {
if (!(sibling instanceof PsiWhiteSpace) &&
!(sibling instanceof PsiJavaToken) // end of switch
) {
caseEnd = sibling;
}
sibling = sibling.getNextSibling();
}
final Document document = editor.getDocument();
final int startOffset = document.getLineStartOffset(document.getLineNumber(caseStart.getTextOffset()));
final int endOffset = document.getLineEndOffset(document.getLineNumber(caseEnd.getTextOffset() + caseEnd.getTextLength())) + 1;
result.add(new TextRange(startOffset,endOffset));
return result;
}
}
static class XmlElementSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof XmlAttribute || e instanceof XmlAttributeValue;
}
}
static class XmlTokenSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
final FileType fileType = e.getContainingFile().getFileType();
return e instanceof XmlToken &&
(fileType == StdFileTypes.XML ||
fileType == StdFileTypes.DTD
);
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
XmlToken token = (XmlToken)e;
if (token.getTokenType() != XmlTokenType.XML_DATA_CHARACTERS &&
token.getTokenType() != XmlTokenType.XML_START_TAG_START &&
token.getTokenType() != XmlTokenType.XML_END_TAG_START
) {
List<TextRange> ranges = super.select(e, editorText, cursorOffset, editor);
addWordSelection(editor.getSettings().isCamelWords(), editorText, cursorOffset, ranges);
return ranges;
}
else {
List<TextRange> result = new ArrayList<TextRange>();
addWordSelection(editor.getSettings().isCamelWords(), editorText, cursorOffset, result);
return result;
}
}
}
static class ScriptletSelectioner extends BasicSelectioner {
@Override
public boolean canSelect(PsiElement e) {
return PsiUtil.isInJspFile(e) && e.getLanguage() instanceof JavaLanguage;
}
@Override
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> ranges = super.select(e, editorText, cursorOffset, editor);
final JspFile psiFile = PsiUtil.getJspFile(e);
if (e.getParent().getTextLength() == psiFile.getTextLength()) {
final JspxFileViewProvider viewProvider = psiFile.getViewProvider();
PsiElement elt = viewProvider.findElementAt(cursorOffset, viewProvider.getTemplateDataLanguage());
ranges.add(elt.getTextRange());
}
return ranges;
}
}
static class ELExpressionHolderSelectioner extends BasicSelectioner {
@Override
public boolean canSelect(PsiElement e) {
return e instanceof ELExpressionHolder;
}
@Override
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
List<TextRange> ranges = super.select(e, editorText, cursorOffset, editor);
if (true) {
ranges.add(e.getTextRange());
}
return ranges;
}
}
static class PlainTextLineSelectioner extends BasicSelectioner {
public boolean canSelect(PsiElement e) {
return e instanceof PsiPlainText || e instanceof XmlToken && ((XmlToken)e).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS;
}
public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
int start = cursorOffset;
while (start > 0 && editorText.charAt(start - 1) != '\n' && editorText.charAt(start - 1) != '\r') start
int end = cursorOffset;
while (end < editorText.length() && editorText.charAt(end) != '\n' && editorText.charAt(end) != '\r') end++;
final TextRange range = new TextRange(start, end);
if (!e.getParent().getTextRange().contains(range)) return null;
List<TextRange> result = new ArrayList<TextRange>();
result.add(range);
return result;
}
}
}
|
package info.ata4.unity.extract.handler;
import info.ata4.unity.serdes.UnityObject;
import info.ata4.unity.struct.ObjectPath;
import java.io.IOException;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class TextAssetHandler extends ExtractHandler {
@Override
public String getClassName() {
return "TextAsset";
}
@Override
public String getFileExtension() {
return "txt";
}
@Override
public void extract(ObjectPath path, UnityObject obj) throws IOException {
String name = obj.getValue("m_Name");
String script = obj.getValue("m_Script");
writeFile(script.getBytes("UTF8"), path.pathID, name);
}
}
|
// Vilya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// 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.threerings.parlor.card.client;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputAdapter;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.samskivert.util.ObserverList;
import com.samskivert.util.QuickSort;
import com.threerings.media.FrameManager;
import com.threerings.media.VirtualMediaPanel;
import com.threerings.media.image.Mirage;
import com.threerings.media.sprite.PathAdapter;
import com.threerings.media.sprite.Sprite;
import com.threerings.media.util.LinePath;
import com.threerings.media.util.Path;
import com.threerings.media.util.PathSequence;
import com.threerings.parlor.card.data.Card;
import com.threerings.parlor.card.data.CardCodes;
import com.threerings.parlor.card.data.Hand;
/**
* Extends VirtualMediaPanel to provide services specific to rendering and manipulating playing
* cards.
*/
public abstract class CardPanel extends VirtualMediaPanel
implements CardCodes
{
/** The selection mode in which cards are not selectable. */
public static final int NONE = 0;
/** The selection mode in which the user can select a single card. */
public static final int SINGLE = 1;
/** The selection mode in which the user can select multiple cards. */
public static final int MULTIPLE = 2;
/**
* A listener for card selection/deselection.
*/
public static interface CardSelectionObserver
{
/**
* Called when a card has been selected.
*/
public void cardSpriteSelected (CardSprite sprite);
/**
* Called when a card has been deselected.
*/
public void cardSpriteDeselected (CardSprite sprite);
}
/**
* Constructor.
*
* @param frameManager the frame manager
*/
public CardPanel (FrameManager frameManager)
{
super(frameManager);
// add a listener for mouse events
CardListener cl = new CardListener();
addMouseListener(cl);
addMouseMotionListener(cl);
}
/**
* Returns the full-sized image for the back of a playing card.
*/
public abstract Mirage getCardBackImage ();
/**
* Returns the full-sized image for the front of the specified card.
*/
public abstract Mirage getCardImage (Card card);
/**
* Returns the small-sized image for the back of a playing card.
*/
public abstract Mirage getMicroCardBackImage ();
/**
* Returns the small-sized image for the front of the specified card.
*/
public abstract Mirage getMicroCardImage (Card card);
/**
* Sets the location of the hand (the location of the center of the hand's upper edge).
*/
public void setHandLocation (int x, int y)
{
_handLocation.setLocation(x, y);
}
/**
* Sets the horizontal spacing between cards in the hand.
*/
public void setHandSpacing (int spacing)
{
_handSpacing = spacing;
}
/**
* Sets the vertical distance to offset cards that are selectable or playable.
*/
public void setSelectableCardOffset (int offset)
{
_selectableCardOffset = offset;
}
/**
* Sets the vertical distance to offset cards that are selected.
*/
public void setSelectedCardOffset (int offset)
{
_selectedCardOffset = offset;
}
/**
* Sets the selection mode for the hand (NONE, PLAY_SINGLE, SINGLE, or MULTIPLE). Changing the
* selection mode does not change the current selection.
*/
public void setHandSelectionMode (int mode)
{
_handSelectionMode = mode;
// update the offsets of all cards in the hand
updateHandOffsets();
}
/**
* Sets the selection predicate that determines which cards from the hand may be selected (if
* null, all cards may be selected). Changing the predicate does not change the current
* selection.
*/
public void setHandSelectionPredicate (Predicate<CardSprite> pred)
{
_handSelectionPredicate = pred;
// update the offsets of all cards in the hand
updateHandOffsets();
}
/**
* Returns the currently selected hand sprite (null if no sprites are selected, the first
* sprite if multiple sprites are selected).
*/
public CardSprite getSelectedHandSprite ()
{
return _selectedHandSprites.size() == 0 ?
null : _selectedHandSprites.get(0);
}
/**
* Returns an array containing the currently selected hand sprites (returns an empty array if
* no sprites are selected).
*/
public CardSprite[] getSelectedHandSprites ()
{
return _selectedHandSprites.toArray(
new CardSprite[_selectedHandSprites.size()]);
}
/**
* Programmatically selects a sprite in the hand.
*/
public void selectHandSprite (final CardSprite sprite)
{
// make sure it's not already selected
if (_selectedHandSprites.contains(sprite)) {
return;
}
// if in single card mode and there's another card selected, deselect it
if (_handSelectionMode == SINGLE) {
CardSprite oldSprite = getSelectedHandSprite();
if (oldSprite != null) {
deselectHandSprite(oldSprite);
}
}
// add to list and update offset
_selectedHandSprites.add(sprite);
sprite.setLocation(sprite.getX(), getHandY(sprite));
// notify the observers
ObserverList.ObserverOp<CardSelectionObserver> op =
new ObserverList.ObserverOp<CardSelectionObserver>() {
public boolean apply (CardSelectionObserver obs) {
obs.cardSpriteSelected(sprite);
return true;
}
};
_handSelectionObservers.apply(op);
}
/**
* Programmatically deselects a sprite in the hand.
*/
public void deselectHandSprite (final CardSprite sprite)
{
// make sure it's selected
if (!_selectedHandSprites.contains(sprite)) {
return;
}
// remove from list and update offset
_selectedHandSprites.remove(sprite);
sprite.setLocation(sprite.getX(), getHandY(sprite));
// notify the observers
ObserverList.ObserverOp<CardSelectionObserver> op =
new ObserverList.ObserverOp<CardSelectionObserver>() {
public boolean apply (CardSelectionObserver obs) {
obs.cardSpriteDeselected(sprite);
return true;
}
};
_handSelectionObservers.apply(op);
}
/**
* Clears any existing hand sprite selection.
*/
public void clearHandSelection ()
{
CardSprite[] sprites = getSelectedHandSprites();
for (CardSprite sprite : sprites) {
deselectHandSprite(sprite);
}
}
/**
* Adds an object to the list of observers to notify when cards in the hand are
* selected/deselected.
*/
public void addHandSelectionObserver (CardSelectionObserver obs)
{
_handSelectionObservers.add(obs);
}
/**
* Removes an object from the hand selection observer list.
*/
public void removeHandSelectionObserver (CardSelectionObserver obs)
{
_handSelectionObservers.remove(obs);
}
/**
* Fades a hand of cards in.
*
* @param hand the hand of cards
* @param fadeDuration the amount of time to spend fading in the entire hand
*/
public void setHand (Hand hand, long fadeDuration)
{
// make sure no cards are hanging around
clearHand();
// create the sprites
int size = hand.size();
for (int i = 0; i < size; i++) {
CardSprite cs = new CardSprite(this, hand.get(i));
_handSprites.add(cs);
}
// sort them
if (shouldSortHand()) {
QuickSort.sort(_handSprites, CARD_COMP);
}
// fade them in at proper locations and layers
long cardDuration = fadeDuration / size;
for (int i = 0; i < size; i++) {
CardSprite cs = _handSprites.get(i);
cs.setLocation(getHandX(size, i), _handLocation.y);
cs.setRenderOrder(i);
cs.addSpriteObserver(_handSpriteObserver);
addSprite(cs);
cs.fadeIn(i * cardDuration, cardDuration);
}
// make sure we have the right card sprite active
updateActiveCardSprite();
}
/**
* Fades a hand of cards in face-down.
*
* @param size the size of the hand
* @param fadeDuration the amount of time to spend fading in each card
*/
public void setHand (int size, long fadeDuration)
{
// fill hand will null entries to signify unknown cards
Hand hand = new Hand();
for (int i = 0; i < size; i++) {
hand.add(null);
}
setHand(hand, fadeDuration);
}
/**
* Shows a hand that was previous set face-down.
*
* @param hand the hand of cards
*/
public void showHand (Hand hand)
{
// sort the hand
if (shouldSortHand()) {
QuickSort.sort(hand);
}
// set the sprites
int len = Math.min(_handSprites.size(), hand.size());
for (int i = 0; i < len; i++) {
CardSprite cs = _handSprites.get(i);
cs.setCard(hand.get(i));
}
}
/**
* Returns the first sprite in the hand that corresponds to the specified card, or null if the
* card is not in the hand.
*/
public CardSprite getHandSprite (Card card)
{
return getCardSprite(_handSprites, card);
}
/**
* Clears all cards from the hand.
*/
public void clearHand ()
{
clearHandSelection();
clearSprites(_handSprites);
}
/**
* Clears all cards from the board.
*/
public void clearBoard ()
{
clearSprites(_boardSprites);
}
/**
* Flies a set of cards from the hand into the ether. Clears any selected cards.
*
* @param cards the card sprites to remove from the hand
* @param dest the point to fly the cards to
* @param flightDuration the duration of the cards' flight
* @param fadePortion the amount of time to spend fading out as a proportion of the flight
* duration
*/
public void flyFromHand (CardSprite[] cards, Point dest, long flightDuration, float fadePortion)
{
// fly each sprite over, removing it from the hand immediately and from the board when it
// finishes its path
for (CardSprite card : cards) {
removeFromHand(card);
LinePath flight = new LinePath(dest, flightDuration);
card.addSpriteObserver(_pathEndRemover);
card.moveAndFadeOut(flight, flightDuration, fadePortion);
}
// adjust the hand to cover the hole
adjustHand(flightDuration, false);
}
/**
* Flies a set of cards from the ether into the hand. Clears any selected cards. The cards
* will first fly to the selected card offset, pause for the specified duration, and then drop
* into the hand.
*
* @param cards the cards to add to the hand
* @param src the point to fly the cards from
* @param flightDuration the duration of the cards' flight
* @param pauseDuration the duration of the pause before dropping into the hand
* @param dropDuration the duration of the cards' drop into the hand
* @param fadePortion the amount of time to spend fading in as a proportion of the flight
* duration
*/
public void flyIntoHand (Card[] cards, Point src, long flightDuration, long pauseDuration,
long dropDuration, float fadePortion)
{
// first create the sprites and add them to the list
CardSprite[] sprites = new CardSprite[cards.length];
for (int i = 0; i < cards.length; i++) {
sprites[i] = new CardSprite(this, cards[i]);
_handSprites.add(sprites[i]);
}
// settle the hand
adjustHand(flightDuration, true);
// then set the layers and fly the cards in
int size = _handSprites.size();
for (CardSprite sprite : sprites) {
int idx = _handSprites.indexOf(sprite);
sprite.setLocation(src.x, src.y);
sprite.setRenderOrder(idx);
sprite.addSpriteObserver(_handSpriteObserver);
addSprite(sprite);
// create a path sequence containing flight, pause, and drop
ArrayList<Path> paths = Lists.newArrayList();
Point hp2 = new Point(getHandX(size, idx), _handLocation.y),
hp1 = new Point(hp2.x, hp2.y - _selectedCardOffset);
paths.add(new LinePath(hp1, flightDuration));
paths.add(new LinePath(hp1, pauseDuration));
paths.add(new LinePath(hp2, dropDuration));
sprite.moveAndFadeIn(new PathSequence(paths), flightDuration +
pauseDuration + dropDuration, fadePortion);
}
}
/**
* Flies a set of cards from the ether into the ether.
*
* @param cards the cards to fly across
* @param src the point to fly the cards from
* @param dest the point to fly the cards to
* @param flightDuration the duration of the cards' flight
* @param cardDelay the amount of time to wait between cards
* @param fadePortion the amount of time to spend fading in and out as a proportion of the
* flight duration
*/
public void flyAcross (Card[] cards, Point src, Point dest, long flightDuration,
long cardDelay, float fadePortion)
{
for (int i = 0; i < cards.length; i++) {
// add on top of all board sprites
CardSprite cs = new CardSprite(this, cards[i]);
cs.setRenderOrder(getHighestBoardLayer() + 1 + i);
cs.setLocation(src.x, src.y);
addSprite(cs);
// prepend an initial delay to all cards after the first
Path path;
long pathDuration;
LinePath flight = new LinePath(dest, flightDuration);
if (i > 0) {
long delayDuration = cardDelay * i;
LinePath delay = new LinePath(src, delayDuration);
path = new PathSequence(delay, flight);
pathDuration = delayDuration + flightDuration;
} else {
path = flight;
pathDuration = flightDuration;
}
cs.addSpriteObserver(_pathEndRemover);
cs.moveAndFadeInAndOut(path, pathDuration, fadePortion);
}
}
/**
* Flies a set of cards from the ether into the ether face-down.
*
* @param number the number of cards to fly across
* @param src the point to fly the cards from
* @param dest the point to fly the cards to
* @param flightDuration the duration of the cards' flight
* @param cardDelay the amount of time to wait between cards
* @param fadePortion the amount of time to spend fading in and out as a proportion of the
* flight duration
*/
public void flyAcross (int number, Point src, Point dest, long flightDuration,
long cardDelay, float fadePortion)
{
// use null values to signify unknown cards
flyAcross(new Card[number], src, dest, flightDuration,
cardDelay, fadePortion);
}
/**
* Flies a card from the hand onto the board. Clears any cards selected.
*
* @param card the sprite to remove from the hand
* @param dest the point to fly the card to
* @param flightDuration the duration of the card's flight
*/
public void flyFromHandToBoard (CardSprite card, Point dest, long flightDuration)
{
// fly it over
LinePath flight = new LinePath(dest, flightDuration);
card.move(flight);
// lower the board so that the card from hand is on top
lowerBoardSprites(card.getRenderOrder() - 1);
// move from one list to the other
removeFromHand(card);
_boardSprites.add(card);
// adjust the hand to cover the hole
adjustHand(flightDuration, false);
}
/**
* Flies a card from the ether onto the board.
*
* @param card the card to add to the board
* @param src the point to fly the card from
* @param dest the point to fly the card to
* @param flightDuration the duration of the card's flight
* @param fadePortion the amount of time to spend fading in as a proportion of the flight
* duration
*/
public void flyToBoard (Card card, Point src, Point dest, long flightDuration,
float fadePortion)
{
// add it on top of the existing cards
CardSprite cs = new CardSprite(this, card);
cs.setRenderOrder(getHighestBoardLayer() + 1);
cs.setLocation(src.x, src.y);
addSprite(cs);
_boardSprites.add(cs);
// and fly it over
LinePath flight = new LinePath(dest, flightDuration);
cs.moveAndFadeIn(flight, flightDuration, fadePortion);
}
/**
* Adds a card to the board immediately.
*
* @param card the card to add to the board
* @param dest the point at which to add the card
*/
public void addToBoard (Card card, Point dest)
{
CardSprite cs = new CardSprite(this, card);
cs.setRenderOrder(getHighestBoardLayer() + 1);
cs.setLocation(dest.x, dest.y);
addSprite(cs);
_boardSprites.add(cs);
}
/**
* Flies a set of cards from the board into the ether.
*
* @param cards the cards to remove from the board
* @param dest the point to fly the cards to
* @param flightDuration the duration of the cards' flight
* @param fadePortion the amount of time to spend fading out as a proportion of the flight
* duration
*/
public void flyFromBoard (CardSprite[] cards, Point dest, long flightDuration,
float fadePortion)
{
for (CardSprite card : cards) {
LinePath flight = new LinePath(dest, flightDuration);
card.addSpriteObserver(_pathEndRemover);
card.moveAndFadeOut(flight, flightDuration, fadePortion);
_boardSprites.remove(card);
}
}
/**
* Flies a set of cards from the board into the ether through an intermediate point.
*
* @param cards the cards to remove from the board
* @param dest1 the first point to fly the cards to
* @param dest2 the final destination of the cards
* @param flightDuration the duration of the cards' flight
* @param fadePortion the amount of time to spend fading out as a proportion of the flight
* duration
*/
public void flyFromBoard (CardSprite[] cards, Point dest1, Point dest2, long flightDuration,
float fadePortion)
{
for (CardSprite card : cards) {
PathSequence flight = new PathSequence(
new LinePath(dest1, flightDuration/2),
new LinePath(dest1, dest2, flightDuration/2));
card.addSpriteObserver(_pathEndRemover);
card.moveAndFadeOut(flight, flightDuration, fadePortion);
_boardSprites.remove(card);
}
}
/**
* Returns the first card sprite in the specified list that represents the specified card, or
* null if there is no such sprite in the list.
*/
protected CardSprite getCardSprite (List<CardSprite> list, Card card)
{
for (int i = 0; i < list.size(); i++) {
CardSprite cs = list.get(i);
if (card.equals(cs.getCard())) {
return cs;
}
}
return null;
}
/**
* Returns whether the user's hand should be sorted when displayed. By default, hands are
* sorted.
*/
protected boolean shouldSortHand ()
{
return true;
}
/**
* Expands or collapses the hand to accommodate new cards or cover the space left by removed
* cards. Skips unmanaged sprites. Clears out any selected cards.
*
* @param adjustDuration the amount of time to spend settling the cards into their new
* locations
* @param updateLayers whether or not to update the layers of the cards
*/
protected void adjustHand (long adjustDuration, boolean updateLayers)
{
// clear out selected cards
clearHandSelection();
// Sort the hand
if (shouldSortHand()) {
QuickSort.sort(_handSprites, CARD_COMP);
}
// Move each card to its proper position (and, optionally, layer)
int size = _handSprites.size();
for (int i = 0; i < size; i++) {
CardSprite cs = _handSprites.get(i);
if (!isManaged(cs)) {
continue;
}
if (updateLayers) {
cs.setRenderOrder(i);
}
LinePath adjust = new LinePath(
new Point(getHandX(size, i), _handLocation.y), adjustDuration);
cs.move(adjust);
}
}
/**
* Removes a card from the hand.
*/
protected void removeFromHand (CardSprite card)
{
_selectedHandSprites.remove(card);
_handSprites.remove(card);
}
/**
* Updates the offsets of all the cards in the hand. If there is only one selectable card,
* that card will always be raised slightly.
*/
protected void updateHandOffsets ()
{
// make active card sprite is up-to-date
updateActiveCardSprite();
int size = _handSprites.size();
for (int i = 0; i < size; i++) {
CardSprite cs = _handSprites.get(i);
if (!cs.isMoving()) {
cs.setLocation(cs.getX(), getHandY(cs));
}
}
}
/**
* Given the location and spacing of the hand, returns the x location of the card at the
* specified index within a hand of the specified size.
*/
protected int getHandX (int size, int idx)
{
// get the card width from the image if not yet known
if (_cardWidth == 0) {
_cardWidth = getCardBackImage().getWidth();
}
// first compute the width of the entire hand, then use that to determine the centered
// location
int width = (size - 1) * _handSpacing + _cardWidth;
return (_handLocation.x - width/2) + idx * _handSpacing;
}
/**
* Determines the y location of the specified card sprite, given its selection state.
*/
protected int getHandY (CardSprite sprite)
{
if (_selectedHandSprites.contains(sprite)) {
return _handLocation.y - _selectedCardOffset;
} else if (isSelectable(sprite) &&
(sprite == _activeCardSprite || isOnlySelectable(sprite))) {
return _handLocation.y - _selectableCardOffset;
} else {
return _handLocation.y;
}
}
/**
* Given the current selection mode and predicate, determines if the specified sprite is
* selectable.
*/
protected boolean isSelectable (CardSprite sprite)
{
return _handSelectionMode != NONE &&
(_handSelectionPredicate == null || _handSelectionPredicate.apply(sprite));
}
/**
* Determines whether the specified sprite is the only selectable sprite in the hand according
* to the selection predicate.
*/
protected boolean isOnlySelectable (CardSprite sprite)
{
// if there's no predicate, last remaining card is only selectable
if (_handSelectionPredicate == null) {
return _handSprites.size() == 1 && _handSprites.contains(sprite);
}
// otherwise, look for a sprite that fits the predicate and isn't the parameter
for (CardSprite cs : _handSprites) {
if (cs != sprite && _handSelectionPredicate.apply(cs)) {
return false;
}
}
return true;
}
/**
* Lowers all board sprites so that they are rendered at or below the specified layer.
*/
protected void lowerBoardSprites (int layer)
{
// see if they're already lower
int highest = getHighestBoardLayer();
if (highest <= layer) {
return;
}
// lower them just enough
int size = _boardSprites.size(), adjustment = layer - highest;
for (int i = 0; i < size; i++) {
CardSprite cs = _boardSprites.get(i);
cs.setRenderOrder(cs.getRenderOrder() + adjustment);
}
}
/**
* Returns the highest render order of any sprite on the board.
*/
protected int getHighestBoardLayer ()
{
// must be at least zero, because that's the lowest number we can push the sprites down to
// (the layer of the first card in the hand)
int size = _boardSprites.size(), highest = 0;
for (int i = 0; i < size; i++) {
highest = Math.max(highest, _boardSprites.get(i).getRenderOrder());
}
return highest;
}
/**
* Clears an array of sprites from the specified list and from the panel.
*/
protected void clearSprites (List<CardSprite> sprites)
{
for (Iterator<CardSprite> it = sprites.iterator(); it.hasNext(); ) {
removeSprite(it.next());
it.remove();
}
}
/**
* Updates the active card sprite based on the location of the mouse pointer.
*/
protected void updateActiveCardSprite ()
{
// can't do anything if we don't know where the mouse pointer is
if (_mouseEvent == null) {
return;
}
Sprite newHighestHit = _spritemgr.getHighestHitSprite(
_mouseEvent.getX(), _mouseEvent.getY());
CardSprite newActiveCardSprite =
(newHighestHit instanceof CardSprite ? (CardSprite)newHighestHit : null);
if (_activeCardSprite != newActiveCardSprite) {
if (_activeCardSprite != null && isManaged(_activeCardSprite)) {
_activeCardSprite.queueNotification(
new CardSpriteExitedOp(_activeCardSprite, _mouseEvent));
}
_activeCardSprite = newActiveCardSprite;
if (_activeCardSprite != null) {
_activeCardSprite.queueNotification(
new CardSpriteEnteredOp(_activeCardSprite, _mouseEvent));
}
}
}
@Override
protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect)
{
gfx.setColor(DEFAULT_BACKGROUND);
gfx.fill(dirtyRect);
super.paintBehind(gfx, dirtyRect);
}
/** Listens for interactions with cards in hand. */
protected class HandSpriteObserver extends PathAdapter
implements CardSpriteObserver
{
@Override
public void pathCompleted (Sprite sprite, Path path, long when)
{
updateActiveCardSprite();
maybeUpdateOffset((CardSprite)sprite);
}
public void cardSpriteClicked (CardSprite sprite, MouseEvent me)
{
// select, deselect, or play card in hand
if (_selectedHandSprites.contains(sprite) &&
_handSelectionMode != NONE) {
deselectHandSprite(sprite);
} else if (_handSprites.contains(sprite) && isSelectable(sprite)) {
selectHandSprite(sprite);
}
}
public void cardSpriteEntered (CardSprite sprite, MouseEvent me)
{
maybeUpdateOffset(sprite);
}
public void cardSpriteExited (CardSprite sprite, MouseEvent me)
{
maybeUpdateOffset(sprite);
}
public void cardSpriteDragged (CardSprite sprite, MouseEvent me)
{}
protected void maybeUpdateOffset (CardSprite sprite)
{
// update the offset if it's in the hand and isn't moving
if (_handSprites.contains(sprite) && !sprite.isMoving()) {
sprite.setLocation(sprite.getX(), getHandY(sprite));
}
}
};
/** Listens for mouse interactions with cards. */
protected class CardListener extends MouseInputAdapter
{
@Override
public void mousePressed (MouseEvent me)
{
if (_activeCardSprite != null &&
isManaged(_activeCardSprite)) {
_handleX = _activeCardSprite.getX() - me.getX();
_handleY = _activeCardSprite.getY() - me.getY();
_hasBeenDragged = false;
}
}
@Override
public void mouseReleased (MouseEvent me)
{
if (_activeCardSprite != null &&
isManaged(_activeCardSprite) &&
_hasBeenDragged) {
_activeCardSprite.queueNotification(
new CardSpriteDraggedOp(_activeCardSprite, me)
);
}
}
@Override
public void mouseClicked (MouseEvent me)
{
if (_activeCardSprite != null &&
isManaged(_activeCardSprite)) {
_activeCardSprite.queueNotification(
new CardSpriteClickedOp(_activeCardSprite, me)
);
}
}
@Override
public void mouseMoved (MouseEvent me)
{
_mouseEvent = me;
updateActiveCardSprite();
}
@Override
public void mouseDragged (MouseEvent me)
{
_mouseEvent = me;
if (_activeCardSprite != null &&
isManaged(_activeCardSprite) &&
_activeCardSprite.isDraggable()) {
_activeCardSprite.setLocation(
me.getX() + _handleX,
me.getY() + _handleY
);
_hasBeenDragged = true;
} else {
updateActiveCardSprite();
}
}
@Override
public void mouseEntered (MouseEvent me)
{
_mouseEvent = me;
}
@Override
public void mouseExited (MouseEvent me)
{
_mouseEvent = me;
}
protected int _handleX, _handleY;
protected boolean _hasBeenDragged;
}
/** Calls CardSpriteObserver.cardSpriteClicked. */
protected static class CardSpriteClickedOp implements
ObserverList.ObserverOp<Object>
{
public CardSpriteClickedOp (CardSprite sprite, MouseEvent me)
{
_sprite = sprite;
_me = me;
}
public boolean apply (Object observer)
{
if (observer instanceof CardSpriteObserver) {
((CardSpriteObserver)observer).cardSpriteClicked(_sprite,
_me);
}
return true;
}
protected CardSprite _sprite;
protected MouseEvent _me;
}
/** Calls CardSpriteObserver.cardSpriteEntered. */
protected static class CardSpriteEnteredOp implements
ObserverList.ObserverOp<Object>
{
public CardSpriteEnteredOp (CardSprite sprite, MouseEvent me)
{
_sprite = sprite;
_me = me;
}
public boolean apply (Object observer)
{
if (observer instanceof CardSpriteObserver) {
((CardSpriteObserver)observer).cardSpriteEntered(_sprite, _me);
}
return true;
}
protected CardSprite _sprite;
protected MouseEvent _me;
}
/** Calls CardSpriteObserver.cardSpriteExited. */
protected static class CardSpriteExitedOp implements
ObserverList.ObserverOp<Object>
{
public CardSpriteExitedOp (CardSprite sprite, MouseEvent me)
{
_sprite = sprite;
_me = me;
}
public boolean apply (Object observer)
{
if (observer instanceof CardSpriteObserver) {
((CardSpriteObserver)observer).cardSpriteExited(_sprite, _me);
}
return true;
}
protected CardSprite _sprite;
protected MouseEvent _me;
}
/** Calls CardSpriteObserver.cardSpriteDragged. */
protected static class CardSpriteDraggedOp implements
ObserverList.ObserverOp<Object>
{
public CardSpriteDraggedOp (CardSprite sprite, MouseEvent me)
{
_sprite = sprite;
_me = me;
}
public boolean apply (Object observer)
{
if (observer instanceof CardSpriteObserver) {
((CardSpriteObserver)observer).cardSpriteDragged(_sprite,
_me);
}
return true;
}
protected CardSprite _sprite;
protected MouseEvent _me;
}
/** The width of the playing cards. */
protected int _cardWidth;
/** The last motion/entrance/exit event received from the mouse. */
protected MouseEvent _mouseEvent;
/** The currently active card sprite (the one that the mouse is over). */
protected CardSprite _activeCardSprite;
/** The sprites for cards within the hand. */
protected ArrayList<CardSprite> _handSprites = Lists.newArrayList();
/** The sprites for cards within the hand that have been selected. */
protected ArrayList<CardSprite> _selectedHandSprites = Lists.newArrayList();
/** The current selection mode for the hand. */
protected int _handSelectionMode;
/** The predicate that determines which cards are selectable (if null, all
* cards are selectable). */
protected Predicate<CardSprite> _handSelectionPredicate;
/** Observers of hand card selection/deselection. */
protected ObserverList<CardSelectionObserver> _handSelectionObservers =
new ObserverList<CardSelectionObserver>(
ObserverList.FAST_UNSAFE_NOTIFY);
/** The location of the center of the hand's upper edge. */
protected Point _handLocation = new Point();
/** The horizontal distance between cards in the hand. */
protected int _handSpacing;
/** The vertical distance to offset cards that are selectable. */
protected int _selectableCardOffset;
/** The vertical distance to offset cards that are selected. */
protected int _selectedCardOffset;
/** The sprites for cards on the board. */
protected ArrayList<CardSprite> _boardSprites = Lists.newArrayList();
/** The hand sprite observer instance. */
protected HandSpriteObserver _handSpriteObserver = new HandSpriteObserver();
/** A path observer that removes the sprite at the end of its path. */
protected PathAdapter _pathEndRemover = new PathAdapter() {
@Override
public void pathCompleted (Sprite sprite, Path path, long when) {
removeSprite(sprite);
}
};
/** Compares two card sprites based on their underlying card. */
protected static final Comparator<CardSprite> CARD_COMP = new Comparator<CardSprite>() {
public int compare (CardSprite cs1, CardSprite cs2) {
if (cs1._card == null || cs2._card == null) {
return 0;
} else {
return cs1._card.compareTo(cs2._card);
}
}
};
/** A nice default green card table background color. */
protected static final Color DEFAULT_BACKGROUND = new Color(0x326D36);
}
|
package org.apache.velocity.runtime.directive;
import java.io.IOException;
import java.io.Writer;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.parser.ParserTreeConstants;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.util.StringUtils;
import org.apache.velocity.exception.MethodInvocationException;
public class Parse extends Directive
{
private boolean ready = false;
/**
* Return name of this directive.
*/
public String getName()
{
return "parse";
}
/**
* Return type of this directive.
*/
public int getType()
{
return LINE;
}
/**
* iterates through the argument list and renders every
* argument that is appropriate. Any non appropriate
* arguments are logged, but render() continues.
*/
public boolean render( InternalContextAdapter context,
Writer writer, Node node)
throws IOException, MethodInvocationException
{
/*
* did we get an argument?
*/
if ( node.jjtGetChild(0) == null)
{
Runtime.error( "#parse() error : null argument" );
return false;
}
/*
* does it have a value? If you have a null reference, then no.
*/
Object value = node.jjtGetChild(0).value( context );
if ( value == null)
{
Runtime.error( "#parse() error : null argument" );
return false;
}
/*
* get the path
*/
String arg = value.toString();
/*
* see if we have exceeded the configured depth.
* If it isn't configured, put a stop at 20 just in case.
*/
Object[] templateStack = context.getTemplateNameStack();
if ( templateStack.length >=
Runtime.getInt(Runtime.PARSE_DIRECTIVE_MAXDEPTH, 20) )
{
StringBuffer path = new StringBuffer();
for( int i = 0; i < templateStack.length; ++i)
{
path.append( " > " + templateStack[i] );
}
Runtime.error( "Max recursion depth reached (" +
templateStack.length + ")" + " File stack:" + path );
return false;
}
/*
* now use the Runtime resource loader to get the template
*/
Template t = null;
try
{
t = Runtime.getTemplate( arg, context.getCurrentResource().getEncoding() );
}
catch ( Exception e)
{
Runtime.error("#parse : cannot find " + arg + " template!");
return false;
}
/*
* and render it
*/
try
{
context.pushCurrentTemplateName(arg);
((SimpleNode) t.getData()).render( context, writer );
}
catch ( Exception e )
{
Runtime.error( "Parse.render() : " + e );
return false;
}
finally
{
context.popCurrentTemplateName();
}
return true;
}
}
|
package org.apache.velocity.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.Stack;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Context;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.util.SimplePool;
/**
* Base class which simplifies the use of Velocity with Servlets.
* Extend this class, implement the <code>handleRequest()</code> method,
* and add your data to the context. Then call
* <code>getTemplate("myTemplate.wm")</code>.
*
* This class puts some things into the context object that you should
* be aware of:
* <pre>
* "req" - The HttpServletRequest object
* "res" - The HttpServletResponse object
* </pre>
*
* If you put a contentType object into the context within either your
* serlvet or within your template, then that will be used to override
* the default content type specified in the properties file.
*
* "contentType" - The value for the Content-Type: header
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* $Id: VelocityServlet.java,v 1.17 2000/11/16 07:07:10 jvanzyl Exp $
*/
public abstract class VelocityServlet extends HttpServlet
{
/**
* The HTTP request object context key.
*/
public static final String REQUEST = "req";
/**
* The HTTP response object context key.
*/
public static final String RESPONSE = "res";
/**
* The HTTP content type context key.
*/
public static final String CONTENT_TYPE = "contentType";
/**
* The encoding to use when generating outputing.
*/
private static String encoding = null;
/**
* The default content type.
*/
private static String defaultContentType;
/**
* This is the string that is looked for when getInitParameter is
* called.
*/
private static final String INIT_PROPS_KEY = "properties";
/**
* Cache of writers
*/
private static SimplePool writerPool = new SimplePool(40);
/**
* Performs initialization of this servlet. Called by the servlet
* container on loading.
*
* @param config The servlet configuration to apply.
*
* @exception ServletException
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
/*
* This will attempt to find the location of the properties
* file from the relative path to the WAR archive (ie:
* docroot). Since JServ returns null for getRealPath()
* because it was never implemented correctly, then we know we
* will not have an issue with using it this way. I don't know
* if this will break other servlet engines, but it probably
* shouldn't since WAR files are the future anyways.
*/
if ( propsFile != null )
{
String realPath = getServletContext().getRealPath(propsFile);
if ( realPath != null )
propsFile = realPath;
}
try
{
Runtime.init(propsFile);
defaultContentType =
Runtime.getString(Runtime.DEFAULT_CONTENT_TYPE, "text/html");
encoding = Runtime.getString(Runtime.TEMPLATE_ENCODING, "8859_1");
}
catch( Exception e )
{
throw new ServletException("Error configuring the loader: " + e);
}
}
/**
* Handles GET
*/
public final void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handle a POST
*/
public final void doPost( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Process the request.
*/
private void doRequest(HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
ServletOutputStream output = response.getOutputStream();
String contentType = null;
VelocityWriter vw = null;
try
{
// create a new context
Context context = new Context();
// put the request/response objects into the context
context.put (REQUEST, request);
context.put (RESPONSE, response);
// check for a content type in the context
if (context.containsKey(CONTENT_TYPE))
{
contentType = (String) context.get (CONTENT_TYPE);
}
else
{
contentType = defaultContentType;
}
// set the content type
response.setContentType(contentType);
// call whomever extends this class and implements this method
Template template = handleRequest(context);
// could not find the template
if ( template == null )
throw new Exception ("Cannot find the template!" );
vw = (VelocityWriter) writerPool.get();
if (vw == null)
vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4*1024, true);
else
vw.recycle(new OutputStreamWriter(output, encoding));
template.merge( context, vw);
}
catch (Exception e)
{
// display error messages
error (output, e.getMessage());
}
finally
{
try
{
if (vw != null)
{
vw.flush();
writerPool.put(vw);
output.close();
}
}
catch (Exception e)
{
// do nothing
}
}
}
/**
* Retrieves the requested template.
*
* @param name The file name of the template to retrieve relative to the
* <code>template.path</code> property.
* @return The requested template.
*/
public Template getTemplate( String name )
throws Exception
{
return Runtime.getTemplate(name);
}
/**
* Implement this method to add your application data to the context,
* calling the <code>getTemplate()</code> method to produce your return
* value.
*
* @param ctx The context to add your data to.
* @return The template to merge with your context.
*/
protected abstract Template handleRequest( Context ctx );
/**
* Send an error message to the client.
*/
private final void error( ServletOutputStream out, String message )
throws ServletException, IOException
{
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<body bgcolor=\"#ffffff\">");
html.append("<h2>Error processing the template</h2>");
html.append(message);
html.append("</body>");
html.append("</html>");
out.print( html.toString() );
}
}
|
package org.jdesktop.swingx.graphics;
import java.awt.Composite;
import java.awt.CompositeContext;
import java.awt.RenderingHints;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.RasterFormatException;
/**
* <p>A blend composite defines the rule according to which a drawing primitive
* (known as the source) is mixed with existing graphics (know as the
* destination.)</p>
* <p><code>BlendComposite</code> is an implementation of the
* {@link java.awt.Composite} interface and must therefore be set as a state on
* a {@link java.awt.Graphics2D} surface.</p>
* <p>Please refer to {@link java.awt.Graphics2D#setComposite(java.awt.Composite)}
* for more information on how to use this class with a graphics surface.</p>
* <h2>Blending Modes</h2>
* <p>This class offers a certain number of blending modes, or compositing
* rules. These rules are inspired from graphics editing software packages,
* like <em>Adobe Photoshop</em> or <em>The GIMP</em>.</p>
* <p>Given the wide variety of implemented blending modes and the difficulty
* to describe them with words, please refer to those tools to visually see
* the result of these blending modes.</p>
* <h2>Opacity</h2>
* <p>Each blending mode has an associated opacity, defined as a float value
* between 0.0 and 1.0. Changing the opacity controls the force with which the
* compositing operation is applied. For instance, a composite with an opacity
* of 0.0 will not draw the source onto the destination. With an opacity of
* 1.0, the source will be fully drawn onto the destination, according to the
* selected blending mode rule.</p>
* <p>The opacity, or alpha value, is used by the composite instance to mutiply
* the alpha value of each pixel of the source when being composited over the
* destination.</p>
* <h2>Creating a Blend Composite</h2>
* <p>Blend composites can be created in various manners:</p>
* <ul>
* <li>Use one of the pre-defined instance. Example:
* <code>BlendComposite.Average</code>.</li>
* <li>Derive one of the pre-defined instances by calling
* {@link #derive(float)} or {@link #derive(BlendingMode)}. Deriving allows
* you to change either the opacity or the blending mode. Example:
* <code>BlendComposite.Average.derive(0.5f)</code>.</li>
* <li>Use a factory method: {@link #getInstance(BlendingMode)} or
* {@link #getInstance(BlendingMode, float)}.</li>
* </ul>
* <h2>Implementation Caveat</h2>
* <p>TThe blending mode <em>SoftLight</em> has not been implemented yet.</p>
*
* @see org.jdesktop.swingx.graphics.BlendComposite.BlendingMode
* @see java.awt.Graphics2D
* @see java.awt.Composite
* @see java.awt.AlphaComposite
* @author Romain Guy <romain.guy@mac.com>
*/
public final class BlendComposite implements Composite {
/**
* <p>A blending mode defines the compositing rule of a
* {@link org.jdesktop.swingx.graphics.BlendComposite}.</p>
*
* @author Romain Guy <romain.guy@mac.com>
*/
public enum BlendingMode {
AVERAGE,
MULTIPLY,
SCREEN,
DARKEN,
LIGHTEN,
OVERLAY,
HARD_LIGHT,
SOFT_LIGHT,
DIFFERENCE,
NEGATION,
EXCLUSION,
COLOR_DODGE,
INVERSE_COLOR_DODGE,
SOFT_DODGE,
COLOR_BURN,
INVERSE_COLOR_BURN,
SOFT_BURN,
REFLECT,
GLOW,
FREEZE,
HEAT,
ADD,
SUBTRACT,
STAMP,
RED,
GREEN,
BLUE,
HUE,
SATURATION,
COLOR,
LUMINOSITY
}
public static final BlendComposite Average = new BlendComposite(BlendingMode.AVERAGE);
public static final BlendComposite Multiply = new BlendComposite(BlendingMode.MULTIPLY);
public static final BlendComposite Screen = new BlendComposite(BlendingMode.SCREEN);
public static final BlendComposite Darken = new BlendComposite(BlendingMode.DARKEN);
public static final BlendComposite Lighten = new BlendComposite(BlendingMode.LIGHTEN);
public static final BlendComposite Overlay = new BlendComposite(BlendingMode.OVERLAY);
public static final BlendComposite HardLight = new BlendComposite(BlendingMode.HARD_LIGHT);
public static final BlendComposite SoftLight = new BlendComposite(BlendingMode.SOFT_LIGHT);
public static final BlendComposite Difference = new BlendComposite(BlendingMode.DIFFERENCE);
public static final BlendComposite Negation = new BlendComposite(BlendingMode.NEGATION);
public static final BlendComposite Exclusion = new BlendComposite(BlendingMode.EXCLUSION);
public static final BlendComposite ColorDodge = new BlendComposite(BlendingMode.COLOR_DODGE);
public static final BlendComposite InverseColorDodge = new BlendComposite(BlendingMode.INVERSE_COLOR_DODGE);
public static final BlendComposite SoftDodge = new BlendComposite(BlendingMode.SOFT_DODGE);
public static final BlendComposite ColorBurn = new BlendComposite(BlendingMode.COLOR_BURN);
public static final BlendComposite InverseColorBurn = new BlendComposite(BlendingMode.INVERSE_COLOR_BURN);
public static final BlendComposite SoftBurn = new BlendComposite(BlendingMode.SOFT_BURN);
public static final BlendComposite Reflect = new BlendComposite(BlendingMode.REFLECT);
public static final BlendComposite Glow = new BlendComposite(BlendingMode.GLOW);
public static final BlendComposite Freeze = new BlendComposite(BlendingMode.FREEZE);
public static final BlendComposite Heat = new BlendComposite(BlendingMode.HEAT);
public static final BlendComposite Add = new BlendComposite(BlendingMode.ADD);
public static final BlendComposite Subtract = new BlendComposite(BlendingMode.SUBTRACT);
public static final BlendComposite Stamp = new BlendComposite(BlendingMode.STAMP);
public static final BlendComposite Red = new BlendComposite(BlendingMode.RED);
public static final BlendComposite Green = new BlendComposite(BlendingMode.GREEN);
public static final BlendComposite Blue = new BlendComposite(BlendingMode.BLUE);
public static final BlendComposite Hue = new BlendComposite(BlendingMode.HUE);
public static final BlendComposite Saturation = new BlendComposite(BlendingMode.SATURATION);
public static final BlendComposite Color = new BlendComposite(BlendingMode.COLOR);
public static final BlendComposite Luminosity = new BlendComposite(BlendingMode.LUMINOSITY);
private final float alpha;
private final BlendingMode mode;
private BlendComposite(BlendingMode mode) {
this(mode, 1.0f);
}
private BlendComposite(BlendingMode mode, float alpha) {
this.mode = mode;
if (alpha < 0.0f || alpha > 1.0f) {
throw new IllegalArgumentException(
"alpha must be comprised between 0.0f and 1.0f");
}
this.alpha = alpha;
}
/**
* <p>Creates a new composite based on the blending mode passed
* as a parameter. A default opacity of 1.0 is applied.</p>
*
* @param mode the blending mode defining the compositing rule
* @return a new <code>BlendComposite</code> based on the selected blending
* mode, with an opacity of 1.0
*/
public static BlendComposite getInstance(BlendingMode mode) {
return new BlendComposite(mode);
}
public static BlendComposite getInstance(BlendingMode mode, float alpha) {
return new BlendComposite(mode, alpha);
}
/**
* <p>Returns a <code>BlendComposite</code> object that uses the specified
* blending mode and this object's alpha value. If the newly specified
* blending mode is the same as this object's, this object is returned.</p>
*
* @param mode the blending mode defining the compositing rule
* @return a <code>BlendComposite</code> object derived from this object,
* that uses the specified blending mode
*/
public BlendComposite derive(BlendingMode mode) {
return this.mode == mode ? this : new BlendComposite(mode, getAlpha());
}
public BlendComposite derive(float alpha) {
return this.alpha == alpha ? this : new BlendComposite(getMode(), alpha);
}
/**
* <p>Returns the opacity of this composite. If no opacity has been defined,
* 1.0 is returned.</p>
*
* @return the alpha value, or opacity, of this object
*/
public float getAlpha() {
return alpha;
}
/**
* <p>Returns the blending mode of this composite.</p>
*
* @return the blending mode used by this object
*/
public BlendingMode getMode() {
return mode;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Float.floatToIntBits(alpha) * 31 + mode.ordinal();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BlendComposite)) {
return false;
}
BlendComposite bc = (BlendComposite) obj;
return mode == bc.mode && alpha == bc.alpha;
}
private static boolean isRgbColorModel(ColorModel cm) {
if (cm instanceof DirectColorModel &&
cm.getTransferType() == DataBuffer.TYPE_INT) {
DirectColorModel directCM = (DirectColorModel) cm;
return directCM.getRedMask() == 0x00FF0000 &&
directCM.getGreenMask() == 0x0000FF00 &&
directCM.getBlueMask() == 0x000000FF &&
(directCM.getNumComponents() == 3 ||
directCM.getAlphaMask() == 0xFF000000);
}
return false;
}
private static boolean isBgrColorModel(ColorModel cm) {
if (cm instanceof DirectColorModel &&
cm.getTransferType() == DataBuffer.TYPE_INT) {
DirectColorModel directCM = (DirectColorModel) cm;
return directCM.getRedMask() == 0x000000FF &&
directCM.getGreenMask() == 0x0000FF00 &&
directCM.getBlueMask() == 0x00FF0000 &&
(directCM.getNumComponents() == 3 ||
directCM.getAlphaMask() == 0xFF000000);
}
return false;
}
/**
* {@inheritDoc}
*/
public CompositeContext createContext(ColorModel srcColorModel,
ColorModel dstColorModel,
RenderingHints hints) {
if (isRgbColorModel(srcColorModel) && isRgbColorModel(dstColorModel)) {
return new BlendingRgbContext(this);
} else if (isBgrColorModel(srcColorModel) && isBgrColorModel(dstColorModel)) {
return new BlendingBgrContext(this);
}
throw new RasterFormatException("Incompatible color models");
}
private static abstract class BlendingContext implements CompositeContext {
protected final Blender blender;
protected final BlendComposite composite;
private BlendingContext(BlendComposite composite) {
this.composite = composite;
this.blender = Blender.getBlenderFor(composite);
}
public void dispose() {
}
}
private static class BlendingRgbContext extends BlendingContext {
private BlendingRgbContext(BlendComposite composite) {
super(composite);
}
public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
int width = Math.min(src.getWidth(), dstIn.getWidth());
int height = Math.min(src.getHeight(), dstIn.getHeight());
float alpha = composite.getAlpha();
int[] result = new int[4];
int[] srcPixel = new int[4];
int[] dstPixel = new int[4];
int[] srcPixels = new int[width];
int[] dstPixels = new int[width];
for (int y = 0; y < height; y++) {
src.getDataElements(0, y, width, 1, srcPixels);
dstIn.getDataElements(0, y, width, 1, dstPixels);
for (int x = 0; x < width; x++) {
// pixels are stored as INT_ARGB
// our arrays are [R, G, B, A]
int pixel = srcPixels[x];
srcPixel[0] = (pixel >> 16) & 0xFF;
srcPixel[1] = (pixel >> 8) & 0xFF;
srcPixel[2] = (pixel ) & 0xFF;
srcPixel[3] = (pixel >> 24) & 0xFF;
pixel = dstPixels[x];
dstPixel[0] = (pixel >> 16) & 0xFF;
dstPixel[1] = (pixel >> 8) & 0xFF;
dstPixel[2] = (pixel ) & 0xFF;
dstPixel[3] = (pixel >> 24) & 0xFF;
blender.blend(srcPixel, dstPixel, result);
// mixes the result with the opacity
dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 |
((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 |
((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 |
(int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF;
}
dstOut.setDataElements(0, y, width, 1, dstPixels);
}
}
}
private static class BlendingBgrContext extends BlendingContext {
private BlendingBgrContext(BlendComposite composite) {
super(composite);
}
public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
int width = Math.min(src.getWidth(), dstIn.getWidth());
int height = Math.min(src.getHeight(), dstIn.getHeight());
float alpha = composite.getAlpha();
int[] result = new int[4];
int[] srcPixel = new int[4];
int[] dstPixel = new int[4];
int[] srcPixels = new int[width];
int[] dstPixels = new int[width];
for (int y = 0; y < height; y++) {
src.getDataElements(0, y, width, 1, srcPixels);
dstIn.getDataElements(0, y, width, 1, dstPixels);
for (int x = 0; x < width; x++) {
// pixels are stored as INT_ABGR
// our arrays are [R, G, B, A]
int pixel = srcPixels[x];
srcPixel[0] = (pixel ) & 0xFF;
srcPixel[1] = (pixel >> 8) & 0xFF;
srcPixel[2] = (pixel >> 16) & 0xFF;
srcPixel[3] = (pixel >> 24) & 0xFF;
pixel = dstPixels[x];
dstPixel[0] = (pixel ) & 0xFF;
dstPixel[1] = (pixel >> 8) & 0xFF;
dstPixel[2] = (pixel >> 16) & 0xFF;
dstPixel[3] = (pixel >> 24) & 0xFF;
blender.blend(srcPixel, dstPixel, result);
// mixes the result with the opacity
dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 |
((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) |
((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 |
((int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF) << 16;
}
dstOut.setDataElements(0, y, width, 1, dstPixels);
}
}
}
private static abstract class Blender {
public abstract void blend(int[] src, int[] dst, int[] result);
public static Blender getBlenderFor(BlendComposite composite) {
switch (composite.getMode()) {
case ADD:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.min(255, src[0] + dst[0]);
result[1] = Math.min(255, src[1] + dst[1]);
result[2] = Math.min(255, src[2] + dst[2]);
result[3] = Math.min(255, src[3] + dst[3]);
}
};
case AVERAGE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = (src[0] + dst[0]) >> 1;
result[1] = (src[1] + dst[1]) >> 1;
result[2] = (src[2] + dst[2]) >> 1;
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case BLUE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0];
result[1] = src[1];
result[2] = dst[2];
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case COLOR:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
float[] srcHSL = new float[3];
ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL);
float[] dstHSL = new float[3];
ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL);
ColorUtilities.HSLtoRGB(srcHSL[0], srcHSL[1], dstHSL[2], result);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case COLOR_BURN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0] == 0 ? 0 :
Math.max(0, 255 - (((255 - dst[0]) << 8) / src[0]));
result[1] = src[1] == 0 ? 0 :
Math.max(0, 255 - (((255 - dst[1]) << 8) / src[1]));
result[2] = src[2] == 0 ? 0 :
Math.max(0, 255 - (((255 - dst[2]) << 8) / src[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case COLOR_DODGE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0] == 255 ? 255 :
Math.min((dst[0] << 8) / (255 - src[0]), 255);
result[1] = src[1] == 255 ? 255 :
Math.min((dst[1] << 8) / (255 - src[1]), 255);
result[2] = src[2] == 255 ? 255 :
Math.min((dst[2] << 8) / (255 - src[2]), 255);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case DARKEN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.min(src[0], dst[0]);
result[1] = Math.min(src[1], dst[1]);
result[2] = Math.min(src[2], dst[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case DIFFERENCE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.abs(dst[0] - src[0]);
result[1] = Math.abs(dst[1] - src[1]);
result[2] = Math.abs(dst[2] - src[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case EXCLUSION:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] + src[0] - (dst[0] * src[0] >> 7);
result[1] = dst[1] + src[1] - (dst[1] * src[1] >> 7);
result[2] = dst[2] + src[2] - (dst[2] * src[2] >> 7);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case FREEZE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0] == 0 ? 0 :
Math.max(0, 255 - (255 - dst[0]) * (255 - dst[0]) / src[0]);
result[1] = src[1] == 0 ? 0 :
Math.max(0, 255 - (255 - dst[1]) * (255 - dst[1]) / src[1]);
result[2] = src[2] == 0 ? 0 :
Math.max(0, 255 - (255 - dst[2]) * (255 - dst[2]) / src[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case GLOW:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] == 255 ? 255 :
Math.min(255, src[0] * src[0] / (255 - dst[0]));
result[1] = dst[1] == 255 ? 255 :
Math.min(255, src[1] * src[1] / (255 - dst[1]));
result[2] = dst[2] == 255 ? 255 :
Math.min(255, src[2] * src[2] / (255 - dst[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case GREEN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0];
result[1] = dst[1];
result[2] = src[2];
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case HARD_LIGHT:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0] < 128 ? dst[0] * src[0] >> 7 :
255 - ((255 - src[0]) * (255 - dst[0]) >> 7);
result[1] = src[1] < 128 ? dst[1] * src[1] >> 7 :
255 - ((255 - src[1]) * (255 - dst[1]) >> 7);
result[2] = src[2] < 128 ? dst[2] * src[2] >> 7 :
255 - ((255 - src[2]) * (255 - dst[2]) >> 7);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case HEAT:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] == 0 ? 0 :
Math.max(0, 255 - (255 - src[0]) * (255 - src[0]) / dst[0]);
result[1] = dst[1] == 0 ? 0 :
Math.max(0, 255 - (255 - src[1]) * (255 - src[1]) / dst[1]);
result[2] = dst[2] == 0 ? 0 :
Math.max(0, 255 - (255 - src[2]) * (255 - src[2]) / dst[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case HUE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
float[] srcHSL = new float[3];
ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL);
float[] dstHSL = new float[3];
ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL);
ColorUtilities.HSLtoRGB(srcHSL[0], dstHSL[1], dstHSL[2], result);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case INVERSE_COLOR_BURN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] == 0 ? 0 :
Math.max(0, 255 - (((255 - src[0]) << 8) / dst[0]));
result[1] = dst[1] == 0 ? 0 :
Math.max(0, 255 - (((255 - src[1]) << 8) / dst[1]));
result[2] = dst[2] == 0 ? 0 :
Math.max(0, 255 - (((255 - src[2]) << 8) / dst[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case INVERSE_COLOR_DODGE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] == 255 ? 255 :
Math.min((src[0] << 8) / (255 - dst[0]), 255);
result[1] = dst[1] == 255 ? 255 :
Math.min((src[1] << 8) / (255 - dst[1]), 255);
result[2] = dst[2] == 255 ? 255 :
Math.min((src[2] << 8) / (255 - dst[2]), 255);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case LIGHTEN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.max(src[0], dst[0]);
result[1] = Math.max(src[1], dst[1]);
result[2] = Math.max(src[2], dst[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case LUMINOSITY:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
float[] srcHSL = new float[3];
ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL);
float[] dstHSL = new float[3];
ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL);
ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case MULTIPLY:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = (src[0] * dst[0]) >> 8;
result[1] = (src[1] * dst[1]) >> 8;
result[2] = (src[2] * dst[2]) >> 8;
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case NEGATION:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = 255 - Math.abs(255 - dst[0] - src[0]);
result[1] = 255 - Math.abs(255 - dst[1] - src[1]);
result[2] = 255 - Math.abs(255 - dst[2] - src[2]);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case OVERLAY:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] < 128 ? dst[0] * src[0] >> 7 :
255 - ((255 - dst[0]) * (255 - src[0]) >> 7);
result[1] = dst[1] < 128 ? dst[1] * src[1] >> 7 :
255 - ((255 - dst[1]) * (255 - src[1]) >> 7);
result[2] = dst[2] < 128 ? dst[2] * src[2] >> 7 :
255 - ((255 - dst[2]) * (255 - src[2]) >> 7);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case RED:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0];
result[1] = dst[1];
result[2] = dst[2];
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case REFLECT:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = src[0] == 255 ? 255 :
Math.min(255, dst[0] * dst[0] / (255 - src[0]));
result[1] = src[1] == 255 ? 255 :
Math.min(255, dst[1] * dst[1] / (255 - src[1]));
result[2] = src[2] == 255 ? 255 :
Math.min(255, dst[2] * dst[2] / (255 - src[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SATURATION:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
float[] srcHSL = new float[3];
ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL);
float[] dstHSL = new float[3];
ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL);
ColorUtilities.HSLtoRGB(dstHSL[0], srcHSL[1], dstHSL[2], result);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SCREEN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = 255 - ((255 - src[0]) * (255 - dst[0]) >> 8);
result[1] = 255 - ((255 - src[1]) * (255 - dst[1]) >> 8);
result[2] = 255 - ((255 - src[2]) * (255 - dst[2]) >> 8);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SOFT_BURN:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] + src[0] < 256 ?
(dst[0] == 255 ? 255 :
Math.min(255, (src[0] << 7) / (255 - dst[0]))) :
Math.max(0, 255 - (((255 - dst[0]) << 7) / src[0]));
result[1] = dst[1] + src[1] < 256 ?
(dst[1] == 255 ? 255 :
Math.min(255, (src[1] << 7) / (255 - dst[1]))) :
Math.max(0, 255 - (((255 - dst[1]) << 7) / src[1]));
result[2] = dst[2] + src[2] < 256 ?
(dst[2] == 255 ? 255 :
Math.min(255, (src[2] << 7) / (255 - dst[2]))) :
Math.max(0, 255 - (((255 - dst[2]) << 7) / src[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SOFT_DODGE:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = dst[0] + src[0] < 256 ?
(src[0] == 255 ? 255 :
Math.min(255, (dst[0] << 7) / (255 - src[0]))) :
Math.max(0, 255 - (((255 - src[0]) << 7) / dst[0]));
result[1] = dst[1] + src[1] < 256 ?
(src[1] == 255 ? 255 :
Math.min(255, (dst[1] << 7) / (255 - src[1]))) :
Math.max(0, 255 - (((255 - src[1]) << 7) / dst[1]));
result[2] = dst[2] + src[2] < 256 ?
(src[2] == 255 ? 255 :
Math.min(255, (dst[2] << 7) / (255 - src[2]))) :
Math.max(0, 255 - (((255 - src[2]) << 7) / dst[2]));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SOFT_LIGHT:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
int mRed = src[0] * dst[0] / 255;
int mGreen = src[1] * dst[1] / 255;
int mBlue = src[2] * dst[2] / 255;
result[0] = mRed + src[0] * (255 - ((255 - src[0]) * (255 - dst[0]) / 255) - mRed) / 255;
result[1] = mGreen + src[1] * (255 - ((255 - src[1]) * (255 - dst[1]) / 255) - mGreen) / 255;
result[2] = mBlue + src[2] * (255 - ((255 - src[2]) * (255 - dst[2]) / 255) - mBlue) / 255;
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case STAMP:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.max(0, Math.min(255, dst[0] + 2 * src[0] - 256));
result[1] = Math.max(0, Math.min(255, dst[1] + 2 * src[1] - 256));
result[2] = Math.max(0, Math.min(255, dst[2] + 2 * src[2] - 256));
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
case SUBTRACT:
return new Blender() {
@Override
public void blend(int[] src, int[] dst, int[] result) {
result[0] = Math.max(0, src[0] + dst[0] - 256);
result[1] = Math.max(0, src[1] + dst[1] - 256);
result[2] = Math.max(0, src[2] + dst[2] - 256);
result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
}
};
}
throw new IllegalArgumentException("Blender not implemented for " +
composite.getMode().name());
}
}
}
|
package org.joda.time.format;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.PeriodType;
import org.joda.time.ReadWritablePeriod;
import org.joda.time.ReadablePeriod;
/**
* PeriodFormatterBuilder is used for constructing {@link PeriodFormatter}s.
* PeriodFormatters are built by appending specific fields and separators.
*
* <p>
* For example, a formatter that prints years and months, like "15 years and 8 months",
* can be constructed as follows:
* <p>
* <pre>
* PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
* .printZeroAlways()
* .appendYears()
* .appendSuffix(" year", " years")
* .appendSeparator(" and ")
* .printZeroRarely()
* .appendMonths()
* .appendSuffix(" month", " months")
* .toFormatter();
* </pre>
* <p>
* PeriodFormatterBuilder itself is mutable and not thread-safe, but the
* formatters that it builds are thread-safe and immutable.
*
* @see PeriodFormat
* @author Brian S O'Neill
*/
public class PeriodFormatterBuilder {
private static final int PRINT_ZERO_RARELY = 1;
private static final int PRINT_ZERO_IF_SUPPORTED = 2;
private static final int PRINT_ZERO_ALWAYS = 3;
private boolean iFavorFirstFieldForZero;
private int iMinPrintedDigits;
private int iPrintZeroSetting;
private int iMaxParsedDigits;
private boolean iRejectSignedValues;
private PeriodFieldAffix iPrefix;
// List of PeriodFormatters used to build a final formatter.
private List iFormatters;
// List of PeriodFormatters used to build an alternate formatter. The
// alternate is chosen if no other fields are printed.
private List iAlternateFormatters;
public PeriodFormatterBuilder() {
clear();
}
/**
* Converts to a PeriodPrinter that prints using all the appended
* elements. Subsequent changes to this builder do not affect the returned
* printer.
*/
public PeriodPrinter toPrinter() {
return toFormatter();
}
/**
* Converts to a PeriodParser that parses using all the appended
* elements. Subsequent changes to this builder do not affect the returned
* parser.
*/
public PeriodParser toParser() {
return toFormatter();
}
/**
* Converts to a PeriodFormatter that formats using all the appended
* elements. Subsequent changes to this builder do not affect the returned
* formatter.
*/
public PeriodFormatter toFormatter() {
PeriodFormatter formatter = toFormatter(iFormatters);
List altFormatters = iAlternateFormatters;
if (altFormatters.size() > 0) {
// Alternate is needed only if field formatters were
// appended. Literals may have been appended as well.
for (int i=altFormatters.size(); --i>=0; ) {
if (altFormatters.get(i) instanceof FieldFormatter) {
formatter = new AlternateSelector
(formatter, altFormatters, iFavorFirstFieldForZero);
break;
}
}
}
return formatter;
}
private static PeriodFormatter toFormatter(List formatters) {
int size = formatters.size();
if (size >= 1 && formatters.get(0) instanceof Separator) {
Separator sep = (Separator) formatters.get(0);
return sep.finish(toFormatter(formatters.subList(1, size)));
}
return createComposite(formatters);
}
/**
* Clears out all the appended elements, allowing this builder to be
* reused.
*/
public void clear() {
iFavorFirstFieldForZero = false;
iMinPrintedDigits = 1;
iPrintZeroSetting = PRINT_ZERO_RARELY;
iMaxParsedDigits = 10;
iRejectSignedValues = false;
iPrefix = null;
if (iFormatters == null) {
iFormatters = new ArrayList();
} else {
iFormatters.clear();
}
if (iAlternateFormatters == null) {
iAlternateFormatters = new ArrayList();
} else {
iAlternateFormatters.clear();
}
}
/**
* Appends another formatter.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder append(PeriodFormatter formatter)
throws IllegalArgumentException
{
if (formatter == null) {
throw new IllegalArgumentException("No formatter supplied");
}
clearPrefix();
iFormatters.add(formatter);
return this;
}
public PeriodFormatterBuilder appendLiteral(String text) {
if (text == null) {
throw new IllegalArgumentException("Literal must not be null");
}
clearPrefix();
Literal literal = new Literal(text);
iFormatters.add(literal);
iAlternateFormatters.add(literal);
return this;
}
/**
* Set the minimum digits printed for the next and following appended
* fields. By default, the minimum digits printed is one. If the field value
* is zero, it is not printed unless a printZero rule is applied.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder minimumPrintedDigits(int minDigits) {
iMinPrintedDigits = minDigits;
return this;
}
/**
* Set the maximum digits parsed for the next and following appended
* fields. By default, the maximum digits parsed is ten.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder maximumParsedDigits(int maxDigits) {
iMaxParsedDigits = maxDigits;
return this;
}
/**
* Reject signed values when parsing the next and following appended fields.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder rejectSignedValues(boolean v) {
iRejectSignedValues = v;
return this;
}
/**
* Never print zero values for the next and following appended fields,
* unless no fields would be printed. If no fields are printed, the printer
* forces at most one "printZeroRarely" field to print a zero.
* <p>
* This field setting is the default.
*
* @return this PeriodFormatterBuilder
* @see #favorLastFieldForZero()
* @see #favorFirstFieldForZero()
*/
public PeriodFormatterBuilder printZeroRarely() {
iPrintZeroSetting = PRINT_ZERO_RARELY;
return this;
}
/**
* Print zero values for the next and following appened fields only if the
* period supports it.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder printZeroIfSupported() {
iPrintZeroSetting = PRINT_ZERO_IF_SUPPORTED;
return this;
}
/**
* Always print zero values for the next and following appended fields,
* even if the period doesn't support it. The parser requires values for
* fields that always print zero.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder printZeroAlways() {
iPrintZeroSetting = PRINT_ZERO_ALWAYS;
return this;
}
/**
* Append a field prefix which applies only to the next appended field. If
* the field is not printed, neither is the prefix.
*
* @param text text to print before field only if field is printed
* @return this PeriodFormatterBuilder
* @see #appendSuffix
*/
public PeriodFormatterBuilder appendPrefix(String text) {
if (text == null) {
throw new IllegalArgumentException();
}
return appendPrefix(new SimpleAffix(text));
}
/**
* Append a field prefix which applies only to the next appended field. If
* the field is not printed, neither is the prefix.
* <p>
* During parsing, the singular and plural versions are accepted whether
* or not the actual value matches plurality.
*
* @param singularText text to print if field value is one
* @param pluralText text to print if field value is not one
* @return this PeriodFormatterBuilder
* @see #appendSuffix
*/
public PeriodFormatterBuilder appendPrefix(String singularText,
String pluralText) {
if (singularText == null || pluralText == null) {
throw new IllegalArgumentException();
}
return appendPrefix(new PluralAffix(singularText, pluralText));
}
/**
* Append a field prefix which applies only to the next appended field. If
* the field is not printed, neither is the prefix.
*
* @param prefix custom prefix
* @return this PeriodFormatterBuilder
* @see #appendSuffix
*/
private PeriodFormatterBuilder appendPrefix(PeriodFieldAffix prefix) {
if (prefix == null) {
throw new IllegalArgumentException();
}
if (iPrefix != null) {
prefix = new CompositeAffix(iPrefix, prefix);
}
iPrefix = prefix;
return this;
}
/**
* Instruct the printer to emit an integer years field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendYears() {
appendField(1);
return this;
}
/**
* Instruct the printer to emit an integer years field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendMonths() {
appendField(2);
return this;
}
/**
* Instruct the printer to emit an integer weeks field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendWeeks() {
appendField(3);
return this;
}
/**
* Instruct the printer to emit an integer days field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendDays() {
appendField(4);
return this;
}
/**
* Instruct the printer to emit an integer hours field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendHours() {
appendField(5);
return this;
}
/**
* Instruct the printer to emit an integer minutes field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendMinutes() {
appendField(6);
return this;
}
/**
* Instruct the printer to emit an integer seconds field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendSeconds() {
appendField(7);
return this;
}
/**
* Instruct the printer to emit an integer millis field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendMillis() {
appendField(8);
return this;
}
/**
* Instruct the printer to emit an integer millis field, if supported.
*
* @return this PeriodFormatterBuilder
*/
public PeriodFormatterBuilder appendMillis3Digit() {
appendField(8, 3);
return this;
}
private void appendField(int type) {
appendField(type, iMinPrintedDigits);
}
private void appendField(int type, int minPrinted) {
FieldFormatter field = new FieldFormatter(minPrinted, iPrintZeroSetting,
iMaxParsedDigits, iRejectSignedValues, type, iPrefix, null);
iFormatters.add(field);
if (iPrintZeroSetting == PRINT_ZERO_RARELY) {
iAlternateFormatters.add(field);
}
iPrefix = null;
}
public PeriodFormatterBuilder appendSuffix(String text) {
if (text == null) {
throw new IllegalArgumentException();
}
return appendSuffix(new SimpleAffix(text));
}
public PeriodFormatterBuilder appendSuffix(String singularText,
String pluralText) {
if (singularText == null || pluralText == null) {
throw new IllegalArgumentException();
}
return appendSuffix(new PluralAffix(singularText, pluralText));
}
private PeriodFormatterBuilder appendSuffix(PeriodFieldAffix suffix) {
final Object originalField;
if (iFormatters.size() > 0) {
originalField = iFormatters.get(iFormatters.size() - 1);
} else {
originalField = null;
}
if (originalField == null || !(originalField instanceof FieldFormatter)) {
throw new IllegalStateException("No field to apply suffix to");
}
clearPrefix();
Object newField = new FieldFormatter((FieldFormatter) originalField, suffix);
iFormatters.set(iFormatters.size() - 1, newField);
int index = iAlternateFormatters.lastIndexOf(originalField);
if (index >= 0) {
iAlternateFormatters.set(index, newField);
}
return this;
}
public PeriodFormatterBuilder appendSeparator(String text) {
return appendSeparator(text, text, true, true);
}
public PeriodFormatterBuilder appendSeparatorIfFieldsAfter(String text) {
return appendSeparator(text, text, false, true);
}
public PeriodFormatterBuilder appendSeparatorIfFieldsBefore(String text) {
return appendSeparator(text, text, true, false);
}
public PeriodFormatterBuilder appendSeparator(String text, String finalText) {
return appendSeparator(text, finalText, true, true);
}
private PeriodFormatterBuilder appendSeparator(String text, String finalText, boolean useBefore, boolean useAfter) {
if (text == null || finalText == null) {
throw new IllegalArgumentException();
}
clearPrefix();
// optimise zero formatter case
List formatters = iFormatters;
if (formatters.size() == 0) {
if (useAfter && useBefore == false) {
formatters.add(new Separator(text, finalText, Literal.EMPTY, useBefore, useAfter));
}
return this;
}
// find the last separator added
int i;
Separator lastSeparator = null;
for (i=formatters.size(); --i>=0; ) {
if (formatters.get(i) instanceof Separator) {
lastSeparator = (Separator) formatters.get(i);
formatters = formatters.subList(i + 1, formatters.size());
break;
}
}
// merge formatters
if (lastSeparator != null && formatters.size() == 0) {
throw new IllegalStateException("Cannot have two adjacent separators");
} else {
PeriodFormatter composite = createComposite(formatters);
formatters.clear();
formatters.add(new Separator(text, finalText, composite, useBefore, useAfter));
}
return this;
}
/**
* If the printer doesn't print any field values, it forces a
* "printZeroRarely" field to print. This setting controls which field is
* selected.
* <p>
* It starts from the last appended field, and moves towards the first,
* stopping until it finds a field that is supported by the period being
* printed. If no supported fields are found, then no fields are printed.
* <p>
* This setting is the default.
*
* @return this PeriodFormatterBuilder
* @see #printZeroRarely()
*/
public PeriodFormatterBuilder favorLastFieldForZero() {
iFavorFirstFieldForZero = false;
return this;
}
/**
* If the printer doesn't print any field values, it forces a
* "printZeroRarely" field to print. This setting controls which field is
* selected.
* <p>
* It starts from the first appended field, and moves towards the last,
* stopping until it finds a field that is supported by the period being
* printed. If no supported fields are found, then no fields are printed.
*
* @return this PeriodFormatterBuilder
* @see #printZeroRarely()
*/
public PeriodFormatterBuilder favorFirstFieldForZero() {
iFavorFirstFieldForZero = true;
return this;
}
private void clearPrefix() throws IllegalStateException {
if (iPrefix != null) {
throw new IllegalStateException("Prefix not followed by field");
}
iPrefix = null;
}
private static PeriodFormatter createComposite(List formatters) {
switch (formatters.size()) {
case 0:
return Literal.EMPTY;
case 1:
return (PeriodFormatter) formatters.get(0);
default:
return new Composite(formatters);
}
}
/**
* Defines a formatted field's prefix or suffix text.
* This can be used for fields such as 'n hours' or 'nH' or 'Hour:n'.
*/
private static interface PeriodFieldAffix {
int calculatePrintedLength(int value);
void printTo(StringBuffer buf, int value);
void printTo(Writer out, int value) throws IOException;
/**
* @return new position after parsing affix, or ~position of failure
*/
int parse(String periodStr, int position);
/**
* @return position where affix starts, or original ~position if not found
*/
int scan(String periodStr, int position);
}
/**
* Implements an affix where the text does not vary by the amount.
*/
private static final class SimpleAffix implements PeriodFieldAffix {
private final String iText;
SimpleAffix(String text) {
iText = text;
}
public int calculatePrintedLength(int value) {
return iText.length();
}
public void printTo(StringBuffer buf, int value) {
buf.append(iText);
}
public void printTo(Writer out, int value) throws IOException {
out.write(iText);
}
public int parse(String periodStr, int position) {
String text = iText;
int textLength = text.length();
if (periodStr.regionMatches(true, position, text, 0, textLength)) {
return position + textLength;
}
return ~position;
}
public int scan(String periodStr, final int position) {
String text = iText;
int textLength = text.length();
int sourceLength = periodStr.length();
for (int pos = position; pos < sourceLength; pos++) {
if (periodStr.regionMatches(true, pos, text, 0, textLength)) {
return pos;
}
}
return ~position;
}
}
/**
* Implements an affix where the text varies by the amount of the field.
* Only singular (1) and plural (not 1) are supported.
*/
private static final class PluralAffix implements PeriodFieldAffix {
private final String iSingularText;
private final String iPluralText;
PluralAffix(String singularText, String pluralText) {
iSingularText = singularText;
iPluralText = pluralText;
}
public int calculatePrintedLength(int value) {
return (value == 1 ? iSingularText : iPluralText).length();
}
public void printTo(StringBuffer buf, int value) {
buf.append(value == 1 ? iSingularText : iPluralText);
}
public void printTo(Writer out, int value) throws IOException {
out.write(value == 1 ? iSingularText : iPluralText);
}
public int parse(String periodStr, int position) {
String text1 = iPluralText;
String text2 = iSingularText;
if (text1.length() < text2.length()) {
// Swap in order to match longer one first.
String temp = text1;
text1 = text2;
text2 = temp;
}
if (periodStr.regionMatches
(true, position, text1, 0, text1.length())) {
return position + text1.length();
}
if (periodStr.regionMatches
(true, position, text2, 0, text2.length())) {
return position + text2.length();
}
return ~position;
}
public int scan(String periodStr, final int position) {
String text1 = iPluralText;
String text2 = iSingularText;
if (text1.length() < text2.length()) {
// Swap in order to match longer one first.
String temp = text1;
text1 = text2;
text2 = temp;
}
int textLength1 = text1.length();
int textLength2 = text2.length();
int sourceLength = periodStr.length();
for (int pos = position; pos < sourceLength; pos++) {
if (periodStr.regionMatches(true, pos, text1, 0, textLength1)) {
return pos;
}
if (periodStr.regionMatches(true, pos, text2, 0, textLength2)) {
return pos;
}
}
return ~position;
}
}
/**
* Builds a composite affix by merging two other affix implementations.
*/
private static final class CompositeAffix implements PeriodFieldAffix {
private final PeriodFieldAffix iLeft;
private final PeriodFieldAffix iRight;
CompositeAffix(PeriodFieldAffix left, PeriodFieldAffix right) {
iLeft = left;
iRight = right;
}
public int calculatePrintedLength(int value) {
return iLeft.calculatePrintedLength(value)
+ iRight.calculatePrintedLength(value);
}
public void printTo(StringBuffer buf, int value) {
iLeft.printTo(buf, value);
iRight.printTo(buf, value);
}
public void printTo(Writer out, int value) throws IOException {
iLeft.printTo(out, value);
iRight.printTo(out, value);
}
public int parse(String periodStr, int position) {
position = iLeft.parse(periodStr, position);
if (position >= 0) {
position = iRight.parse(periodStr, position);
}
return position;
}
public int scan(String periodStr, final int position) {
int pos = iLeft.scan(periodStr, position);
if (pos >= 0) {
return iRight.scan(periodStr, pos);
}
return ~position;
}
}
/**
* Formats the numeric value of a field, potentially with prefix/suffix.
*/
private static final class FieldFormatter extends AbstractPeriodFormatter
implements PeriodFormatter
{
private final int iMinPrintedDigits;
private final int iPrintZeroSetting;
private final int iMaxParsedDigits;
private final boolean iRejectSignedValues;
private final int iFieldType;
private final PeriodFieldAffix iPrefix;
private final PeriodFieldAffix iSuffix;
FieldFormatter(int minPrintedDigits, int printZeroSetting,
int maxParsedDigits, boolean rejectSignedValues,
int fieldType, PeriodFieldAffix prefix, PeriodFieldAffix suffix) {
iMinPrintedDigits = minPrintedDigits;
iPrintZeroSetting = printZeroSetting;
iMaxParsedDigits = maxParsedDigits;
iRejectSignedValues = rejectSignedValues;
iFieldType = fieldType;
iPrefix = prefix;
iSuffix = suffix;
}
FieldFormatter(FieldFormatter field, PeriodFieldAffix suffix) {
iMinPrintedDigits = field.iMinPrintedDigits;
iPrintZeroSetting = field.iPrintZeroSetting;
iMaxParsedDigits = field.iMaxParsedDigits;
iRejectSignedValues = field.iRejectSignedValues;
iFieldType = field.iFieldType;
iPrefix = field.iPrefix;
if (field.iSuffix != null) {
suffix = new CompositeAffix(field.iSuffix, suffix);
}
iSuffix = suffix;
}
FieldFormatter(FieldFormatter field, int printZeroSetting) {
iMinPrintedDigits = field.iMinPrintedDigits;
iPrintZeroSetting = printZeroSetting;
iMaxParsedDigits = field.iMaxParsedDigits;
iRejectSignedValues = field.iRejectSignedValues;
iFieldType = field.iFieldType;
iPrefix = field.iPrefix;
iSuffix = field.iSuffix;
}
public int countFieldsToPrint(ReadablePeriod period) {
if (iPrintZeroSetting == PRINT_ZERO_ALWAYS || getFieldValue(period) >= 0) {
return 1;
}
return 0;
}
public int countFieldsToPrint(ReadablePeriod period, int stopAt) {
return stopAt <= 0 ? 0 : countFieldsToPrint(period);
}
public int calculatePrintedLength(ReadablePeriod period) {
long valueLong = getFieldValue(period);
if (valueLong < 0) {
return 0;
}
int value = (int)valueLong;
int sum = Math.max
(FormatUtils.calculateDigitCount(value), iMinPrintedDigits);
if (value < 0) {
// Account for sign character
sum++;
}
PeriodFieldAffix affix;
if ((affix = iPrefix) != null) {
sum += affix.calculatePrintedLength(value);
}
if ((affix = iSuffix) != null) {
sum += affix.calculatePrintedLength(value);
}
return sum;
}
public void printTo(StringBuffer buf, ReadablePeriod period) {
long valueLong = getFieldValue(period);
if (valueLong < 0) {
return;
}
int value = (int)valueLong;
PeriodFieldAffix affix;
if ((affix = iPrefix) != null) {
affix.printTo(buf, value);
}
int minDigits = iMinPrintedDigits;
if (minDigits <= 1) {
FormatUtils.appendUnpaddedInteger(buf, value);
} else {
FormatUtils.appendPaddedInteger(buf, value, minDigits);
}
if ((affix = iSuffix) != null) {
affix.printTo(buf, value);
}
}
public void printTo(Writer out, ReadablePeriod period) throws IOException {
long valueLong = getFieldValue(period);
if (valueLong < 0) {
return;
}
int value = (int)valueLong;
PeriodFieldAffix affix;
if ((affix = iPrefix) != null) {
affix.printTo(out, value);
}
int minDigits = iMinPrintedDigits;
if (minDigits <= 1) {
FormatUtils.writeUnpaddedInteger(out, value);
} else {
FormatUtils.writePaddedInteger(out, value, minDigits);
}
if ((affix = iSuffix) != null) {
affix.printTo(out, value);
}
}
public int parseInto(ReadWritablePeriod period,
String text, int position) {
boolean mustParse = (iPrintZeroSetting == PRINT_ZERO_ALWAYS);
// Shortcut test.
if (position >= text.length()) {
return mustParse ? ~position : position;
}
if (iPrefix != null) {
position = iPrefix.parse(text, position);
if (position >= 0) {
// If prefix is found, then the parse must finish.
mustParse = true;
} else {
// Prefix not found, so bail.
if (!mustParse) {
// It's okay because parsing of this field is not
// required. Don't return an error. Fields down the
// chain can continue on, trying to parse.
return ~position;
}
return position;
}
}
int suffixPos = -1;
if (iSuffix != null && !mustParse) {
// Pre-scan the suffix, to help determine if this field must be
// parsed.
suffixPos = iSuffix.scan(text, position);
if (suffixPos >= 0) {
// If suffix is found, then parse must finish.
mustParse = true;
} else {
// Suffix not found, so bail.
if (!mustParse) {
// It's okay because parsing of this field is not
// required. Don't return an error. Fields down the
// chain can continue on, trying to parse.
return ~suffixPos;
}
return suffixPos;
}
}
if (!mustParse && !isSupported(period.getPeriodType())) {
// If parsing is not required and the field is not supported,
// exit gracefully so that another parser can continue on.
return position;
}
int limit;
if (suffixPos > 0) {
limit = Math.min(iMaxParsedDigits, suffixPos - position);
} else {
limit = Math.min(iMaxParsedDigits, text.length() - position);
}
boolean negative = false;
int length = 0;
while (length < limit) {
char c = text.charAt(position + length);
if (length == 0 && (c == '-' || c == '+') && !iRejectSignedValues) {
negative = c == '-';
if (negative) {
length++;
} else {
// Skip the '+' for parseInt to succeed.
position++;
}
// Expand the limit to disregard the sign character.
limit = Math.min(limit + 1, text.length() - position);
continue;
}
if (c < '0' || c > '9') {
break;
}
length++;
}
if (length == 0) {
return ~position;
}
if (position + length != suffixPos) {
// If there are additional non-digit characters before the
// suffix is reached, then assume that the suffix found belongs
// to a field not yet reached. Return original position so that
// another parser can continue on.
return position;
}
int value;
if (length >= 9) {
// Since value may exceed max, use stock parser which checks
// for this.
value = Integer.parseInt
(text.substring(position, position += length));
} else {
int i = position;
if (negative) {
i++;
}
value = text.charAt(i++) - '0';
position += length;
while (i < position) {
value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0';
}
if (negative) {
value = -value;
}
}
setFieldValue(period, value);
if (position >= 0 && iSuffix != null) {
position = iSuffix.parse(text, position);
}
return position;
}
/**
* @return negative value if nothing to print, otherwise lower 32 bits
* is signed int value.
*/
long getFieldValue(ReadablePeriod period) {
PeriodType type;
if (iPrintZeroSetting == PRINT_ZERO_ALWAYS) {
type = null; // Don't need to check if supported.
} else {
type = period.getPeriodType();
}
int value;
switch (iFieldType) {
default:
return -1;
case 1:
if (type != null && type.years().isSupported() == false) {
return -1;
}
value = period.getYears();
break;
case 2:
if (type != null && type.months().isSupported() == false) {
return -1;
}
value = period.getMonths();
break;
case 3:
if (type != null && type.weeks().isSupported() == false) {
return -1;
}
value = period.getWeeks();
break;
case 4:
if (type != null && type.days().isSupported() == false) {
return -1;
}
value = period.getDays();
break;
case 5:
if (type != null && type.hours().isSupported() == false) {
return -1;
}
value = period.getHours();
break;
case 6:
if (type != null && type.minutes().isSupported() == false) {
return -1;
}
value = period.getMinutes();
break;
case 7:
if (type != null && type.seconds().isSupported() == false) {
return -1;
}
value = period.getSeconds();
break;
case 8:
if (type != null && type.millis().isSupported() == false) {
return -1;
}
value = period.getMillis();
break;
}
if (value == 0 && iPrintZeroSetting == PRINT_ZERO_RARELY) {
return -1;
}
return value & 0xffffffffL;
}
boolean isSupported(PeriodType type) {
switch (iFieldType) {
default:
return false;
case 1:
return type.years().isSupported();
case 2:
return type.months().isSupported();
case 3:
return type.weeks().isSupported();
case 4:
return type.days().isSupported();
case 5:
return type.hours().isSupported();
case 6:
return type.minutes().isSupported();
case 7:
return type.seconds().isSupported();
case 8:
return type.millis().isSupported();
}
}
void setFieldValue(ReadWritablePeriod period, int value) {
switch (iFieldType) {
default:
break;
case 1:
period.setYears(value);
break;
case 2:
period.setMonths(value);
break;
case 3:
period.setWeeks(value);
break;
case 4:
period.setDays(value);
break;
case 5:
period.setHours(value);
break;
case 6:
period.setMinutes(value);
break;
case 7:
period.setSeconds(value);
break;
case 8:
period.setMillis(value);
break;
}
}
int getPrintZeroSetting() {
return iPrintZeroSetting;
}
}
/**
* Handles a simple literal piece of text.
*/
private static final class Literal extends AbstractPeriodFormatter
implements PeriodFormatter
{
static final Literal EMPTY = new Literal("");
private final String iText;
Literal(String text) {
iText = text;
}
public int countFieldsToPrint(ReadablePeriod period, int stopAt) {
return 0;
}
public int calculatePrintedLength(ReadablePeriod period) {
return iText.length();
}
public void printTo(StringBuffer buf, ReadablePeriod period) {
buf.append(iText);
}
public void printTo(Writer out, ReadablePeriod period) throws IOException {
out.write(iText);
}
public int parseInto(ReadWritablePeriod period,
String periodStr, int position) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
}
/**
* Handles a separator, that splits the fields into multiple parts.
* For example, the 'T' in the ISO8601 standard.
*/
private static final class Separator extends AbstractPeriodFormatter
implements PeriodFormatter
{
private final String iText;
private final String iFinalText;
private final boolean iUseBefore;
private final boolean iUseAfter;
private PeriodFormatter iBefore;
private PeriodFormatter iAfter;
Separator(String text, String finalText, PeriodFormatter before, boolean useBefore, boolean useAfter) {
iText = text;
iFinalText = finalText;
iBefore = before;
iUseBefore = useBefore;
iUseAfter = useAfter;
}
public int countFieldsToPrint(ReadablePeriod period, int stopAt) {
int sum = iBefore.countFieldsToPrint(period, stopAt);
if (sum < stopAt) {
sum += iAfter.countFieldsToPrint(period, stopAt);
}
return sum;
}
public int calculatePrintedLength(ReadablePeriod period) {
PeriodPrinter before = iBefore;
PeriodPrinter after = iAfter;
int sum = before.calculatePrintedLength(period)
+ after.calculatePrintedLength(period);
if (iUseBefore) {
if (before.countFieldsToPrint(period, 1) > 0) {
if (iUseAfter) {
int afterCount = after.countFieldsToPrint(period, 2);
if (afterCount > 0) {
sum += (afterCount > 1 ? iText : iFinalText).length();
}
} else {
sum += iText.length();
}
}
} else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) {
sum += iText.length();
}
return sum;
}
public void printTo(StringBuffer buf, ReadablePeriod period) {
PeriodPrinter before = iBefore;
PeriodPrinter after = iAfter;
before.printTo(buf, period);
if (iUseBefore) {
if (before.countFieldsToPrint(period, 1) > 0) {
if (iUseAfter) {
int afterCount = after.countFieldsToPrint(period, 2);
if (afterCount > 0) {
buf.append(afterCount > 1 ? iText : iFinalText);
}
} else {
buf.append(iText);
}
}
} else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) {
buf.append(iText);
}
after.printTo(buf, period);
}
public void printTo(Writer out, ReadablePeriod period) throws IOException {
PeriodPrinter before = iBefore;
PeriodPrinter after = iAfter;
before.printTo(out, period);
if (iUseBefore) {
if (before.countFieldsToPrint(period, 1) > 0) {
if (iUseAfter) {
int afterCount = after.countFieldsToPrint(period, 2);
if (afterCount > 0) {
out.write(afterCount > 1 ? iText : iFinalText);
}
} else {
out.write(iText);
}
}
} else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) {
out.write(iText);
}
after.printTo(out, period);
}
public int parseInto(ReadWritablePeriod period,
String periodStr, int position) {
final int oldPos = position;
position = iBefore.parseInto(period, periodStr, position);
if (position < 0) {
return position;
}
if (position > oldPos) {
// Since position advanced, this separator is
// allowed. Optionally parse it.
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
position += iText.length();
} else if (iText != iFinalText && periodStr.regionMatches
(true, position, iFinalText, 0, iFinalText.length())) {
position += iFinalText.length();
}
}
position = iAfter.parseInto(period, periodStr, position);
return position;
}
Separator finish(PeriodFormatter after) {
iAfter = after;
return this;
}
}
/**
* Composite implementation that merges other fields to create a full pattern.
*/
private static final class Composite extends AbstractPeriodFormatter
implements PeriodFormatter
{
private final PeriodFormatter[] iFormatters;
Composite(List formatters) {
iFormatters = (PeriodFormatter[])formatters.toArray
(new PeriodFormatter[formatters.size()]);
}
public int countFieldsToPrint(ReadablePeriod period, int stopAt) {
int sum = 0;
PeriodPrinter[] printers = iFormatters;
for (int i=printers.length; sum < stopAt && --i>=0; ) {
sum += printers[i].countFieldsToPrint(period);
}
return sum;
}
public int calculatePrintedLength(ReadablePeriod period) {
int sum = 0;
PeriodPrinter[] printers = iFormatters;
for (int i=printers.length; --i>=0; ) {
sum += printers[i].calculatePrintedLength(period);
}
return sum;
}
public void printTo(StringBuffer buf, ReadablePeriod period) {
PeriodPrinter[] printers = iFormatters;
int len = printers.length;
for (int i=0; i<len; i++) {
printers[i].printTo(buf, period);
}
}
public void printTo(Writer out, ReadablePeriod period) throws IOException {
PeriodPrinter[] printers = iFormatters;
int len = printers.length;
for (int i=0; i<len; i++) {
printers[i].printTo(out, period);
}
}
public int parseInto(ReadWritablePeriod period,
String periodStr, int position) {
PeriodParser[] parsers = iFormatters;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position);
}
return position;
}
}
/**
* Selects between a number of choices based on which matches best.
*/
private static final class AlternateSelector extends AbstractPeriodFormatter
implements PeriodFormatter
{
private final PeriodFormatter iPrimaryFormatter;
private final PeriodPrinter[] iAlternatePrinters;
private final boolean iFavorFirstFieldForZero;
AlternateSelector(PeriodFormatter primaryFormatter,
List alternatePrinters,
boolean favorFirstFieldForZero) {
iPrimaryFormatter = primaryFormatter;
iAlternatePrinters = (PeriodPrinter[])alternatePrinters.toArray
(new PeriodPrinter[alternatePrinters.size()]);
iFavorFirstFieldForZero = favorFirstFieldForZero;
}
public int countFieldsToPrint(ReadablePeriod period, int stopAt) {
int count = iPrimaryFormatter.countFieldsToPrint(period, stopAt);
if (count < 1 && stopAt >= 1) {
if (chooseFieldToPrint(period) != null) {
return 1;
}
}
return count;
}
public int calculatePrintedLength(ReadablePeriod period) {
if (iPrimaryFormatter.countFieldsToPrint(period, 1) > 0) {
return iPrimaryFormatter.calculatePrintedLength(period);
}
Object chosenOne = chooseFieldToPrint(period);
int sum = 0;
PeriodPrinter[] printers = iAlternatePrinters;
for (int i=printers.length; --i>=0; ) {
PeriodPrinter dp = printers[i];
if (dp == chosenOne || !(dp instanceof FieldFormatter)) {
sum += dp.calculatePrintedLength(period);
}
}
return sum;
}
public void printTo(StringBuffer buf, ReadablePeriod period) {
if (iPrimaryFormatter.countFieldsToPrint(period, 1) > 0) {
iPrimaryFormatter.printTo(buf, period);
return;
}
Object chosenOne = chooseFieldToPrint(period);
PeriodPrinter[] printers = iAlternatePrinters;
int len = printers.length;
for (int i=0; i<len; i++) {
PeriodPrinter dp = printers[i];
if (dp == chosenOne || !(dp instanceof FieldFormatter)) {
dp.printTo(buf, period);
}
}
}
public void printTo(Writer out, ReadablePeriod period) throws IOException {
if (iPrimaryFormatter.countFieldsToPrint(period, 1) > 0) {
iPrimaryFormatter.printTo(out, period);
return;
}
Object chosenOne = chooseFieldToPrint(period);
PeriodPrinter[] printers = iAlternatePrinters;
int len = printers.length;
for (int i=0; i<len; i++) {
PeriodPrinter dp = printers[i];
if (dp == chosenOne || !(dp instanceof FieldFormatter)) {
dp.printTo(out, period);
}
}
}
public int parseInto(ReadWritablePeriod period,
String periodStr, int position) {
return iPrimaryFormatter.parseInto(period, periodStr, position);
}
private FieldFormatter chooseFieldToPrint(ReadablePeriod period) {
PeriodType type = period.getPeriodType();
PeriodPrinter[] printers = iAlternatePrinters;
if (iFavorFirstFieldForZero) {
int len = printers.length;
for (int i=0; i<len; i++) {
PeriodPrinter dp = printers[i];
if (dp instanceof FieldFormatter) {
FieldFormatter ff = (FieldFormatter) dp;
if (ff.isSupported(type)) {
if (ff.getPrintZeroSetting() == PRINT_ZERO_RARELY) {
ff = new FieldFormatter(ff, PRINT_ZERO_IF_SUPPORTED);
printers[i] = ff;
}
return ff;
}
}
}
} else {
for (int i=printers.length; --i>=0; ) {
PeriodPrinter dp = printers[i];
if (dp instanceof FieldFormatter) {
FieldFormatter ff = (FieldFormatter) dp;
if (ff.isSupported(type)) {
if (ff.getPrintZeroSetting() == PRINT_ZERO_RARELY) {
ff = new FieldFormatter(ff, PRINT_ZERO_IF_SUPPORTED);
printers[i] = ff;
}
return ff;
}
}
}
}
return null;
}
}
}
|
package com.intellij.ide.projectView.impl.nodes;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.ProjectJdk;
import com.intellij.openapi.roots.JdkOrderEntry;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.LibraryOrderEntry;
import com.intellij.openapi.roots.ui.util.CellAppearanceUtils;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class NamedLibraryElementNode extends ProjectViewNode<NamedLibraryElement>{
private static final Icon LIB_ICON_OPEN = IconLoader.getIcon("/nodes/ppLibOpen.png");
private static final Icon LIB_ICON_CLOSED = IconLoader.getIcon("/nodes/ppLibClosed.png");
public NamedLibraryElementNode(Project project, NamedLibraryElement value, ViewSettings viewSettings) {
super(project, value, viewSettings);
}
public NamedLibraryElementNode(final Project project, final Object value, final ViewSettings viewSettings) {
this(project, (NamedLibraryElement)value, viewSettings);
}
public Collection<AbstractTreeNode> getChildren() {
final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
LibraryGroupNode.addLibraryChildren(getValue().getOrderEntry(), children, getProject(), this);
return children;
}
public String getTestPresentation() {
return "Library: " + getValue().getName();
}
private static Icon getJdkIcon(JdkOrderEntry entry, boolean isExpanded) {
final ProjectJdk jdk = entry.getJdk();
if (jdk == null) {
return CellAppearanceUtils.GENERIC_JDK_ICON;
}
return isExpanded? jdk.getSdkType().getIconForExpandedTreeNode() : jdk.getSdkType().getIcon();
}
public String getName() {
return getValue().getName();
}
public boolean contains(VirtualFile file) {
return orderEntryContainsFile(getValue().getOrderEntry(), file);
}
public static boolean orderEntryContainsFile(OrderEntry orderEntry, VirtualFile file) {
VirtualFile[] files = orderEntry.getFiles(OrderRootType.CLASSES);
for (VirtualFile virtualFile : files) {
boolean ancestor = VfsUtil.isAncestor(virtualFile, file, false);
if (ancestor) return true;
}
return false;
}
public void update(PresentationData presentation) {
presentation.setPresentableText(getValue().getName());
final OrderEntry orderEntry = getValue().getOrderEntry();
presentation.setOpenIcon(orderEntry instanceof JdkOrderEntry ? getJdkIcon((JdkOrderEntry)orderEntry, true) : LIB_ICON_OPEN);
presentation.setClosedIcon(orderEntry instanceof JdkOrderEntry ? getJdkIcon((JdkOrderEntry)orderEntry, false) : LIB_ICON_CLOSED);
if (orderEntry instanceof JdkOrderEntry) {
final JdkOrderEntry jdkOrderEntry = (JdkOrderEntry)orderEntry;
presentation.setLocationString(FileUtil.toSystemDependentName(jdkOrderEntry.getJdk().getHomePath()));
}
}
protected String getToolTip() {
OrderEntry orderEntry = getValue().getOrderEntry();
return orderEntry instanceof JdkOrderEntry ? "JDK" : StringUtil.capitalize(((LibraryOrderEntry)orderEntry).getLibraryLevel() + " library");
}
}
|
package org.tuckey.web.filters.urlrewrite;
import org.tuckey.web.filters.urlrewrite.utils.Log;
import org.tuckey.web.filters.urlrewrite.utils.NumberUtils;
import org.tuckey.web.filters.urlrewrite.utils.RegexPattern;
import org.tuckey.web.filters.urlrewrite.utils.StringMatchingMatcher;
import org.tuckey.web.filters.urlrewrite.utils.StringMatchingPattern;
import org.tuckey.web.filters.urlrewrite.utils.StringMatchingPatternSyntaxException;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;
import org.tuckey.web.filters.urlrewrite.utils.WildcardPattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
public final class Condition extends TypeConverter {
private static Log log = Log.getLog(Condition.class);
/**
* Should this expression be matched case sensitively.
*/
private boolean caseSensitive = false;
/**
* Used to identify the condition.
*/
private int id = 0;
/**
* Used to cache the pattern for faster execution.
*/
private StringMatchingPattern pattern;
/**
* The name of the header etc.
*/
private String name;
/**
* The operator that should be used to evaluate the condition.
*/
private short operator;
/**
* Value of this condition if the type is header.
*/
private String strValue;
/**
* Value of this condition if the type is port.
*/
private long numericValue = 0;
/**
* What to do with the next rule, this will indicate "or" otherwise do "and".
*/
private boolean processNextOr = false;
private boolean valid = false;
private boolean initialised = false;
// Operators
private static final short OPERATOR_EQUAL = 1;
private static final short OPERATOR_NOT_EQUAL = 2;
private static final short OPERATOR_GREATER_THAN = 3;
private static final short OPERATOR_LESS_THAN = 4;
private static final short OPERATOR_GREATER_THAN_OR_EQUAL = 5;
private static final short OPERATOR_LESS_THAN_OR_EQUAL = 6;
private static final short OPERATOR_INSTANCEOF = 7;
// if we are doing an instanceof test the class we want to test against
Class instanceOfClass = null;
// the rule that "owns" this condition.
private RuleBase rule;
/**
* Will check and see if the condition matches the request.
*
* @param hsRequest
* @return true on match
* @deprecated use getConditionMatch(HttpServletRequest hsRequest)
*/
public boolean matches(final HttpServletRequest hsRequest) {
return getConditionMatch(hsRequest) != null;
}
/**
* Will check and see if the condition matches the request.
*
* @param hsRequest
* @return true on match
*/
public ConditionMatch getConditionMatch(final HttpServletRequest hsRequest) {
if (!initialised) {
log.debug("condition not initialised skipping");
// error initialising do not process
return null;
}
if (!valid) {
log.debug("condition not valid skipping");
return null;
}
switch (type) {
case TYPE_TIME:
return evaluateNumericCondition(System.currentTimeMillis());
case TYPE_TIME_YEAR:
return evaluateCalendarCondition(Calendar.YEAR);
case TYPE_TIME_MONTH:
return evaluateCalendarCondition(Calendar.MONTH);
case TYPE_TIME_DAY_OF_MONTH:
return evaluateCalendarCondition(Calendar.DAY_OF_MONTH);
case TYPE_TIME_DAY_OF_WEEK:
return evaluateCalendarCondition(Calendar.DAY_OF_WEEK);
case TYPE_TIME_AMPM:
return evaluateCalendarCondition(Calendar.AM_PM);
case TYPE_TIME_HOUR_OF_DAY:
return evaluateCalendarCondition(Calendar.HOUR_OF_DAY);
case TYPE_TIME_MINUTE:
return evaluateCalendarCondition(Calendar.MINUTE);
case TYPE_TIME_SECOND:
return evaluateCalendarCondition(Calendar.SECOND);
case TYPE_TIME_MILLISECOND:
return evaluateCalendarCondition(Calendar.MILLISECOND);
case TYPE_ATTRIBUTE:
return evaluateAttributeCondition(name == null ? null : hsRequest.getAttribute(name));
case TYPE_AUTH_TYPE:
return evaluateStringCondition(hsRequest.getAuthType());
case TYPE_CHARACTER_ENCODING:
return evaluateStringCondition(hsRequest.getCharacterEncoding());
case TYPE_CONTENT_LENGTH:
return evaluateNumericCondition(hsRequest.getContentLength());
case TYPE_CONTENT_TYPE:
return evaluateStringCondition(hsRequest.getContentType());
case TYPE_CONTEXT_PATH:
return evaluateStringCondition(hsRequest.getContextPath());
case TYPE_COOKIE:
return evaluateCookieCondition(hsRequest.getCookies(), name);
case TYPE_LOCAL_PORT:
return evaluateNumericCondition(hsRequest.getLocalPort());
case TYPE_METHOD:
return evaluateStringCondition(hsRequest.getMethod());
case TYPE_PARAMETER:
return evaluateStringCondition(name == null ? null : hsRequest.getParameter(name));
case TYPE_PATH_INFO:
return evaluateStringCondition(hsRequest.getPathInfo());
case TYPE_PATH_TRANSLATED:
return evaluateStringCondition(hsRequest.getPathTranslated());
case TYPE_PROTOCOL:
return evaluateStringCondition(hsRequest.getProtocol());
case TYPE_QUERY_STRING:
return evaluateStringCondition(hsRequest.getQueryString());
case TYPE_REMOTE_ADDR:
return evaluateStringCondition(hsRequest.getRemoteAddr());
case TYPE_REMOTE_HOST:
return evaluateStringCondition(hsRequest.getRemoteHost());
case TYPE_REMOTE_USER:
return evaluateStringCondition(hsRequest.getRemoteUser());
case TYPE_REQUESTED_SESSION_ID:
return evaluateStringCondition(hsRequest.getRequestedSessionId());
case TYPE_REQUEST_URI:
return evaluateStringCondition(hsRequest.getRequestURI());
case TYPE_REQUEST_URL:
StringBuffer requestUrlBuff = hsRequest.getRequestURL();
String requestUrlStr = null;
if (requestUrlBuff != null) {
requestUrlStr = requestUrlBuff.toString();
}
return evaluateStringCondition(requestUrlStr);
case TYPE_SESSION_ATTRIBUTE:
Object sessionAttributeValue = null;
if (hsRequest.getSession() != null && name != null) {
sessionAttributeValue = hsRequest.getSession().getAttribute(name);
}
return evaluateAttributeCondition(sessionAttributeValue);
case TYPE_SESSION_IS_NEW:
boolean sessionNew = false;
HttpSession session = hsRequest.getSession();
if (session != null) {
sessionNew = session.isNew();
}
return evaluateBoolCondition(sessionNew);
case TYPE_SERVER_PORT:
return evaluateNumericCondition(hsRequest.getServerPort());
case TYPE_SERVER_NAME:
return evaluateStringCondition(hsRequest.getServerName());
case TYPE_SCHEME:
return evaluateStringCondition(hsRequest.getScheme());
case TYPE_USER_IN_ROLE:
log.debug("is user in role " + name + " op " + operator);
return evaluateBoolCondition(hsRequest.isUserInRole(name));
case TYPE_EXCEPTION:
String eName = null;
Exception e = (Exception) hsRequest.getAttribute("javax.servlet.error.exception");
if (OPERATOR_INSTANCEOF == operator) {
return evaluateInstanceOfCondition(e);
} else {
if (e != null && e.getClass() != null) eName = e.getClass().getName();
return evaluateStringCondition(eName);
}
default:
return evaluateHeaderCondition(hsRequest);
}
}
private ConditionMatch evaluateAttributeCondition(Object attribObject) {
String attribValue = null;
if (attribObject == null) {
if (log.isDebugEnabled()) {
log.debug(name + " doesn't exist");
}
} else {
attribValue = attribObject.toString();
}
if (OPERATOR_INSTANCEOF == operator) {
return evaluateInstanceOfCondition(attribObject);
} else {
return evaluateStringCondition(attribValue);
}
}
private ConditionMatch evaluateInstanceOfCondition(Object obj) {
// only test for instanceof if object is not null
if (obj == null) return null;
if (log.isDebugEnabled()) {
log.debug("is " + obj.getClass() + " an instanceof " + instanceOfClass);
}
if (instanceOfClass == null) {
log.error("this condition may have failed to initialise correctly, instanceof class is null");
return null;
}
if (instanceOfClass.isInstance(obj)) {
log.debug("yes");
return new ConditionMatch();
}
log.debug("no");
return null;
}
private ConditionMatch evaluateCookieCondition(Cookie[] cookies, String name) {
if (cookies == null) {
// we will have to do an exists check
return evaluateBoolCondition(false);
}
if (name == null) {
return evaluateBoolCondition(false);
}
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie == null) {
continue;
}
if (name.equals(cookie.getName())) {
return evaluateStringCondition(cookie.getValue());
}
}
return evaluateBoolCondition(false);
}
private ConditionMatch evaluateStringCondition(String value) {
if (pattern == null && value == null) {
log.debug("value is empty and pattern is also, condition false");
return evaluateBoolCondition(false);
} else if (pattern == null) {
log.debug("value isn't empty but pattern is, assuming checking for existence, condition true");
return evaluateBoolCondition(true);
}
if (value == null) {
// value is null make value ""
value = "";
}
if (log.isDebugEnabled()) {
log.debug("evaluating \"" + value + "\" against " + strValue);
}
StringMatchingMatcher matcher = pattern.matcher(value);
return evaluateBoolCondition(matcher, matcher.find());
}
/**
* Evaluate taking into account the operator, not only boolean operators considered.
*/
private ConditionMatch evaluateBoolCondition(boolean outcome) {
if (log.isTraceEnabled()) {
log.trace("outcome " + outcome);
}
if (operator == OPERATOR_NOT_EQUAL) {
log.debug("not equal operator in use");
return !outcome ? new ConditionMatch() : null;
}
return outcome ? new ConditionMatch() : null;
}
private ConditionMatch evaluateBoolCondition(StringMatchingMatcher matcher, boolean outcome) {
ConditionMatch conditionMatch = evaluateBoolCondition(outcome);
if (conditionMatch != null) {
conditionMatch.setMatcher(matcher);
}
return conditionMatch;
}
private ConditionMatch evaluateHeaderCondition(final HttpServletRequest hsRequest) {
String headerValue = null;
if (name != null) {
headerValue = hsRequest.getHeader(name);
}
return evaluateStringCondition(headerValue);
}
/**
* Will evaluate a calendar condition.
*
* @param calField the calendar field from Calendar
*/
private ConditionMatch evaluateCalendarCondition(final int calField) {
return evaluateNumericCondition((Calendar.getInstance()).get(calField));
}
/**
* Will evaluate usign operator.
*
* @param compareWith what to compare with
* @return true or false
*/
private ConditionMatch evaluateNumericCondition(final long compareWith) {
if (log.isDebugEnabled()) {
log.debug("evaluating with operator, is " + compareWith + " " + getOperator() + " " + numericValue);
}
switch (operator) {
case OPERATOR_NOT_EQUAL:
return compareWith != numericValue ? new ConditionMatch() : null;
case OPERATOR_GREATER_THAN:
return compareWith > numericValue ? new ConditionMatch() : null;
case OPERATOR_LESS_THAN:
return compareWith < numericValue ? new ConditionMatch() : null;
case OPERATOR_GREATER_THAN_OR_EQUAL:
return compareWith >= numericValue ? new ConditionMatch() : null;
case OPERATOR_LESS_THAN_OR_EQUAL:
return compareWith <= numericValue ? new ConditionMatch() : null;
default:
return compareWith == numericValue ? new ConditionMatch() : null;
}
}
/**
* Returns false on failure. Use getError to get the description of the error.
*
* @return weather or not the condition was successful in initialisation.
*/
public boolean initialise() {
initialised = true;
if (error != null) {
return false;
}
// make sure we default to header if not set
if (type == 0) {
type = TYPE_HEADER;
}
switch (type) {
// note, only numeric specified others handled by default:
case TYPE_SERVER_PORT:
initNumericValue();
break;
case TYPE_TIME:
initNumericValue();
break;
case TYPE_TIME_YEAR:
initNumericValue();
break;
case TYPE_TIME_MONTH:
initNumericValue();
break;
case TYPE_TIME_DAY_OF_MONTH:
initNumericValue();
break;
case TYPE_TIME_DAY_OF_WEEK:
initNumericValue();
break;
case TYPE_TIME_AMPM:
initNumericValue();
break;
case TYPE_TIME_HOUR_OF_DAY:
initNumericValue();
break;
case TYPE_TIME_MINUTE:
initNumericValue();
break;
case TYPE_TIME_SECOND:
initNumericValue();
break;
case TYPE_TIME_MILLISECOND:
initNumericValue();
break;
case TYPE_CONTENT_LENGTH:
initNumericValue();
break;
case TYPE_LOCAL_PORT:
initNumericValue();
break;
case TYPE_USER_IN_ROLE:
// we only care to make sure the user has entered a name (if no name use value)
// note regexs cannot be entered against this due to limitations in servlet spec
if (StringUtils.isBlank(name)) {
name = strValue;
}
break;
case TYPE_SESSION_ATTRIBUTE:
if (StringUtils.isBlank(name)) {
setError("you must set a name for session attributes");
}
initStringValue();
break;
case TYPE_ATTRIBUTE:
if (StringUtils.isBlank(name)) {
setError("you must set a name for attributes");
}
initStringValue();
break;
case TYPE_HEADER:
if (StringUtils.isBlank(name)) {
setError("you must set a name for a header");
}
initStringValue();
break;
default:
// other generic types
initStringValue();
}
if (log.isDebugEnabled()) {
log.debug("loaded condition " + getType() + " " + name + " " + strValue);
}
valid = error == null;
return valid;
}
private void initStringValue() {
if (StringUtils.isBlank(strValue)) {
log.debug("value is blank initing pattern to null");
pattern = null;
return;
}
if (OPERATOR_INSTANCEOF == operator) {
// want to be able to do instance of that means value is not a regexp
log.debug("initialising instanceof condition");
strValue = StringUtils.trim(strValue);
try {
instanceOfClass = Class.forName(strValue);
if (instanceOfClass == null) {
setError("had trouble finding " + strValue + " after Class.forName got a null object");
}
} catch (ClassNotFoundException e) {
setError("could not find " + strValue + " got a " + e.toString());
} catch (NoClassDefFoundError e) {
setError("could not find " + strValue + " got a " + e.toString());
}
} else {
try {
if (rule != null && rule.isMatchTypeWildcard()) {
log.debug("rule match type is wildcard");
pattern = new WildcardPattern(strValue);
} else {
// default is regex
pattern = new RegexPattern(strValue, caseSensitive);
}
} catch (StringMatchingPatternSyntaxException e) {
setError("Problem compiling regular expression " + strValue + " (" + e.getMessage() + ")");
}
}
}
/**
* Will init a numeric value type ie port.
*/
private void initNumericValue() {
if (numericValue == 0) {
numericValue = NumberUtils.stringToLong(StringUtils.trim(strValue));
if (numericValue == 0 && !"0".equals(strValue)) {
setError("Value " + strValue + " is not a valid number (tried to cast to java type long)");
}
}
}
protected void setError(String s) {
super.setError(s);
log.error("Condition " + id + " had error: " + s);
}
/**
* Will get the operator type.
*
* @return notequal, greater etc.
*/
public String getOperator() {
switch (operator) {
case OPERATOR_NOT_EQUAL:
return "notequal";
case OPERATOR_GREATER_THAN:
return "greater";
case OPERATOR_LESS_THAN:
return "less";
case OPERATOR_GREATER_THAN_OR_EQUAL:
return "greaterorequal";
case OPERATOR_LESS_THAN_OR_EQUAL:
return "lessorequal";
case OPERATOR_INSTANCEOF:
return "instanceof";
case OPERATOR_EQUAL:
return "equal";
default:
return "";
}
}
/**
* Will ste the operator.
*
* @param operator type
*/
public void setOperator(final String operator) {
if ("notequal".equals(operator)) {
this.operator = OPERATOR_NOT_EQUAL;
} else if ("greater".equals(operator)) {
this.operator = OPERATOR_GREATER_THAN;
} else if ("less".equals(operator)) {
this.operator = OPERATOR_LESS_THAN;
} else if ("greaterorequal".equals(operator)) {
this.operator = OPERATOR_GREATER_THAN_OR_EQUAL;
} else if ("lessorequal".equals(operator)) {
this.operator = OPERATOR_LESS_THAN_OR_EQUAL;
} else if ("instanceof".equals(operator)) {
this.operator = OPERATOR_INSTANCEOF;
} else if ("equal".equals(operator) || StringUtils.isBlank(operator)) {
this.operator = OPERATOR_EQUAL;
} else {
setError("Operator " + operator + " is not valid");
}
}
/**
* Will get the name.
*
* @return String
*/
public String getName() {
return name;
}
/**
* Will set the name.
*
* @param name the name
*/
public void setName(final String name) {
this.name = name;
}
/**
* Will return "add" or "or".
*
* @return "add" or "or"
*/
public String getNext() {
if (processNextOr) return "or";
return "and";
}
/**
* Will set next.
*
* @param next "or" or "and"
*/
public void setNext(final String next) {
if ("or".equals(next)) {
this.processNextOr = true;
} else if ("and".equals(next) || StringUtils.isBlank(next)) {
this.processNextOr = false;
} else {
setError("Next " + next + " is not valid (can be 'and', 'or')");
}
}
/**
* Will get the value.
*
* @return String
*/
public String getValue() {
return strValue;
}
/**
* Will set the value.
*
* @param value the value
*/
public void setValue(final String value) {
this.strValue = value;
}
/**
* True if process next is or.
*
* @return boolean
*/
public boolean isProcessNextOr() {
return processNextOr;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
public String getDisplayName() {
return "Condtition " + id;
}
public void setRule(RuleBase rule) {
this.rule = rule;
}
}
|
package org.demyo.service.impl;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.transaction.Transactional;
import org.demyo.common.config.SystemConfiguration;
import org.demyo.common.exception.DemyoErrorCode;
import org.demyo.common.exception.DemyoException;
import org.demyo.common.exception.DemyoRuntimeException;
import org.demyo.dao.IImageRepo;
import org.demyo.dao.IModelRepo;
import org.demyo.model.Image;
import org.demyo.model.config.ApplicationConfiguration;
import org.demyo.service.IConfigurationService;
import org.demyo.service.IImageService;
import org.demyo.utils.io.DIOUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Implements the contract defined by {@link IImageService}.
*/
// TODO: delete the file as well on image deletion
@Service
public class ImageService extends AbstractModelService<Image> implements IImageService {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageService.class);
private static final String UPLOAD_DIRECTORY_NAME = "uploads";
@Autowired
private IImageRepo repo;
@Autowired
private IConfigurationService configService;
private File uploadDirectory;
/**
* Default constructor.
*/
public ImageService() {
super(Image.class);
uploadDirectory = new File(SystemConfiguration.getInstance().getImagesDirectory(), UPLOAD_DIRECTORY_NAME);
uploadDirectory.mkdirs();
}
@Override
protected IModelRepo<Image> getRepo() {
return repo;
}
@Override
@Deprecated
public File getImageFile(String path) throws DemyoException {
File image = new File(SystemConfiguration.getInstance().getImagesDirectory(), path);
validateImagePath(image);
if (!image.isFile()) {
throw new DemyoException(DemyoErrorCode.IMAGE_NOT_FOUND, path);
}
return image;
}
@Override
public File getImageFile(Image imageModel) throws DemyoException {
String path = imageModel.getUrl();
File image = new File(SystemConfiguration.getInstance().getImagesDirectory(), path);
validateImagePath(image);
if (!image.isFile()) {
throw new DemyoException(DemyoErrorCode.IMAGE_NOT_FOUND, path);
}
return image;
}
@Override
public File getImageThumbnail(long id) throws DemyoException {
// Check cache (two possible formats)
File pngThumb = new File(SystemConfiguration.getInstance().getThumbnailDirectory(), id + ".png");
File jpgThumb = new File(SystemConfiguration.getInstance().getThumbnailDirectory(), id + ".jpg");
if (pngThumb.exists()) {
return pngThumb;
}
if (jpgThumb.exists()) {
return jpgThumb;
}
// No cache hit, generate thumbnail
File image = getImageFile(getByIdForEdition(id));
long time = System.currentTimeMillis();
BufferedImage buffImage;
try {
buffImage = ImageIO.read(image);
} catch (IOException e) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_IO_ERROR, e);
}
// If the image has one dimension too small, constrain it to that
ApplicationConfiguration config = configService.getConfiguration();
int desiredMaxWidth = config.getThumbnailWidth() > buffImage.getWidth() ? buffImage.getWidth() : config
.getThumbnailWidth();
int desiredMaxHeight = config.getThumbnailHeight() > buffImage.getHeight() ? buffImage.getHeight()
: config.getThumbnailHeight();
// Resize
BufferedImage buffThumb = Scalr.resize(buffImage, Method.BALANCED, Mode.AUTOMATIC, desiredMaxWidth,
desiredMaxHeight, Scalr.OP_ANTIALIAS);
LOGGER.debug("Thumbnail generated in {}ms", System.currentTimeMillis() - time);
try {
// Write opaque images as JPG, transparent images as PNG
if (Transparency.OPAQUE == buffThumb.getTransparency()) {
ImageIO.write(buffThumb, "jpg", jpgThumb);
return jpgThumb;
} else {
ImageIO.write(buffThumb, "png", pngThumb);
return pngThumb;
}
} catch (IOException e) {
// Ensure we don't store invalid contents
jpgThumb.delete();
pngThumb.delete();
throw new DemyoRuntimeException(DemyoErrorCode.IMAGE_IO_ERROR, e);
} finally {
buffImage.flush();
buffThumb.flush();
}
}
private void validateImagePath(File image) throws DemyoException {
try {
String imagesDirectoryPath = SystemConfiguration.getInstance().getImagesDirectory().getCanonicalPath();
String imagePath = image.getCanonicalPath();
if (!imagePath.startsWith(imagesDirectoryPath)) {
throw new DemyoException(DemyoErrorCode.IMAGE_DIRECTORY_TRAVERSAL, imagePath);
}
} catch (IOException e) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_IO_ERROR, e);
}
}
@Override
@Transactional
public long uploadImage(String originalFileName, File imageFile) {
// Determine the hash of the uploaded file
String hash;
try (FileInputStream data = new FileInputStream(imageFile)) {
hash = DigestUtils.sha256Hex(data);
} catch (IOException e) {
throw new DemyoRuntimeException(DemyoErrorCode.IMAGE_UPLOAD_ERROR, e);
}
// Determine the target file name
String extension = DIOUtils.getFileExtension(originalFileName);
if (extension == null) {
extension = "jpg";
}
File targetFile = new File(uploadDirectory, hash + "." + extension);
// Check if the file exists already
if (targetFile.exists()) {
LOGGER.debug("Uploaded file {} already exists as {}", originalFileName, targetFile);
// Reuse the same image
Image foundImage = repo.findByUrl(UPLOAD_DIRECTORY_NAME + "/" + targetFile.getName());
if (foundImage != null) {
LOGGER.debug("Already existing image found with ID {}", foundImage.getId());
return foundImage.getId();
}
LOGGER.debug("Already existing image was not found in the database. Uploading it as a new one...");
targetFile.delete();
}
// Either the file does not exist, or it was removed in the previous step
// Move the image to its final destination
imageFile.renameTo(targetFile);
// Create a new image with the right attributes
Image image = new Image();
image.setUrl(UPLOAD_DIRECTORY_NAME + "/" + targetFile.getName());
image.setDescription(inferDescription(originalFileName));
return save(image);
}
@Override
public long addExistingImage(String path) {
File imagesDirectory = SystemConfiguration.getInstance().getImagesDirectory();
File targetFile = new File(imagesDirectory, path);
if (!targetFile.toPath().startsWith(imagesDirectory.toPath())) {
throw new DemyoRuntimeException(DemyoErrorCode.IMAGE_DIRECTORY_TRAVERSAL, path
+ " is not a valid path");
}
// Create a new image with the right attributes
Image image = new Image();
image.setUrl(path);
image.setDescription(inferDescription(targetFile.getName()));
return save(image);
}
private static String inferDescription(String originalFileName) {
// Strip any path attributes
String description = new File(originalFileName).getName();
// Strip the extension
description = description.replaceAll("\\.[^.]+$", "");
// Convert underscores into spaces
description = description.replace('_', ' ');
LOGGER.debug("Uploaded file {} led to description: {}", originalFileName, description);
return description;
}
@Override
public List<String> findUnknownDiskImages() {
List<String> unknownFiles = new ArrayList<>();
File imagesDirectory = SystemConfiguration.getInstance().getImagesDirectory();
// Find the files
Collection<File> foundFiles = FileUtils.listFiles(imagesDirectory,
new SuffixFileFilter(Arrays.asList(".jpg", ".jpeg", ".png", ".gif"), IOCase.INSENSITIVE),
TrueFileFilter.INSTANCE);
// Find the paths known in the database
Set<String> knownFiles = repo.findAllPaths();
// Filter out the known files
Path imagesDirectoryPath = imagesDirectory.toPath();
for (File file : foundFiles) {
String relativePath = imagesDirectoryPath.relativize(file.toPath()).toString();
boolean known = knownFiles.contains(relativePath);
LOGGER.trace("Is {} known? {}", relativePath, known);
if (!known) {
unknownFiles.add(relativePath);
}
}
Collections.sort(unknownFiles);
return unknownFiles;
}
}
|
package com.trendrr.oss.taskprocessor;
import java.util.Comparator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.FileCache;
import com.trendrr.oss.PriorityUpdateQueue;
import com.trendrr.oss.concurrent.LazyInitObject;
import com.trendrr.oss.executionreport.ExecutionReport;
import com.trendrr.oss.taskprocessor.Task.ASYNCH;
/**
* @author Dustin Norlander
* @created Sep 24, 2012
*
*/
public class TaskProcessor {
protected static Log log = LogFactory.getLog(TaskProcessor.class);
static class TaskProcessorThreadFactory implements ThreadFactory {
static final AtomicInteger poolNumber = new AtomicInteger(1);
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
TaskProcessorThreadFactory(String name) {
SecurityManager s = System.getSecurityManager();
group = (s != null)? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "TP-" + name +"-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
static LazyInitObject<AsynchTaskRegistery> asynchTasks = new LazyInitObject<AsynchTaskRegistery>() {
@Override
public AsynchTaskRegistery init() {
AsynchTaskRegistery reg = new AsynchTaskRegistery();
reg.start();
return reg;
}
};
protected ExecutorService threadPool = null;
protected String name;
protected TaskCallback callback;
//example threadpool, blocks when queue is full.
// ExecutorService threadPool = new ThreadPoolExecutor(
// 1, // core size
// 30, // max size
// 130, // idle timeout
// TimeUnit.SECONDS,
// new ArrayBlockingQueue<Runnable>(30), // queue with a size
// new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread.
/**
* creates a new TaskProcessor with a new executorService
* ExecutorService threadPool = new ThreadPoolExecutor(
1, // core size
numThreads, // max size
130, // idle timeout
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size
new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread.
);
*
* @param name
* @param callback
* @param numThreads
*/
public static TaskProcessor defaultInstance(String name, TaskCallback callback, int numThreads) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
1, // core size
numThreads, // max size
130, // idle timeout
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size
new TaskProcessorThreadFactory(name),
new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread.
);
return new TaskProcessor(name, callback, threadPool);
}
/**
* creates a new task processor.
*
*
*
*
* @param name The name of this processor. used for execution reporting.
* @param callback Methods called for every task execution. this callback is called before the callback specified in the task. can be null.
* @param executor the executor
*/
public TaskProcessor(String name, TaskCallback callback, ExecutorService executor) {
this.threadPool = executor;
this.name = name;
this.callback = callback;
}
/**
* submits a task for execution.
* @param task
*/
public void submitTask(Task task) {
if (task.getSubmitted() == null) {
task.submitted();
}
task.setProcessor(this);
//add to the executor service..
TaskFilterRunner runner = new TaskFilterRunner(task);
this.threadPool.execute(runner);
}
public void setAsynch(Task t, ASYNCH asynch, long timeout) {
asynchTasks.get().add(t, asynch, timeout);
}
/**
* submit a future, a separate thread will poll it on interval and
* call your callback when isDone is set, or cancel once the timeout has.
*
* callback is executed in one of this processors executor threads.
* @param future
* @param callback
*/
public void submitFuture(Task task, Future future, FuturePollerCallback callback, long timeout) {
FuturePollerWrapper wrapper = new FuturePollerWrapper(future, callback, timeout, task);
asynchTasks.get().addFuture(wrapper);
}
public void resumeAsynch(String taskId) {
asynchTasks.get().resume(taskId);
}
public ExecutorService getExecutor() {
return this.threadPool;
}
/**
* A unique name for this processor. only one instance per name will be allowed.
* @return
*/
public String getName() {
return this.name;
}
public void taskComplete(Task task) {
if (this.callback != null) {
this.callback.taskComplete(task);
}
if (task.getCallback() != null) {
task.getCallback().taskComplete(task);
}
}
public void taskError(Task task, Exception error) {
if (this.callback != null) {
this.callback.taskError(task, error);
}
if (task.getCallback() != null) {
task.getCallback().taskError(task, error);
}
}
}
|
package com.gmail.justbru00.epic.randombuilders.listeners;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.justbru00.epic.randombuilders.chat.Messager;
import com.gmail.justbru00.epic.randombuilders.map.MapManager;
import com.gmail.justbru00.epic.randombuilders.utils.BuildingManager;
import com.gmail.justbru00.epic.randombuilders.utils.ItemBuilder;
public class BuildingListener implements Listener {
@EventHandler
public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) {
if (event.getEntityType() == EntityType.FALLING_BLOCK) {
BuildingManager.addBlock(event.getBlock().getLocation());
}
}
@EventHandler
public void onBlockDamage(BlockDamageEvent e) {
if (BuildingManager.canBreak()) {
if (BuildingManager.checkBlock(e.getBlock().getLocation())) {
ItemStack silk = new ItemBuilder(Material.DIAMOND_PICKAXE).setAmount(1).build();
silk.addEnchantment(Enchantment.SILK_TOUCH, 1);
e.getBlock().breakNaturally(silk);
e.setCancelled(true);
}
} else if (e.getPlayer().getGameMode().equals(GameMode.CREATIVE)){
} else {
e.setCancelled(true);
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {
if (BuildingManager.canBreak()) {
if (BuildingManager.checkBlock(e.getBlock().getLocation())) {
// Make sure this works with fancy breaking
} else {
if (e.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
// uhhh stuff?
} else {
e.setCancelled(true);
Messager.msgPlayer("&cThis block is protected.", e.getPlayer(), "game");
}
}
} else {
if (e.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
// uhhh stuff?
} else {
e.setCancelled(true);
}
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent e) {
if (BuildingManager.canPlace()) {
if (MapManager.getCurrentMap().isInsideArea(e.getBlock().getLocation())) {
BuildingManager.addBlock(e.getBlock().getLocation());
} else {
e.setCancelled(true);
Messager.msgPlayer("&cThat is outside your area", e.getPlayer(), "game");
return;
}
} else {
if (e.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
// uhhhh stuff?
} else {
e.setCancelled(true);
}
}
}
}
|
package com.virtualfactory.screen.layer.components;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.builder.PanelBuilder;
import de.lessvoid.nifty.controls.ButtonClickedEvent;
import de.lessvoid.nifty.controls.Controller;
import de.lessvoid.nifty.controls.Label;
import de.lessvoid.nifty.controls.label.builder.LabelBuilder;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.input.NiftyInputEvent;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.xml.xpp3.Attributes;
import de.lessvoid.nifty.controls.window.WindowControl;
import de.lessvoid.nifty.elements.render.ImageRenderer;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.tools.SizeValue;
import de.lessvoid.nifty.builder.ElementBuilder.Align;
import com.virtualfactory.engine.GameEngine;
import com.virtualfactory.entity.E_Game;
import com.virtualfactory.entity.E_Machine;
import com.virtualfactory.entity.E_Operator;
import com.virtualfactory.entity.E_Purchase;
import com.virtualfactory.entity.E_Ship;
import com.virtualfactory.entity.E_Station;
import com.virtualfactory.utils.CommonBuilders;
import com.virtualfactory.utils.GameType;
import com.virtualfactory.utils.Pair;
import com.virtualfactory.utils.Params;
import com.virtualfactory.utils.Sounds;
import com.virtualfactory.utils.StationType;
import com.virtualfactory.utils.Utils;
import java.util.ArrayList;
import java.util.Properties;
/**
*
* @author David
*/
public class OverallScreenController implements Controller {
private Nifty nifty;
private Screen screen;
private GameEngine gameEngine;
private WindowControl winControls;
private boolean isVisible;
private Element quitPopup;
private Element gameOverPopup;
private boolean isExpanded_OperatorCosts = false;
private boolean isExpanded_MachineEquipmentCosts = false;
private boolean isExpanded_OtherCosts = false;
private NiftyImage imageAdd;
private NiftyImage imageMinus;
private Align overall_label = Align.Left;
private Align overall_value = Align.Right;
private final CommonBuilders common = new CommonBuilders();
private String sizePreviousImage = "35px";
private boolean isUpdating = false;
@Override
public void bind(
final Nifty nifty,
final Screen screen,
final Element element,
final Properties parameter,
final Attributes controlDefinitionAttributes) {
this.nifty = nifty;
this.screen = screen;
this.winControls = screen.findNiftyControl("winOverallControl", WindowControl.class);
Attributes x = new Attributes();
x.set("hideOnClose", "true");
this.winControls.bind(nifty, screen, winControls.getElement(), null, x);
Attributes y = new Attributes();
y.set("closeable", "false");
this.winControls.bind(nifty, screen, winControls.getElement(), null, y);
isVisible = false;
quitPopup = nifty.createPopup("quitPopup");
gameOverPopup = nifty.createPopup("gameOverByBankruptcy");
imageAdd = nifty.createImage("Interface/Principal/add_gray.png", false);
imageMinus = nifty.createImage("Interface/Principal/minus_gray.png", false);
}
public boolean isIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
@Override
public void init(final Properties parameter, final Attributes controlDefinitionAttributes) {
}
@Override
public void onStartScreen() {
}
@Override
public void onFocus(final boolean getFocus) {
}
@Override
public boolean inputEvent(final NiftyInputEvent inputEvent) {
return false;
}
@NiftyEventSubscriber(id="overallRefresh")
public void onRefreshButtonClicked(final String id, final ButtonClickedEvent event) {
updateData();
}
public void loadWindowControl(GameEngine game,int index, Pair<Integer,Integer> position){
this.gameEngine = game;
if (index == -1){
winControls.getElement().setVisible(false);
winControls.getContent().hide();
isVisible = false;
}else{
winControls.getElement().setVisible(true);
winControls.getContent().show();
isVisible = true;
if (position != null){
if (winControls.getWidth() + position.getFirst() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth())
position.setFirst(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth() - winControls.getWidth());
if (winControls.getHeight() + position.getSecond() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight())
position.setSecond(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight() - winControls.getHeight());
winControls.getElement().setConstraintX(new SizeValue(position.getFirst() + "px"));
winControls.getElement().setConstraintY(new SizeValue(position.getSecond() + "px"));
winControls.getElement().getParent().layoutElements();
}
// winControls.getElement().setConstraintX(null);
// winControls.getElement().setConstraintY(null);
}
loadValues(index);
}
private void loadValues(int index){
if (index == -1){
((Label)screen.findNiftyControl("currentMoneyValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(0));
((Label)screen.findNiftyControl("totalExpendituresValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(0));
((Label)screen.findNiftyControl("totalIncomesValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(0));
((Label)screen.findNiftyControl("totalProfitValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(0));
}else{
updateData();
}
}
public void updateData(){
if (isUpdating) return;
isUpdating = true;
double currentMoney = 0;
double initialMoney = 0;
double totalOverHead = ((gameEngine.getGameData().getCurrentTimeWithFactor() - gameEngine.getGameData().getInitialTimeWithFactor())/Params.overheadRateInMinutes)*gameEngine.getGameData().getCurrentGame().getOverhead();
double totalCostOperators = 0;
double totalHireOperators = gameEngine.getGameData().getTotalOperatorsHire();
double totalFireOperators = gameEngine.getGameData().getTotalOperatorsFire();
double totalCostMachines = 0;
double totalPurchaseMachines = gameEngine.getGameData().getTotalMachinesPurchase();
double totalPreventiveMaintenanceMachine = gameEngine.getGameData().getTotalMachinePreventiveMaintenance();
double totalSaleMachines = gameEngine.getGameData().getTotalMachinesSale();
double totalCostEquipment = 0;
double totalPurchaseEquipment = gameEngine.getGameData().getTotalEquipmentPurchase();
double totalPreventiveMaintenanceEquipment = gameEngine.getGameData().getTotalEquipmentPreventiveMaintenance();
double totalSaleEquipment = gameEngine.getGameData().getTotalEquipmentSale();
double totalCostStations = 0;
double totalCostPurchases = 0;
double totalIncomeShips = 0;
double totalExpenditures = 0;
double totalIncomes = 0;
double totalProfit = 0;
initialMoney = gameEngine.getGameData().getCurrentGame().getInitialMoney();
// ((Label)screen.findNiftyControl("initialMoneyValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(initialMoney));
for (E_Operator operator : gameEngine.getGameData().getMapUserOperator().values())
totalCostOperators += operator.updateAndGetEarnedMoney();
for (E_Machine machine : gameEngine.getGameData().getMapUserMachineByOperation().values())
totalCostMachines += machine.getAccumulatedCost();
for (E_Machine equipment : gameEngine.getGameData().getMapUserMachineByTransport().values())
totalCostEquipment += equipment.getAccumulatedCost();
for (E_Station station : gameEngine.getGameData().getMapUserStation().values()){
if (station.getStationType().equals(StationType.StorageRM) || station.getStationType().equals(StationType.StorageIG) || station.getStationType().equals(StationType.StorageFG)){
totalCostStations += station.getTotalCostBySlots();
// for (E_Bucket bucket : station.getArrBuckets())
// totalCostStations += bucket.updateAndGetTotalCost();
}
}
for (E_Purchase purchase : gameEngine.getGameData().getMapPurchase().values())
totalCostPurchases += purchase.getAccumulatedCosts();
for (E_Ship ship : gameEngine.getGameData().getMapShip().values())
totalIncomeShips += ship.getIncomeAccumulated();
currentMoney = initialMoney - totalCostOperators - totalHireOperators - totalFireOperators - totalOverHead
- totalCostMachines - totalPurchaseMachines - totalPreventiveMaintenanceMachine + totalSaleMachines
- totalPurchaseEquipment - totalPreventiveMaintenanceEquipment + totalSaleEquipment
- totalCostStations - totalCostPurchases + totalIncomeShips;
gameEngine.getGameData().getCurrentGame().setCurrentMoney(Utils.formatValue2Dec(currentMoney));
totalExpenditures = totalCostOperators + totalFireOperators + totalHireOperators + totalCostMachines + totalPurchaseMachines +
totalPreventiveMaintenanceMachine + totalPurchaseEquipment + totalPreventiveMaintenanceEquipment +
totalCostStations + totalCostPurchases + totalOverHead;
totalIncomes = totalSaleMachines + totalSaleEquipment + totalIncomeShips;
totalProfit = totalIncomes - totalExpenditures;
if (isVisible){
if (isExpanded_OperatorCosts){
((Label)screen.findNiftyControl("costOperatorValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostOperators) + ")");
((Label)screen.findNiftyControl("hireOperatorValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalHireOperators) + ")");
((Label)screen.findNiftyControl("fireOperatorValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalFireOperators) + ")");
}
if (isExpanded_MachineEquipmentCosts){
((Label)screen.findNiftyControl("costMachineValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostMachines) + ")");
((Label)screen.findNiftyControl("purchaseMachineValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalPurchaseMachines) + ")");
((Label)screen.findNiftyControl("preventiveMaintenanceMachineValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalPreventiveMaintenanceMachine) + ")");
((Label)screen.findNiftyControl("purchaseEquipmentValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalPurchaseEquipment) + ")");
((Label)screen.findNiftyControl("preventiveMaintenanceEquipmentValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalPreventiveMaintenanceEquipment) + ")");
}
if (isExpanded_OtherCosts){
((Label)screen.findNiftyControl("costOverheadValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalOverHead) + ")");
((Label)screen.findNiftyControl("costStationsValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostStations) + ")");
((Label)screen.findNiftyControl("costPurchasesValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostPurchases) + ")");
}
((Label)screen.findNiftyControl("operatorCostsValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostOperators+totalHireOperators+totalFireOperators) + ")");
((Label)screen.findNiftyControl("machineEquipmentCostsValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalCostMachines+totalPurchaseMachines+totalPreventiveMaintenanceMachine+totalPurchaseEquipment+totalPreventiveMaintenanceEquipment) + ")");
((Label)screen.findNiftyControl("otherCostsValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalOverHead+totalCostStations+totalCostPurchases) + ")");
((Label)screen.findNiftyControl("saleMachineValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(totalSaleMachines));
((Label)screen.findNiftyControl("saleEquipmentValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(totalSaleEquipment));
((Label)screen.findNiftyControl("incomeForSalesValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(totalIncomeShips));
((Label)screen.findNiftyControl("currentMoneyValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(currentMoney));
((Label)screen.findNiftyControl("totalExpendituresValue_WOvC", Label.class)).setText("(" + Utils.formatValue2DecToString(totalExpenditures) + ")");
((Label)screen.findNiftyControl("totalIncomesValue_WOvC", Label.class)).setText(Utils.formatValue2DecToString(totalIncomes));
((Label)screen.findNiftyControl("totalProfitValue_WOvC", Label.class)).setText(totalProfit<0 ? "(" + Utils.formatValue2DecToString(totalProfit) + ")" : Utils.formatValue2DecToString(totalProfit));
}
if (currentMoney <= 0){
//GAME OVER!!!! YOU LOST!!
gameEngine.getGameSounds().stopSound(Sounds.Background);
gameEngine.getGameSounds().stopSound(Sounds.GameNoMoney);
gameEngine.getGameSounds().playSound(Sounds.GameOver);
gameEngine.getLayerScreenController().pauseGame();
gameEngine.getGameData().getCurrentGame().setAttemptNumbers(gameEngine.getGameData().getCurrentGame().getAttemptNumbers()+1);
gameEngine.getGameData().updatePlayerLog();
gameEngine.getGameData().updateFailedGame();
gameEngine.setExecuteGame(false);
nifty.showPopup(screen, gameOverPopup.getId(), null);
}
isUpdating = false;
}
@NiftyEventSubscriber(id="gameOverRestartB")
public void onGameOverRestartButtonClicked(final String id, final ButtonClickedEvent event) {
nifty.closePopup(gameOverPopup.getId());
ArrayList<E_Game> games = gameEngine.getGameData().loadGamesByType(GameType.CPU);
E_Game game = null;
for (E_Game tempGame : games){
if (gameEngine.getInitialGameId() == tempGame.getIdGame()){
game = tempGame;
break;
}
}
if (game != null){
gameEngine.playGame(game,true);
// gameEngine.getLayerScreenController().playGame();
}
}
@NiftyEventSubscriber(id="gameOverQuitB")
public void onGameOverQuitButtonClicked(final String id, final ButtonClickedEvent event) {
nifty.showPopup(screen, quitPopup.getId(), null);
}
@NiftyEventSubscriber(pattern="quitPopup.*")
public void onAnswerPopupButtonClicked(final String id, final ButtonClickedEvent event) {
if (id.equals("quitPopupYes")){
gameEngine.getGameData().logoutPlayer();
gameEngine.jmonkeyApp.stop();
System.exit(0);
}else{
nifty.closePopup(quitPopup.getId());
}
}
public void clickToOperatorCosts(){
if (isExpanded_OperatorCosts){
screen.findElementByName("imageOperatorCosts").getRenderer(ImageRenderer.class).setImage(imageAdd);
}else{
screen.findElementByName("imageOperatorCosts").getRenderer(ImageRenderer.class).setImage(imageMinus);
}
loadOperatorCosts(!isExpanded_OperatorCosts);
isExpanded_OperatorCosts = !isExpanded_OperatorCosts;
updateLocation();
}
public void clickToMachineEquipmentCosts(){
if (isExpanded_MachineEquipmentCosts){
screen.findElementByName("imageMachineEquipmentCosts").getRenderer(ImageRenderer.class).setImage(imageAdd);
}else{
screen.findElementByName("imageMachineEquipmentCosts").getRenderer(ImageRenderer.class).setImage(imageMinus);
}
loadMachineEquipmentCosts(!isExpanded_MachineEquipmentCosts);
isExpanded_MachineEquipmentCosts = !isExpanded_MachineEquipmentCosts;
updateLocation();
}
public void clickToOtherCosts(){
if (isExpanded_OtherCosts){
screen.findElementByName("imageOtherCosts").getRenderer(ImageRenderer.class).setImage(imageAdd);
}else{
screen.findElementByName("imageOtherCosts").getRenderer(ImageRenderer.class).setImage(imageMinus);
}
loadOtherCosts(!isExpanded_OtherCosts);
isExpanded_OtherCosts = !isExpanded_OtherCosts;
updateLocation();
}
private void loadOperatorCosts(boolean isLoading){
int newHeight;
String panelName = "operatorCosts_parent";
if (isLoading){
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("costOperator_WOvC","Operator Cost/Hour:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("costOperatorValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("costOperatorValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("hireOperator_WOvC","Operator Hire:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("hireOperatorSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("hireOperatorValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("fireOperator_WOvC","Operator Fire:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("fireOperatorValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("fireOperatorValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
newHeight = 60;
}else{
for(Element tempElement : screen.findElementByName(panelName).getElements())
tempElement.markForRemoval();
newHeight = -60;
}
winControls.setHeight(new SizeValue(String.valueOf(winControls.getHeight() + newHeight)));
screen.findElementByName(panelName).layoutElements();
screen.findElementByName("winOverallControl").getParent().layoutElements();
}
private void loadMachineEquipmentCosts(boolean isLoading){
int newHeight;
String panelName = "machineEquipmentCosts_parent";
if (isLoading){
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("costMachine_WOvC","Machine Cost/Hour:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("costMachineValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("costMachineValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("purchaseMachine_WOvC","Machine Purchase:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("purchaseMachineValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("purchaseMachineValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("preventiveMaintenanceMachine_WOvC","Machine Prev.Maint.:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("preventiveMaintenanceMachineValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("preventiveMaintenanceMachineValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("purchaseEquipment_WOvC","Equipment Purchase:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("purchaseEquipmentValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("purchaseEquipmentValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("preventiveMaintenanceEquipment_WOvC","Equipment Prev.Maint.:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("preventiveMaintenanceEquipmentValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("preventiveMaintenanceEquipmentValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
newHeight = 120;
}else{
for(Element tempElement : screen.findElementByName(panelName).getElements())
tempElement.markForRemoval();
newHeight = -120;
}
winControls.setHeight(new SizeValue(String.valueOf(winControls.getHeight() + newHeight)));
screen.findElementByName(panelName).layoutElements();
screen.findElementByName("winOverallControl").getParent().layoutElements();
}
private void loadOtherCosts(boolean isLoading){
int newHeight;
String panelName = "otherCosts_parent";
if (isLoading){
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("costOverhead_WOvC","Overhead Cost/Hour:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("costOverheadValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("costOverheadValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("costStations_WOvC","Storage Cost/Hour:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("costStationsValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("costStationsValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
new PanelBuilder(){{
childLayoutHorizontal();
panel(common.hspacer(sizePreviousImage));
control(new LabelBuilder("costPurchases_WOvC","Part Purchase:"){{ width("160px"); height("20px"); textHAlign(overall_label); }}); panel(common.hspacer("5px"));
control(new LabelBuilder("costPurchasesValueSign_WOvC",Params.moneySign){{ width(Params.moneySignSizeField); height("20px"); textHAlignCenter(); }});
control(new LabelBuilder("costPurchasesValue_WOvC","_"){{ width("70px"); height("20px"); textHAlign(overall_value); }});
}}.build(nifty, screen, screen.findElementByName(panelName));
newHeight = 60;
}else{
for(Element tempElement : screen.findElementByName(panelName).getElements())
tempElement.markForRemoval();
newHeight = -60;
}
winControls.setHeight(new SizeValue(String.valueOf(winControls.getHeight() + newHeight)));
screen.findElementByName(panelName).layoutElements();
screen.findElementByName("winOverallControl").getParent().layoutElements();
}
private void updateLocation(){
int initialY = Params.screenHeight - (720 - 488);//nifty.getScreen("layerScreen").findElementByName("winOverallControl").getY();
int yOperators = 60;
int yMachines = 120;
int yOthers = 60;
if (isExpanded_OperatorCosts)
initialY -= yOperators;
if (isExpanded_MachineEquipmentCosts)
initialY -= yMachines;
if (isExpanded_OtherCosts)
initialY -= yOthers;
winControls.getElement().setConstraintY(new SizeValue(initialY + "px"));
winControls.getElement().getParent().layoutElements();
}
public void HideWindow()
{
nifty.getScreen("layerScreen").findElementByName("winOverallControl").hide();
nifty.getScreen("layerScreen").findElementByName("OverallLabel").show();
}
public void ShowWindow(){
nifty.getScreen("layerScreen").findElementByName("winOverallControl").show();
nifty.getScreen("layerScreen").findElementByName("OverallLabel").hide();
}
public void refresh(boolean bool) {
if (bool) {
if (isExpanded_OperatorCosts)
clickToOperatorCosts();
if (isExpanded_MachineEquipmentCosts)
clickToMachineEquipmentCosts();
if (isExpanded_OtherCosts)
clickToOtherCosts();
int h = Params.screenHeight - (720 - 488);
nifty.getScreen("layerScreen").findElementByName("winOverallControl").setConstraintY(new SizeValue(h + "px"));
}
}
}
|
package HxCKDMS.HxCBlocks.Reference;
public class References {
public static final String MOD_ID = "HxCBlocks";
public static final String MOD_NAME = "HxC-Blocks";
public static final String VERSION = "1.6.2";
public static final String SERVER_PROXY_LOCATION = "HxCKDMS.HxCBlocks.Proxy.ServerProxy";
public static final String CLIENT_PROXY_LOCATION = "HxCKDMS.HxCBlocks.Proxy.ClientProxy";
public static final String DEPENDENCIES = "required-after:HxCCore@[1.8.0,)";
}
|
package org.rstudio.studio.client.workbench.views.viewer;
import com.google.inject.Inject;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.plumber.events.PlumberAPIStatusEvent;
import org.rstudio.studio.client.shiny.events.ShinyApplicationStatusEvent;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.ui.DelayLoadTabShim;
import org.rstudio.studio.client.workbench.ui.DelayLoadWorkbenchTab;
import org.rstudio.studio.client.workbench.views.viewer.events.ViewerClearedEvent;
import org.rstudio.studio.client.workbench.views.viewer.events.ViewerNavigateEvent;
import org.rstudio.studio.client.workbench.views.viewer.events.ViewerPreviewRmdEvent;
public class ViewerTab extends DelayLoadWorkbenchTab<ViewerPresenter>
{
public abstract static class Shim
extends DelayLoadTabShim<ViewerPresenter, ViewerTab>
implements ViewerNavigateEvent.Handler,
ViewerPreviewRmdEvent.Handler,
ViewerClearedEvent.Handler,
ShinyApplicationStatusEvent.Handler,
PlumberAPIStatusEvent.Handler {}
@Inject
public ViewerTab(Shim shim, Session session, EventBus eventBus)
{
super("Viewer", shim);
session_ = session;
eventBus.addHandler(ViewerNavigateEvent.TYPE, shim);
eventBus.addHandler(ViewerPreviewRmdEvent.TYPE, shim);
eventBus.addHandler(ViewerClearedEvent.TYPE, shim);
eventBus.addHandler(ShinyApplicationStatusEvent.TYPE, shim);
eventBus.addHandler(PlumberAPIStatusEvent.TYPE, shim);
}
@SuppressWarnings("unused")
private Session session_;
}
|
package bammerbom.ultimatecore.bukkit.api;
import bammerbom.ultimatecore.bukkit.UltimateFileLoader;
import bammerbom.ultimatecore.bukkit.configuration.Config;
import bammerbom.ultimatecore.bukkit.configuration.ConfigSection;
import bammerbom.ultimatecore.bukkit.resources.classes.MetaItemStack;
import bammerbom.ultimatecore.bukkit.resources.utils.DateUtil;
import bammerbom.ultimatecore.bukkit.resources.utils.ItemUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* A class representing a kit.
*/
public class UKit {
private static final Config kits = new Config(UltimateFileLoader.DFkits);
private final ConfigSection kit;
private final String name;
private final String description;
private final List<ItemStack> items;
private final long cooldown;
public UKit(final String name) {
this.name = name;
this.kit = kits.getConfigurationSection(name);
this.items = getItemStacks(kit.getMapList("items"));
this.cooldown = DateUtil.parseDateDiff(kit.getString("cooldown", "0"));
this.description = ChatColor.translateAlternateColorCodes('&', kit.getString("description", ""));
}
/**
* Adds a list of represented enchantments to an ItemStack.
*
* @param is ItemStack to add enchantments to
* @param enchantments List of nodes representing enchantments
* @return ItemStack with enchantments applied
*/
private ItemStack addEnchantments(final ItemStack is, final List<ConfigSection> enchantments) {
for (final ConfigSection enchantment : enchantments) {
final Enchantment realEnchantment = this.getEnchantment(enchantment);
if (realEnchantment == null) {
continue;
}
is.addUnsafeEnchantment(realEnchantment, enchantment.getInt("level", 1));
}
return is;
}
/**
* Gets an enchantment from a node representing it.
*
* @param enchantment Node
* @return Enchantment (may be null)
*/
private Enchantment getEnchantment(final ConfigSection enchantment) {
return Enchantment.getByName(enchantment.getString("type", "").toUpperCase());
}
/**
* Gets an ItemStack from the given node
*
* @param item Node representing an ItemStack
* @return ItemStack of null
*/
private ItemStack getItemStack(final Map<String, Object> item) {
final ItemStack is = ItemUtil.searchItem((String) item.get("type"));
if (is == null) {
return null;
}
if (item.containsKey("amount")) {
is.setAmount((int) item.get("amount"));
}
if (item.containsKey("damage")) {
is.setDurability(((Number) item.get("damage")).shortValue());
}
MetaItemStack ism = new MetaItemStack(is);
for (String s : item.keySet()) {
if (s.equalsIgnoreCase("amount") || s.equalsIgnoreCase("type") || s.equalsIgnoreCase("damage")) {
continue;
}
try {
ism.addStringMeta(null, true, s + ":" + item.get(s).toString().replaceAll(" ", "_"));
} catch (Exception ex) {
continue;
}
}
return ism.getItemStack();
}
/**
* Gets all of the ItemStacks represented by the list of nodes.
*
* @param items List of nodes representing items
* @return List of ItemStacks, never null
*/
private List<ItemStack> getItemStacks(final List<Map<?, ?>> items) {
final List<ItemStack> itemStacks = new ArrayList<>();
for (final Map<?, ?> item : items) {
HashMap<String, Object> itemc = new HashMap<>();
itemc.putAll((Map<? extends String, ? extends Object>) item);
final ItemStack is = this.getItemStack(itemc);
if (is == null) {
continue;
}
itemStacks.add(is);
}
return itemStacks;
}
/**
* Gets the lore for the given item.
*
* @param item Item to get lore for
* @return List of strings, never null
*/
private List<String> getLore(final ConfigSection item) {
final List<String> lore = new ArrayList<>();
if (item == null) {
return lore;
}
for (final String loreItem : item.getStringList("lore")) {
lore.add(ChatColor.translateAlternateColorCodes('&', loreItem));
}
return lore;
}
/**
* Gets the amount of seconds this kit's cooldown is.
*
* @return Seconds
*/
public long getCooldown() {
return this.cooldown;
}
/**
* Gets the timestamp in milliseconds for when the cooldown for the given
* player will expire.
*
* @param p Player
* @return Cooldown expiration timestamp in milliseconds
*/
public long getCooldownFor(final Player p) {
final long lastUsed = this.getLastUsed(p);
return (this.getCooldown()) + lastUsed;
}
/**
* Gets the description of this kit, suitable for display to players.
*
* @return Description
*/
public String getDescription() {
return this.description;
}
/**
* Gets a cloned list of items contained in this kit.
*
* @return Cloned list
*/
public List<ItemStack> getItems() {
return new ArrayList<>(this.items);
}
/**
* Gets the timestamp in milliseconds that the player last used this kit.
*
* @param p Player
* @return Timestamp in milliseconds
*/
public long getLastUsed(final Player p) {
return UC.getPlayer(p).getPlayerConfig().getLong("kits." + this.getName() + ".lastused", 0L);
}
/**
* Gets the name of this kit.
*
* @return Name
*/
public String getName() {
return this.name;
}
/**
* Checks to see if the cooldown time has passed for the player using this
* kit. If this returns true, the player can use the kit, if not, he can't.
*
* @param p RPlayer using kit
* @return If the player can use the kit
*/
public boolean hasCooldownPassedFor(final Player p) {
final long lastUsed = this.getLastUsed(p);
return !(this.getCooldown() == -1L && lastUsed != 0L) && lastUsed + (this.getCooldown()) < System.currentTimeMillis();
}
/**
* Sets the last time that the player used this kit.
*
* @param p Player using kit
* @param lastUsed Timestamp in milliseconds
*/
public void setLastUsed(final Player p, final long lastUsed) {
if (this.getCooldown() == 0L) {
return;
}
Config conf = UC.getPlayer(p).getPlayerConfig();
conf.set("kits." + this.getName() + ".lastused", lastUsed);
conf.save();
}
}
|
package ch.ethz.geco.gecko.command;
import ch.ethz.geco.gecko.command.audio.Join;
import ch.ethz.geco.gecko.command.audio.Leave;
import ch.ethz.geco.gecko.command.core.Avatar;
import ch.ethz.geco.gecko.command.core.Ping;
import ch.ethz.geco.gecko.command.core.Restart;
import ch.ethz.geco.gecko.command.core.Update;
import ch.ethz.geco.gecko.command.misc.Test;
import ch.ethz.geco.gecko.command.misc.Whois;
/**
* This class is just for having all registered commands in one place
*/
public class CommandBank {
/**
* Registers all commands in the CommandRegistry
*/
public static void registerCommands() {
// Audio
CommandRegistry.registerCommand(new Join());
CommandRegistry.registerCommand(new Leave());
// Core
CommandRegistry.registerCommand(new Avatar());
CommandRegistry.registerCommand(new Ping());
CommandRegistry.registerCommand(new Restart());
CommandRegistry.registerCommand(new Update());
// Misc
CommandRegistry.registerCommand(new Whois());
CommandRegistry.registerCommand(new Test());
}
}
|
package StevenDimDoors.mod_pocketDim.tileentities;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet132TileEntityData;
import net.minecraft.util.AxisAlignedBB;
import StevenDimDoors.mod_pocketDim.ServerPacketHandler;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.config.DDProperties;
import StevenDimDoors.mod_pocketDim.core.DimLink;
import StevenDimDoors.mod_pocketDim.core.NewDimData;
import StevenDimDoors.mod_pocketDim.core.PocketManager;
import StevenDimDoors.mod_pocketDim.util.Point4D;
public class TileEntityRift extends DDTileEntityBase
{
private static final int RIFT_INTERACTION_RANGE = 5;
private static final int MAX_ANCESTOR_LINKS = 2;
private static final int MAX_CHILD_LINKS = 1;
private static final int ENDERMAN_SPAWNING_CHANCE = 1;
private static final int MAX_ENDERMAN_SPAWNING_CHANCE = 32;
private static final int RIFT_SPREAD_CHANCE = 1;
private static final int MAX_RIFT_SPREAD_CHANCE = 256;
private static final int HOSTILE_ENDERMAN_CHANCE = 1;
private static final int MAX_HOSTILE_ENDERMAN_CHANCE = 3;
private static final int UPDATE_PERIOD = 200;
private static final int CLOSING_PERIOD = 40;
private static Random random = new Random();
private int updateTimer;
private int closeTimer = 0;
public int xOffset = 0;
public int yOffset = 0;
public int zOffset = 0;
public boolean shouldClose = false;
public DimLink nearestRiftData;
public int spawnedEndermenID = 0;
public TileEntityRift()
{
// Vary the update times of rifts to prevent all the rifts in a cluster
// from updating at the same time.
updateTimer = random.nextInt(UPDATE_PERIOD);
}
@Override
public void updateEntity()
{
if (PocketManager.getLink(xCoord, yCoord, zCoord, worldObj.provider.dimensionId) == null)
{
if (worldObj.getBlockId(xCoord, yCoord, zCoord) == mod_pocketDim.blockRift.blockID)
{
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
}
else
{
this.invalidate();
}
return;
}
if (worldObj.getBlockId(xCoord, yCoord, zCoord) != mod_pocketDim.blockRift.blockID)
{
this.invalidate();
return;
}
// Check if this rift should render white closing particles and
// spread the closing effect to other rifts nearby.
if (this.shouldClose)
{
closeRift();
return;
}
if (updateTimer >= UPDATE_PERIOD)
{
this.spawnEndermen(mod_pocketDim.properties);
updateTimer = 0;
}
else if (updateTimer == UPDATE_PERIOD / 2)
{
this.calculateParticleOffsets();
this.spread(mod_pocketDim.properties);
}
updateTimer++;
}
private void spawnEndermen(DDProperties properties)
{
if (worldObj.isRemote || !properties.RiftsSpawnEndermenEnabled)
{
return;
}
// Ensure that this rift is only spawning one Enderman at a time, to prevent hordes of Endermen
Entity entity = worldObj.getEntityByID(this.spawnedEndermenID);
if (entity != null && entity instanceof EntityEnderman)
{
return;
}
if (random.nextInt(MAX_ENDERMAN_SPAWNING_CHANCE) < ENDERMAN_SPAWNING_CHANCE)
{
// Endermen will only spawn from groups of rifts
if (updateNearestRift())
{
List<Entity> list = worldObj.getEntitiesWithinAABB(EntityEnderman.class,
AxisAlignedBB.getBoundingBox(xCoord - 9, yCoord - 3, zCoord - 9, xCoord + 9, yCoord + 3, zCoord + 9));
if (list.isEmpty())
{
EntityEnderman enderman = new EntityEnderman(worldObj);
enderman.setLocationAndAngles(xCoord + 0.5, yCoord - 1, zCoord + 0.5, 5, 6);
worldObj.spawnEntityInWorld(enderman);
if (random.nextInt(MAX_HOSTILE_ENDERMAN_CHANCE) < HOSTILE_ENDERMAN_CHANCE)
{
EntityPlayer player = this.worldObj.getClosestPlayerToEntity(enderman, 50);
if (player != null)
{
enderman.setTarget(player);
}
}
}
}
}
}
public boolean updateNearestRift()
{
nearestRiftData = PocketManager.getDimensionData(worldObj).findNearestRift(this.worldObj, 5, xCoord, yCoord, zCoord);
return (nearestRiftData != null);
}
private void closeRift()
{
NewDimData dimension = PocketManager.getDimensionData(worldObj);
if (closeTimer == CLOSING_PERIOD / 2)
{
ArrayList<DimLink> riftLinks = dimension.findRiftsInRange(worldObj, 6, xCoord, yCoord, zCoord);
if (riftLinks.size() > 0)
{
for (DimLink riftLink : riftLinks)
{
Point4D location = riftLink.source();
TileEntityRift rift = (TileEntityRift) worldObj.getBlockTileEntity(location.getX(), location.getY(), location.getZ());
if (rift != null)
{
rift.shouldClose = true;
rift.onInventoryChanged();
}
}
}
}
if (closeTimer >= CLOSING_PERIOD)
{
if (!this.worldObj.isRemote)
{
DimLink link = PocketManager.getLink(this.xCoord, this.yCoord, this.zCoord, worldObj);
if (link != null)
{
dimension.deleteLink(link);
}
}
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
worldObj.playSound(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, "mods.DimDoors.sfx.riftClose", 0.7f, 1, false);
}
closeTimer++;
}
private void calculateParticleOffsets()
{
if (updateNearestRift())
{
Point4D location = nearestRiftData.source();
this.xOffset = this.xCoord - location.getX();
this.yOffset = this.yCoord - location.getY();
this.zOffset = this.zCoord - location.getZ();
}
else
{
this.xOffset = 0;
this.yOffset = 0;
this.xOffset = 0;
}
this.onInventoryChanged();
}
@Override
public boolean shouldRenderInPass(int pass)
{
return pass == 1;
}
public int countAncestorLinks(DimLink link)
{
if (link.parent() != null)
{
return countAncestorLinks(link.parent()) + 1;
}
return 0;
}
public void spread(DDProperties properties)
{
if (worldObj.isRemote || !properties.RiftSpreadEnabled
|| random.nextInt(MAX_RIFT_SPREAD_CHANCE) < RIFT_SPREAD_CHANCE || this.shouldClose)
{
return;
}
NewDimData dimension = PocketManager.getDimensionData(worldObj);
DimLink link = dimension.getLink(xCoord, yCoord, zCoord);
if (link.childCount() >= MAX_CHILD_LINKS || countAncestorLinks(link) >= MAX_ANCESTOR_LINKS)
{
return;
}
// The probability of rifts trying to spread increases if more rifts are nearby.
// Players should see rifts spread faster within clusters than at the edges of clusters.
// Also, single rifts CANNOT spread.
int nearRifts = dimension.findRiftsInRange(worldObj, RIFT_INTERACTION_RANGE, xCoord, yCoord, zCoord).size();
if (nearRifts == 0 || random.nextInt(nearRifts) == 0)
{
return;
}
mod_pocketDim.blockRift.spreadRift(dimension, link, worldObj, random);
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.updateTimer = nbt.getInteger("updateTimer");
this.xOffset = nbt.getInteger("xOffset");
this.yOffset = nbt.getInteger("yOffset");
this.zOffset = nbt.getInteger("zOffset");
this.shouldClose = nbt.getBoolean("shouldClose");
this.spawnedEndermenID = nbt.getInteger("spawnedEndermenID");
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setInteger("updateTimer", this.updateTimer);
nbt.setInteger("xOffset", this.xOffset);
nbt.setInteger("yOffset", this.yOffset);
nbt.setInteger("zOffset", this.zOffset);
nbt.setBoolean("shouldClose", this.shouldClose);
nbt.setInteger("spawnedEndermenID", this.spawnedEndermenID);
}
@Override
public Packet getDescriptionPacket()
{
if (PocketManager.getLink(xCoord, yCoord, zCoord, worldObj) != null)
{
return ServerPacketHandler.createLinkPacket(PocketManager.getLink(xCoord, yCoord, zCoord, worldObj).link());
}
return null;
}
@Override
public void onDataPacket(INetworkManager net, Packet132TileEntityData pkt)
{
readFromNBT(pkt.data);
}
@Override
public float[] getRenderColor(Random rand)
{
return null;
}
}
|
package club.magicfun.aquila.job;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import club.magicfun.aquila.model.Job;
import club.magicfun.aquila.model.Rank;
import club.magicfun.aquila.model.RankSearchQueue;
import club.magicfun.aquila.model.RankSearchType;
import club.magicfun.aquila.service.RankingService;
import club.magicfun.aquila.service.ScheduleService;
import club.magicfun.aquila.util.HtmlUtility;
import club.magicfun.aquila.util.StringUtility;
@Component
public class RankSearchJob {
private static final Logger logger = LoggerFactory.getLogger(RankSearchJob.class);
private static final String RANK_SEARCH_URL_TEMPLATE = "http://s.taobao.com/search?q={KEYWORD}&sort={SORTTYPE}&style=list";
private static final int RANK_SEARCH_QUEUE_NUMBER_PER_TIME = 5;
@Autowired
private ScheduleService scheduleService;
@Autowired
private RankingService rankingService;
public RankSearchJob() {
super();
}
@Scheduled(cron = "0/30 * * * * ? ")
public void run() {
String className = this.getClass().getName();
Job job = scheduleService.findJobByClassName(className);
// determine if to run this job
if (job != null && job.isJobReadyToRun()) {
job = scheduleService.startJob(job);
logger.info("Job [" + job.getId() + "," + job.getClassName() + "] is started.");
List<RankSearchQueue> rankSearchQueues = rankingService.findFewActivePendingRankSearchQueues(RANK_SEARCH_QUEUE_NUMBER_PER_TIME);
if (rankSearchQueues != null && rankSearchQueues.size() > 0) {
logger.info("Rank Search Queues count = " + rankSearchQueues.size());
for (RankSearchQueue rankSearchQueue : rankSearchQueues) {
logger.info("Dealing with Rank Search Queues: " + rankSearchQueue.getKeyword());
// delete ranks first by rank search queue id
List<Rank> originalRanks = rankingService.findAllRanksByRankSearchQueueId(rankSearchQueue.getId());
if (originalRanks != null && originalRanks.size() > 0) {
rankingService.deleteRanksInBatch(originalRanks);
logger.info(originalRanks.size() + " old ranks had been deleted.");
}
boolean containsError = false;
Set<RankSearchType> rankSearchTypes = rankSearchQueue.getRankSearchTypes();
if (rankSearchTypes != null) {
try {
WebDriver webDriver = new ChromeDriver();
for (RankSearchType rankSearchType : rankSearchTypes) {
logger.info("Dealing with Rank Search Type: " + rankSearchType.getName());
String url = RANK_SEARCH_URL_TEMPLATE
.replaceFirst("\\{KEYWORD\\}", rankSearchQueue.getKeyword())
.replaceFirst("\\{SORTTYPE\\}", rankSearchType.getSortType());
logger.info("URL: " + url);
webDriver.get(url);
List<WebElement> prodItemDivs = webDriver.findElements(By.xpath(
|
package com.aimmac23.node.jna;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.FileUtils;
import com.google.common.collect.FluentIterable;
import com.google.common.io.Files;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class JnaLibraryLoader {
private static final Logger log = Logger.getLogger(JnaLibraryLoader.class.getName());
static private LibVPX libVPX;
static private YUVLib yuvLib;
static private LibMKV libMKV;
static private EncoderInterface encoder;
// optional dependency
static private XvfbScreenshotInterface xvfbInterface;
private static void addNativePath(String path) {
NativeLibrary.addSearchPath("vpx", path);
NativeLibrary.addSearchPath("yuv", path);
NativeLibrary.addSearchPath("mkv", path);
NativeLibrary.addSearchPath("interface", path);
NativeLibrary.addSearchPath("xvfb_interface", path);
}
private static File extractJNABinariesIfAvailable() {
InputStream zipStream = JnaLibraryLoader.class.getClassLoader().getResourceAsStream("native.zip");
if(zipStream == null) {
throw new IllegalStateException("Native code zip file not found");
}
String targetDirectory = System.getProperty("java.io.tmpdir") + File.separator + "nativeCode-" + System.currentTimeMillis() + File.separator;
File target = new File(targetDirectory);
if(target.exists()) {
target.delete();
}
target.mkdir();
try {
ZipInputStream zipInputStream = new ZipInputStream(zipStream);
ZipEntry entry = null;
while((entry = zipInputStream.getNextEntry()) != null){
File extractedFilePath = new File(targetDirectory + entry.getName());
if(entry.isDirectory()) {
extractedFilePath.mkdirs();
continue;
}
FileOutputStream outputStream = new FileOutputStream(extractedFilePath);
byte[] buffer = new byte[1024];
int size = 0;
while((size = zipInputStream.read(buffer)) != -1){
outputStream.write(buffer, 0 , size);
}
outputStream.flush();
outputStream.close();
}
zipInputStream.close();
zipStream.close();
addNativePath(targetDirectory);
// at this point, we will have extracted the native libraries into a new temporary folder, containing directories
// "32bit" and "64bit". There is no platform-independent way to figure out what bit-size this JVM uses, and no way to
// change the search path of JNA once added, so we're going to copy things onto the search path instead and see what happens.
return target;
} catch(IOException e) {
log.info("Caught IOException");
throw new IllegalStateException("Could not extract native libraries", e);
}
}
public static void init() {
File targetDirectory = extractJNABinariesIfAvailable();
addShutdownCleanupHook(targetDirectory);
// this makes things work in Eclipse
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
for(String entry : classpathEntries) {
addNativePath(entry);
}
try {
tryBitDepth(BitDepth.BIT_64, targetDirectory);
}
catch(Error e) {
log.info("Could not load 64 bit native libraries - attempting 32 bit instead");
deleteAllFilesInDirectory(targetDirectory);
tryBitDepth(BitDepth.BIT_32, targetDirectory);
}
}
private static void deleteAllFilesInDirectory(File directory) {
File[] files = directory.listFiles();
for(File file : files) {
if(file.isFile()) {
file.delete();
}
}
}
private static void tryLoadLibraries() {
libVPX = (LibVPX) Native.loadLibrary("vpx", LibVPX.class);
yuvLib = (YUVLib) Native.loadLibrary("yuv", YUVLib.class);
libMKV = (LibMKV) Native.loadLibrary("mkv", LibMKV.class);
encoder = (EncoderInterface) Native.loadLibrary("interface", EncoderInterface.class);
}
private static void tryBitDepth(BitDepth depth, File targetDirectory) {
File sourceDirectory = new File(targetDirectory, depth.getDirectoryName());
if(!sourceDirectory.exists()) {
throw new IllegalStateException("Native code directory not found for bit depth: " + depth);
}
File[] filesToCopy = sourceDirectory.listFiles();
for(File file : filesToCopy) {
File destinationLocation = new File(targetDirectory, file.getName());
try {
FileUtils.copyFile(file, destinationLocation);
}
catch(IOException e) {
throw new IllegalStateException("Could not copy file: " + file + " to: " + destinationLocation, e);
}
}
tryLoadLibraries();
}
private static void disposeLibrary(Library lib, String name) {
if(lib != null) {
NativeLibrary.getInstance(name).dispose();
}
}
private static synchronized void addShutdownCleanupHook(final File extractedDirectory) {
Thread shutdownThread = new Thread(new Runnable() {
@Override
public void run() {
// close the native libraries in reverse order
disposeLibrary(xvfbInterface, "xvfb_interface");
disposeLibrary(encoder, "interface");
disposeLibrary(libMKV, "mkv");
disposeLibrary(yuvLib, "yuv");
disposeLibrary(libVPX, "vpx");
// Java File doesn't want to recursively delete things
Iterator<File> iterator = Files.fileTreeTraverser().postOrderTraversal(extractedDirectory).iterator();
while(iterator.hasNext()) {
iterator.next().delete();
}
}
}, "JNA Shutdown Hook Thread");
Runtime.getRuntime().addShutdownHook(shutdownThread);
}
public static EncoderInterface getEncoder() {
return encoder;
}
public static YUVLib getYuvLib() {
return yuvLib;
}
public static LibVPX getLibVPX() {
return libVPX;
}
public static XvfbScreenshotInterface getXvfbInterface() {
if(xvfbInterface == null) {
xvfbInterface = (XvfbScreenshotInterface) Native.loadLibrary("xvfb_interface", XvfbScreenshotInterface.class);
}
return xvfbInterface;
}
private static enum BitDepth {
BIT_32("32bit"), BIT_64("64bit");
private String directoryName;
private BitDepth(String directoryName) {
this.directoryName = directoryName;
}
public String getDirectoryName() {
return directoryName;
}
}
}
|
package com.blog.start.jpa.service;
import com.blog.start.exception.RssException;
import com.blog.start.jpa.entity.Blog;
import com.blog.start.jpa.entity.Item;
import com.blog.start.jpa.entity.User;
import com.blog.start.jpa.repositorie.BlogRepository;
import com.blog.start.jpa.repositorie.ItemRepository;
import com.blog.start.jpa.repositorie.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BlogService {
@Autowired
private BlogRepository blogRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private RssService rssService;
@Autowired
private ItemRepository itemRepository;
public void saveItems(Blog blog) {
try {
List<Item> items = rssService.getItems(blog.getUrl());
for (Item item : items) {
Item saveItem = itemRepository.findByBlogAndLink(blog, item.getLink());
if (saveItem == null) {
item.setBlog(blog);
itemRepository.save(item);
}
}
} catch (RssException e) {
e.printStackTrace();
}
}
/*
//1 hour
@Scheduled(fixedDelay = 3600000)
public void reloadBlog() {
List<Blog> blogs = blogRepository.findAll();
for (Blog blog : blogs) {
saveItems(blog);
}
}*/
public void save(Blog blog, String name) {
User user = userRepository.findByName(name);
blog.setUser(user);
blogRepository.save(blog);
saveItems(blog);
}
@PreAuthorize("#blog.user.name==authentication.name or hasRole('ROLE_ADMIN')")
public void delete(@P("blog") Blog blog) {
blogRepository.delete(blog);
}
public Blog findOne(int id) {
return blogRepository.findOne(id);
}
}
|
package com.celements.navigation;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.model.reference.DocumentReference;
import com.celements.common.classes.IClassCollectionRole;
import com.celements.web.service.IWebUtilsService;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.web.Utils;
public class NavigationApi extends Api {
private static Log LOGGER = LogFactory.getFactory().getInstance(NavigationApi.class);
private INavigation navigation;
private NavigationApi(INavigation navigation, XWikiContext context) {
super(context);
this.navigation = navigation;
}
public static NavigationApi getAPIObject(INavigation navigation,
XWikiContext context) {
return new NavigationApi(navigation, context);
}
public static NavigationApi createNavigation(XWikiContext context) {
return getAPIObject(new Navigation(Navigation.newNavIdForContext(context)),
context);
}
public String getMultilingualMenuName(String fullName, String language) {
return navigation.getMenuNameCmd().getMultilingualMenuName(fullName, language,
context);
}
public String getMultilingualMenuName(com.xpn.xwiki.api.Object menuItem,
String language) {
return navigation.getMenuNameCmd().getMultilingualMenuName(menuItem, language,
context);
}
public String getMultilingualMenuName(com.xpn.xwiki.api.Object menuItem,
String language, boolean allowEmptyMenuNames) {
return navigation.getMenuNameCmd().getMultilingualMenuName(menuItem.getXWikiObject(),
language, allowEmptyMenuNames, context);
}
public String getMultilingualMenuNameOnly(String fullName, String language) {
return navigation.getMenuNameCmd().getMultilingualMenuNameOnly(fullName, language,
true, context);
}
public String getMultilingualMenuNameOnly(String fullName, String language,
boolean allowEmptyMenuNames) {
return navigation.getMenuNameCmd().getMultilingualMenuNameOnly(fullName, language,
allowEmptyMenuNames, context);
}
public String includeNavigation() {
return navigation.includeNavigation(context);
}
public int getMenuItemPos(String fullName) {
return navigation.getMenuItemPos(fullName, context);
}
public int getActiveMenuItemPos(int menuLevel) {
return navigation.getActiveMenuItemPos(menuLevel, context);
}
public List<com.xpn.xwiki.api.Object> getMenuItemsForHierarchyLevel(
int menuLevel) {
return navigation.getMenuItemsForHierarchyLevel(menuLevel, context);
}
public void setFromHierarchyLevel(int fromHierarchyLevel) {
navigation.setFromHierarchyLevel(fromHierarchyLevel);
}
public void setToHierarchyLevel(int toHierarchyLevel) {
navigation.setToHierarchyLevel(toHierarchyLevel);
}
public void setMenuPart(String menuPart) {
navigation.setMenuPart(menuPart);
}
public void setMenuSpace(String menuSpace) {
navigation.setMenuSpace(menuSpace);
}
public String getPrevMenuItemFullName(com.xpn.xwiki.api.Object menuItem) {
return navigation.getPrevMenuItemFullName(menuItem.getName(), context);
}
public String getNextMenuItemFullName(com.xpn.xwiki.api.Object menuItem) {
return navigation.getNextMenuItemFullName(menuItem.getName(), context);
}
public boolean isNavigationEnabled() {
return navigation.isNavigationEnabled();
}
private DocumentReference getNavigationConfigClassRef(XWikiDocument doc) {
return getNavigationClasses().getNavigationConfigClassRef(getWebUtilsService(
).getWikiRef(doc.getDocumentReference()).getName());
}
public void loadConfigByName(String configName) {
navigation.loadConfigByName(configName, context);
}
/**
* @deprecated since 2.18.0 instead use loadConfigFromDoc(DocumentReference)
*/
@Deprecated
public void loadConfigFromDoc(String fullName) {
DocumentReference configDocRef = getWebUtilsService().resolveDocumentReference(
fullName);
loadConfig_internal(configDocRef, null);
}
/**
* @deprecated since 2.18.0 instead use loadConfigFromDoc(DocumentReference, int)
*/
@Deprecated
public void loadConfigFromDoc(String fullName, int objNum) {
DocumentReference configDocRef = getWebUtilsService().resolveDocumentReference(
fullName);
loadConfig_internal(configDocRef, objNum);
}
public void loadConfigFromDoc(DocumentReference configDocRef) {
loadConfig_internal(configDocRef, null);
}
public void loadConfigFromDoc(DocumentReference configDocRef, int objNum) {
loadConfig_internal(configDocRef, objNum);
}
private void loadConfig_internal(DocumentReference configDocRef, Integer objNum) {
try {
XWikiDocument doc = context.getWiki().getDocument(configDocRef, context);
BaseObject navConfigXobj = getNavigationConfigObject(doc, objNum);
if (navConfigXobj != null) {
LOGGER.debug("loadConfig_internal: configName [" + navConfigXobj.getStringValue(
"menu_element_name") + "] , " + navConfigXobj);
navigation.loadConfigFromObject(navConfigXobj);
}
} catch (XWikiException exp) {
LOGGER.warn("failed to get document [" + configDocRef + "].");
}
}
private BaseObject getNavigationConfigObject(XWikiDocument doc, Integer objNum) {
BaseObject navConfigXobj;
if (objNum == null) {
navConfigXobj = doc.getXObject(getNavigationConfigClassRef(doc));
} else {
navConfigXobj = doc.getXObject(getNavigationConfigClassRef(doc), objNum);
}
return navConfigXobj;
}
public void setCMcssClass(String cmCssClass) {
navigation.setCMcssClass(cmCssClass);
}
public String getMenuSpace() {
return navigation.getMenuSpace(context);
}
public String getUniqueId(String menuItemName) {
return navigation.getUniqueId(menuItemName);
}
public void setShowAll(boolean showAll) {
navigation.setShowAll(showAll);
}
public void setHasLink(boolean hasLink) {
navigation.setHasLink(hasLink);
}
public void addUlCSSClass(String cssClass) {
navigation.addUlCSSClass(cssClass);
}
public void setLanguage(String language) {
navigation.setLanguage(language);
}
public void setShowInactiveToLevel(int showInactiveToLevel) {
navigation.setShowInactiveToLevel(showInactiveToLevel);
}
private IWebUtilsService getWebUtilsService() {
return Utils.getComponent(IWebUtilsService.class);
}
private NavigationClasses getNavigationClasses() {
return (NavigationClasses) Utils.getComponent(IClassCollectionRole.class,
"celements.celNavigationClasses");
}
}
|
package com.clinichelper.Service;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
@Service
public class AmazonService {
private static String bucketName = System.getenv("AWS_BUCKET_NAME");
private static String keyName = System.getenv("AWS_BUCKET_KEY");
public void UploadImageToAWS(String uploadFileName,File file) {
file.renameTo(new File(uploadFileName));
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
try {
System.out.println("Uploading a new object to S3 from a file\n");
s3client.putObject(new PutObjectRequest(
bucketName, keyName, file));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
|
package com.codeborne.selenide;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.internal.Killable;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import static com.codeborne.selenide.Configuration.*;
import static java.io.File.separatorChar;
import static org.openqa.selenium.OutputType.FILE;
import static org.openqa.selenium.ie.InternetExplorerDriver.INITIAL_BROWSER_URL;
public class WebDriverRunner {
public static final String CHROME = "chrome";
public static final String INTERNET_EXPLORER = "ie";
public static final String FIREFOX = "firefox";
/**
* To use HtmlUnitDriver, you need to include extra dependency to your project:
* <dependency org="org.seleniumhq.selenium" name="selenium-htmlunit-driver" rev="2.33.0" conf="test->default"/>
*
* It's also possible to run HtmlUnit driver emulating different browsers:
* <p>
* java -Dbrowser=htmlunit:firefox
* </p>
* <p>
* java -Dbrowser=htmlunit:chrome
* </p>
* <p>
* java -Dbrowser=htmlunit:internet explorer (default)
* </p>
* etc.
*/
public static final String HTMLUNIT = "htmlunit";
/**
* To use OperaDriver, you need to include extra dependency to your project:
* <dependency org="com.github.detro.ghostdriver" name="phantomjsdriver" rev="1.+" conf="test->default"/>
*/
public static final String PHANTOMJS = "phantomjs";
/**
* To use OperaDriver, you need to include extra dependency to your project:
* <dependency org="com.opera" name="operadriver" rev="0.18" conf="test->default"/>
*/
public static final String OPERA = "opera";
private static WebDriver webdriver;
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
closeWebDriver();
}
});
}
/**
* Tell Selenide use your provided WebDriver instance.
* Use it if you need a custom logic for creating WebDriver.
*
* It's recommended not to use implicit wait with this driver, because Selenide handles timing issues explicitly.
*
* <p/>
* <p/>
*
* NB! Be sure to call this method before calling <code>open(url)</code>.
* Otherwise Selenide will create its own WebDriver instance and would not close it.
*
* <p/>
* <p/>
* P.S. Alternatively, you can run tests with system property
* <pre> -Dbrowser=com.my.WebDriverFactory</pre>
*
* which should implement interface com.codeborne.selenide.WebDriverProvider
*/
public static void setWebDriver(WebDriver webDriver) {
webdriver = webDriver;
}
/**
* Get the underlying instance of Selenium WebDriver.
* This can be used for any operations directly with WebDriver.
*/
public static WebDriver getWebDriver() {
if (webdriver == null) {
webdriver = createDriver();
}
return webdriver;
}
public static void closeWebDriver() {
if (webdriver != null) {
if (!holdBrowserOpen) {
try {
webdriver.quit();
} catch (WebDriverException cannotCloseBrowser) {
System.err.println("Cannot close browser normally: " + cleanupWebDriverExceptionMessage(cannotCloseBrowser));
}
finally {
killBrowser();
}
}
webdriver = null;
}
}
static void killBrowser() {
if (webdriver instanceof Killable) {
try {
((Killable) webdriver).kill();
} catch (Exception e) {
System.err.println("Failed to kill browser " + webdriver + ':');
e.printStackTrace();
}
}
}
public static boolean ie() {
return INTERNET_EXPLORER.equalsIgnoreCase(browser);
}
public static boolean htmlUnit() {
return browser != null && browser.startsWith(HTMLUNIT);
}
public static boolean phantomjs() {
return PHANTOMJS.equalsIgnoreCase(browser);
}
public static void clearBrowserCache() {
if (webdriver != null) {
webdriver.manage().deleteAllCookies();
}
}
public static String source() {
return getWebDriver().getPageSource();
}
public static String url() {
return getWebDriver().getCurrentUrl();
}
public static String takeScreenShot(String className, String methodName) {
return takeScreenShot(getScreenshotFileName(className, methodName));
}
static String getScreenshotFileName(String className, String methodName) {
return className.replace('.', separatorChar) + separatorChar + methodName;
}
public static String takeScreenShot(String fileName) {
if (webdriver == null) {
System.err.println("Cannot take screenshot because browser is not started");
return null;
}
File targetFile = new File(reportsFolder, fileName + ".html");
try {
writeToFile(webdriver.getPageSource(), targetFile);
} catch (Exception e) {
System.err.println(e);
}
if (webdriver instanceof TakesScreenshot) {
targetFile = takeScreenshotImage((TakesScreenshot) webdriver, fileName, targetFile);
}
else if (webdriver instanceof RemoteWebDriver) {
WebDriver remoteDriver = new Augmenter().augment(webdriver);
if (webdriver instanceof TakesScreenshot) {
targetFile = takeScreenshotImage((TakesScreenshot) remoteDriver, fileName, targetFile);
}
}
return targetFile.getAbsolutePath();
}
private static File takeScreenshotImage(TakesScreenshot driver, String fileName, final File targetFile) {
try {
File scrFile = driver.getScreenshotAs(FILE);
File imageFile = new File(reportsFolder, fileName + ".png");
copyFile(scrFile, imageFile);
return imageFile;
} catch (Exception e) {
System.err.println(e);
}
return targetFile;
}
private static void copyFile(File sourceFile, File targetFile) throws IOException {
copyFile(new FileInputStream(sourceFile), targetFile);
}
private static void copyFile(InputStream in, File targetFile) throws IOException {
ensureFolderExists(targetFile);
byte[] buffer = new byte[1024];
int len;
try {
final FileOutputStream out = new FileOutputStream(targetFile);
try {
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
private static void writeToFile(String content, File targetFile) throws IOException {
copyFile(new ByteArrayInputStream(content.getBytes()), targetFile);
}
private static File ensureFolderExists(File targetFile) {
File folder = targetFile.getParentFile();
if (!folder.exists()) {
System.err.println("Creating folder: " + folder);
if (!folder.mkdirs()) {
System.err.println("Failed to create " + folder);
}
}
return targetFile;
}
private static WebDriver createDriver() {
if (remote != null) {
return createRemoteDriver(remote, browser);
}
else if (CHROME.equalsIgnoreCase(browser)) {
ChromeOptions options = new ChromeOptions();
if (startMaximized) {
// Due do bug in ChromeDriver we need this workaround
options.addArguments("chrome.switches", "--start-maximized");
}
return new ChromeDriver(options);
}
else if (ie()) {
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(INITIAL_BROWSER_URL, baseUrl);
return maximize(new InternetExplorerDriver(ieCapabilities));
}
else if (htmlUnit()) {
DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setCapability(HtmlUnitDriver.INVALIDSELECTIONERROR, true);
capabilities.setCapability(HtmlUnitDriver.INVALIDXPATHERROR, false);
capabilities.setJavascriptEnabled(true);
if (browser.indexOf(':') > -1) {
// Use constants BrowserType.IE, BrowserType.FIREFOX, BrowserType.CHROME etc.
String emulatedBrowser = browser.replaceFirst("htmlunit:(.*)", "$1");
capabilities.setVersion(emulatedBrowser);
}
return new HtmlUnitDriver(capabilities);
}
else if (FIREFOX.equalsIgnoreCase(browser)) {
return maximize(new FirefoxDriver());
}
else if (OPERA.equalsIgnoreCase(browser)) {
return createInstanceOf("com.opera.core.systems.OperaDriver");
}
else if (PHANTOMJS.equals(browser)) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("takesScreenshot", true);
return new org.openqa.selenium.phantomjs.PhantomJSDriver(capabilities);
}
else {
return createInstanceOf(browser);
}
}
private static RemoteWebDriver maximize(RemoteWebDriver driver) {
if (startMaximized) {
driver.manage().window().maximize();
}
return driver;
}
private static WebDriver createInstanceOf(String className) {
try {
Class<?> clazz = Class.forName(className);
if (WebDriverProvider.class.isAssignableFrom(clazz)) {
return ((WebDriverProvider)clazz.newInstance()).createDriver();
} else {
return (WebDriver) Class.forName(className).newInstance();
}
}
catch (Exception invalidClassName) {
throw new IllegalArgumentException(invalidClassName);
}
}
private static WebDriver createRemoteDriver(String remote, String browser) {
try {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(browser);
return new RemoteWebDriver(new URL(remote), capabilities);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Invalid 'remote' parameter: " + remote, e);
}
}
public static String cleanupWebDriverExceptionMessage(WebDriverException webDriverException) {
return cleanupWebDriverExceptionMessage(webDriverException.toString());
}
static String cleanupWebDriverExceptionMessage(String webDriverExceptionInfo) {
return webDriverExceptionInfo == null || webDriverExceptionInfo.indexOf('\n') == -1 ?
webDriverExceptionInfo :
webDriverExceptionInfo
.substring(0, webDriverExceptionInfo.indexOf('\n'))
.replaceFirst("(.*)\\(WARNING: The server did not provide any stacktrace.*", "$1")
.replaceFirst("org\\.openqa\\.selenium\\.(.*)", "$1")
.trim();
}
}
|
package com.touwolf.mailchimp.model.list;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.touwolf.mailchimp.MailchimpException;
import com.touwolf.mailchimp.impl.MailchimpBuilder;
import com.touwolf.mailchimp.impl.MailchimpUtils;
import com.touwolf.mailchimp.model.MailchimpResponse;
import com.touwolf.mailchimp.model.list.data.interestcategories.ListsInterestCategoriesReadRequest;
import com.touwolf.mailchimp.model.list.data.interestcategories.ListsInterestCategoriesReadResponse;
import com.touwolf.mailchimp.model.list.data.interestcategories.ListsInterestCategoriesRequest;
import com.touwolf.mailchimp.model.list.data.interestcategories.ListsInterestCategoriesResponse;
import org.apache.commons.lang.StringUtils;
import org.bridje.ioc.Component;
@Component
public class ListsInterestCategories
{
private final Gson GSON = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
private MailchimpBuilder builder;
public ListsInterestCategories builder(MailchimpBuilder builder)
{
this.builder = builder;
return this;
}
/**
* Create a new interest category
*
* @param listId The unique id for the list.
* @param request Request body parameters
*
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> create(String listId, ListsInterestCategoriesRequest request) throws MailchimpException
{
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
String url = "/lists/" + listId + "/interest-categories";
String payload = GSON.toJson(request);
return builder.post(url, payload, ListsInterestCategoriesResponse.class);
}
public MailchimpResponse<ListsInterestCategoriesReadResponse> read(String listId, ListsInterestCategoriesReadRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
String url = "/lists/" + listId + "/interest-categories";
url = MailchimpUtils.formatQueryString(url, "fields", request.getFields());
url = MailchimpUtils.formatQueryString(url, "exclude_fields", request.getExcludeFields());
url = MailchimpUtils.formatQueryString(url, "count", request.getCount());
url = MailchimpUtils.formatQueryString(url, "offset", request.getOffset());
url = MailchimpUtils.formatQueryString(url, "type", request.getType());
return builder.get(url, ListsInterestCategoriesReadResponse.class);
}
/**
* Get information about a specific interest category.
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param fields A comma-separated list of fields to return. Reference parameters of sub-objects with dot notation.
* @param excludeFields A comma-separated list of fields to exclude. Reference parameters of sub-objects with dot notation.
*
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> read(String listId, String interestCategoryId, String fields, String excludeFields) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
url = MailchimpUtils.formatQueryString(url, "fields", fields);
url = MailchimpUtils.formatQueryString(url, "exclude_fields", excludeFields);
return builder.get(url, ListsInterestCategoriesResponse.class);
}
/**
* Update a specific interest category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param request Request body parameters
*
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> edit(String listId, String interestCategoryId, ListsInterestCategoriesRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
String payload = GSON.toJson(request);
return builder.patch(url, payload, ListsInterestCategoriesResponse.class);
}
/**
* Delete a specific interest category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
*
* @throws MailchimpException
*/
public MailchimpResponse<Void> delete(String listId, String interestCategoryId) throws MailchimpException
{
if(StringUtils.isBlank(listId))
{
throw new MailchimpException("The field campaign_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
return builder.delete(url, Void.class);
}
}
|
package com.xtremelabs.robolectric.res;
import java.util.ArrayList;
import java.util.List;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
import com.xtremelabs.robolectric.RobolectricConfig;
import com.xtremelabs.robolectric.tester.android.content.pm.StubPackageManager;
public class RobolectricPackageManager extends StubPackageManager {
public PackageInfo packageInfo;
public ArrayList<PackageInfo> packageList;
private List<ResolveInfo> resolveList;
private ContextWrapper contextWrapper;
private RobolectricConfig config;
private ApplicationInfo applicationInfo;
public RobolectricPackageManager(ContextWrapper contextWrapper, RobolectricConfig config) {
this.contextWrapper = contextWrapper;
this.config = config;
}
@Override
public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException {
ensurePackageInfo();
return packageInfo;
}
@Override
public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException {
if (config.getPackageName().equals(packageName)) {
if (applicationInfo == null) {
applicationInfo = new ApplicationInfo();
applicationInfo.flags = config.getApplicationFlags();
applicationInfo.targetSdkVersion = config.getSdkVersion();
applicationInfo.packageName = config.getPackageName();
applicationInfo.processName = config.getProcessName();
}
return applicationInfo;
}
throw new NameNotFoundException();
}
@Override
public List<PackageInfo> getInstalledPackages(int flags) {
ensurePackageInfo();
if (packageList == null) {
packageList = new ArrayList<PackageInfo>();
packageList.add(packageInfo);
}
return packageList;
}
@Override
public List<ResolveInfo> queryIntentActivities( Intent intent, int flags ) {
if( resolveList == null ) {
resolveList = new ArrayList<ResolveInfo>();
}
return resolveList;
}
private void ensurePackageInfo() {
if (packageInfo == null) {
packageInfo = new PackageInfo();
packageInfo.packageName = contextWrapper.getPackageName();
packageInfo.versionName = "1.0";
}
}
}
|
package com.demigodsrpg.game.model;
import com.demigodsrpg.game.DGGame;
import com.demigodsrpg.game.Setting;
import com.demigodsrpg.game.ability.AbilityMetaData;
import com.demigodsrpg.game.aspect.Aspect;
import com.demigodsrpg.game.aspect.Aspects;
import com.demigodsrpg.game.battle.BattleMetaData;
import com.demigodsrpg.game.battle.Participant;
import com.demigodsrpg.game.deity.Deity;
import com.demigodsrpg.game.deity.Faction;
import com.demigodsrpg.game.util.JsonSection;
import com.demigodsrpg.game.util.ZoneUtil;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.map.hash.TIntDoubleHashMap;
import org.bukkit.*;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class PlayerModel extends AbstractPersistentModel<String> implements Participant {
private final String mojangId;
private String lastKnownName;
// -- PARENTS -- //
private Deity god;
private Deity hero;
private final List<String> aspects = new ArrayList<>(1);
private Faction faction;
private final BiMap<String, String> binds = HashBiMap.create();
private final TIntDoubleHashMap experience;
private long lastLoginTime;
private double maxHealth;
private double favor;
private int level;
private boolean canPvp;
private int kills;
private int deaths;
private int teamKills;
@SuppressWarnings("deprecation")
public PlayerModel(Player player) {
mojangId = player.getUniqueId().toString();
lastKnownName = player.getName();
lastLoginTime = System.currentTimeMillis();
experience = new TIntDoubleHashMap(1);
god = Deity.LOREM;
hero = Deity.IPSUM;
faction = Faction.NEUTRAL;
maxHealth = 20.0;
favor = 700.0;
level = 0;
canPvp = true;
kills = 0;
deaths = 0;
teamKills = 0;
}
public PlayerModel(String mojangId, JsonSection conf) {
this.mojangId = mojangId;
lastKnownName = conf.getString("last_known_name");
lastLoginTime = conf.getLong("last_login_time");
aspects.addAll(conf.getStringList("aspects").stream().collect(Collectors.toList()));
god = DGGame.DEITY_R.deityFromName(conf.getString("god"));
hero = DGGame.DEITY_R.deityFromName(conf.getString("hero"));
faction = DGGame.FACTION_R.factionFromName(conf.getString("faction"));
binds.putAll((Map) conf.getSection("binds").getValues());
maxHealth = conf.getDouble("max_health");
favor = conf.getDouble("favor");
experience = new TIntDoubleHashMap(1);
for (Map.Entry<String, Object> entry : conf.getSection("devotion").getValues().entrySet()) {
try {
experience.put(Aspects.valueOf(entry.getKey()).getId(), Double.valueOf(entry.getValue().toString()));
} catch (Exception ignored) {
}
}
level = conf.getInt("level");
canPvp = conf.getBoolean("can_pvp", true);
kills = conf.getInt("kills");
deaths = conf.getInt("deaths");
teamKills = conf.getInt("team_kills");
}
@Override
public Type getType() {
return Type.PERSISTENT;
}
@Override
public String getPersistentId() {
return mojangId;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = new HashMap<>();
map.put("last_known_name", lastKnownName);
map.put("last_login_time", lastLoginTime);
map.put("aspects", Lists.newArrayList(aspects));
map.put("god", god.getName());
map.put("hero", hero.getName());
map.put("faction", faction.getName());
map.put("binds", binds);
map.put("max_health", maxHealth);
map.put("favor", favor);
Map<Integer, Double> devotionMap = new HashMap<>();
TIntIterator iterator = experience.keySet().iterator();
while (iterator.hasNext()) {
int key = iterator.next();
try {
devotionMap.put(key, experience.get(key));
} catch (Exception ignored) {
}
}
map.put("devotion", devotionMap);
map.put("level", level);
map.put("can_pvp", canPvp);
map.put("kills", kills);
map.put("deaths", deaths);
map.put("team_kills", teamKills);
return map;
}
public String getMojangId() {
return mojangId;
}
public String getLastKnownName() {
return lastKnownName;
}
public void setLastKnownName(String lastKnownName) {
this.lastKnownName = lastKnownName;
DGGame.PLAYER_R.register(this);
}
public long getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Long lastLoginTime) {
this.lastLoginTime = lastLoginTime;
DGGame.PLAYER_R.register(this);
}
public List<String> getAspects() {
return aspects;
}
public void addAspect(Aspect aspect) {
aspects.add(getAspectName(aspect));
DGGame.PLAYER_R.register(this);
}
public void removeAspect(Aspect aspect) {
aspects.remove(getAspectName(aspect));
DGGame.PLAYER_R.register(this);
}
@Override
public Faction getFaction() {
return faction;
}
public void setFaction(Faction faction) {
this.faction = faction;
DGGame.PLAYER_R.register(this);
}
public Deity getGod() {
return god;
}
public Deity getHero() {
return hero;
}
public boolean hasDeity(Deity deity) {
return deity.equals(god) || deity.equals(hero);
}
double getMaxHealth() {
return maxHealth;
}
void setMaxHealth(Double maxHealth) {
this.maxHealth = maxHealth;
DGGame.PLAYER_R.register(this);
}
public double getFavor() {
return favor;
}
public void setFavor(Double favor) {
this.favor = favor;
DGGame.PLAYER_R.register(this);
}
public double getExperience(Aspect aspect) {
if (!experience.containsKey(aspect.getId())) {
return 0.0;
}
return experience.get(aspect.getId());
}
double getExperience(String aspectName) {
int ordinal = Aspects.valueOf(aspectName).getId();
if (!experience.containsKey(ordinal)) {
return 0.0;
}
return experience.get(ordinal);
}
public Double getTotalExperience() {
double total = 0.0;
for (String aspect : aspects) {
total += getExperience(aspect);
}
return total;
}
public void setExperience(Aspect aspect, double experience) {
this.experience.put(aspect.getId(), experience);
calculateAscensions();
DGGame.PLAYER_R.register(this);
}
void setExperience(String aspectName, double experience) {
int ordinal = Aspects.valueOf(aspectName).getId();
this.experience.put(ordinal, experience);
calculateAscensions();
DGGame.PLAYER_R.register(this);
}
public int getLevel() {
return level;
}
void setLevel(int level) {
this.level = level;
DGGame.PLAYER_R.register(this);
}
public Map<String, String> getBindsMap() {
return binds;
}
public AbilityMetaData getBound(Material material) {
if (binds.inverse().containsKey(material.name())) {
return DGGame.ABILITY_R.fromCommand(binds.inverse().get(material.name()));
}
return null;
}
public Material getBound(AbilityMetaData ability) {
return getBound(ability.getCommand());
}
Material getBound(String abilityCommand) {
if (binds.containsKey(abilityCommand)) {
return Material.valueOf(binds.get(abilityCommand));
}
return null;
}
public void bind(AbilityMetaData ability, Material material) {
binds.put(ability.getCommand(), material.name());
DGGame.PLAYER_R.register(this);
}
public void bind(String abilityCommand, Material material) {
binds.put(abilityCommand, material.name());
DGGame.PLAYER_R.register(this);
}
public void unbind(AbilityMetaData ability) {
binds.remove(ability.getCommand());
DGGame.PLAYER_R.register(this);
}
public void unbind(String abilityCommand) {
binds.remove(abilityCommand);
DGGame.PLAYER_R.register(this);
}
public void unbind(Material material) {
binds.inverse().remove(material.name());
DGGame.PLAYER_R.register(this);
}
public boolean getCanPvp() {
return canPvp;
}
void setCanPvp(Boolean canPvp) {
this.canPvp = canPvp;
DGGame.PLAYER_R.register(this);
}
public int getKills() {
return kills;
}
public void addKill() {
kills++;
DGGame.PLAYER_R.register(this);
}
public int getDeaths() {
return deaths;
}
public void addDeath() {
deaths++;
DGGame.PLAYER_R.register(this);
}
public int getTeamKills() {
return teamKills;
}
public void addTeamKill() {
teamKills++;
DGGame.PLAYER_R.register(this);
}
void resetTeamKills() {
teamKills = 0;
DGGame.PLAYER_R.register(this);
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(UUID.fromString(mojangId));
}
public boolean getOnline() {
return getOfflinePlayer().isOnline();
}
@Override
public EntityType getEntityType() {
return EntityType.PLAYER;
}
@Override
public Location getLocation() {
if (getOnline()) {
return getOfflinePlayer().getPlayer().getLocation();
}
throw new UnsupportedOperationException("We don't support finding locations for players who aren't online.");
}
public boolean isDemigod() {
return hero != null && god != null;
}
public boolean hasAspect(Aspect aspect) {
return getAspects().contains(getAspectName(aspect));
}
@SuppressWarnings("RedundantCast")
@Override
public boolean reward(BattleMetaData data) {
double experience = getTotalExperience();
teamKills += data.getTeamKills();
if (checkTeamKills()) {
double score = data.getHits() + data.getAssists() / 2;
score += data.getDenies();
score += data.getKills() * 2;
score -= data.getDeaths() * 1.5;
score *= (double) Setting.EXP_MULTIPLIER.get();
score /= aspects.size() + 1;
for (String aspect : aspects) {
setExperience(aspect, getExperience(aspect) + score);
}
}
DGGame.PLAYER_R.register(this);
return experience > getTotalExperience();
}
boolean checkTeamKills() {
int maxTeamKills = Setting.MAX_TEAM_KILLS.get();
if (maxTeamKills <= teamKills) {
// Reset them to excommunicated
setFaction(Faction.EXCOMMUNICATED);
resetTeamKills();
double former = getTotalExperience();
if (getOnline()) {
Player player = getOfflinePlayer().getPlayer();
player.sendMessage(ChatColor.RED + "Your former faction has just excommunicated you.");
player.sendMessage(ChatColor.RED + "You will no longer respawn at the faction spawn.");
player.sendMessage(ChatColor.RED + "You have lost " +
ChatColor.GOLD + DecimalFormat.getCurrencyInstance().format(former - getTotalExperience()) +
ChatColor.RED + " experience.");
player.sendMessage(ChatColor.YELLOW + "To join a faction, "); // TODO
}
return false;
}
return true;
}
public void giveFirstAspect(Deity hero, Aspect aspect) {
giveAspect(aspect);
setFaction(hero.getFaction());
setMaxHealth(25.0);
setLevel(1);
setExperience(aspect, 20.0);
calculateAscensions();
}
public void giveAspect(Aspect aspect) {
aspects.add(getAspectName(aspect));
setExperience(aspect, 20.0);
}
public boolean canClaim(Aspect aspect) {
if (faction.equals(Faction.NEUTRAL)) {
return !hasAspect(aspect);
}
if (Setting.NO_ALLIANCE_ASPECT_MODE.get()) {
return costForNextDeity() <= level && !hasAspect(aspect);
}
// TODO Decide how to check if they can claim an aspect.
return costForNextDeity() <= level && !hasAspect(aspect);
}
void calculateAscensions() {
Player player = getOfflinePlayer().getPlayer();
if (getLevel() >= (int) Setting.ASCENSION_CAP.get()) return;
while (getTotalExperience() >= (int) Math.ceil(500 * Math.pow(getLevel() + 1, 2.02)) && getLevel() < (int) Setting.ASCENSION_CAP.get()) {
setMaxHealth(getMaxHealth() + 10.0);
player.setMaxHealth(getMaxHealth());
player.setHealthScale(20.0);
player.setHealthScaled(true);
player.setHealth(getMaxHealth());
setLevel(getLevel() + 1);
player.sendMessage(ChatColor.AQUA + "Congratulations! Your Ascensions increased to " + getLevel() + ".");
player.sendMessage(ChatColor.YELLOW + "Your maximum HP has increased to " + getMaxHealth() + ".");
}
DGGame.PLAYER_R.register(this);
}
public int costForNextDeity() {
if (Setting.NO_COST_ASPECT_MODE.get()) return 0;
switch (aspects.size() + 1) {
case 1:
return 2;
case 2:
return 5;
case 3:
return 9;
case 4:
return 14;
case 5:
return 19;
case 6:
return 25;
case 7:
return 30;
case 8:
return 35;
case 9:
return 40;
case 10:
return 50;
case 11:
return 60;
case 12:
return 70;
case 13:
return 80;
}
return 120;
}
@SuppressWarnings("deprecation")
public void updateCanPvp() {
if (Bukkit.getPlayer(mojangId) == null) return;
// Define variables
final Player player = Bukkit.getPlayer(mojangId);
final boolean inNoPvpZone = ZoneUtil.inNoPvpZone(player.getLocation());
if (DGGame.BATTLE_R.isInBattle(this)) return;
if (!getCanPvp() && !inNoPvpZone) {
setCanPvp(true);
player.sendMessage(ChatColor.GRAY + "You can now enter in a battle.");
} else if (!inNoPvpZone) {
setCanPvp(true);
DGGame.SERVER_R.remove(player.getName(), "pvp_cooldown");
} else if (getCanPvp() && !DGGame.SERVER_R.contains(player.getName(), "pvp_cooldown")) {
int delay = 10;
DGGame.SERVER_R.put(player.getName(), "pvp_cooldown", true, delay, TimeUnit.SECONDS);
final PlayerModel THIS = this;
Bukkit.getScheduler().scheduleSyncDelayedTask(DGGame.getInst(), new BukkitRunnable() {
@Override
public void run() {
if (ZoneUtil.inNoPvpZone(player.getLocation())) {
if (DGGame.BATTLE_R.isInBattle(THIS)) return;
setCanPvp(false);
player.sendMessage(ChatColor.GRAY + "You are now safe from other players.");
}
}
}, (delay * 20));
}
}
private String getAspectName(Aspect aspect) {
return aspect.getGroup() + " " + aspect.getTier().name();
}
}
|
package eu.amidst.core.modelstructure.statics.impl;
import eu.amidst.core.header.Variable;
import eu.amidst.core.modelstructure.ParentSet;
import java.util.ArrayList;
import java.util.List;
public class ParentSetImpl implements ParentSet {
private ArrayList<Variable> vars;
public void addParent(Variable variable){
vars.add(variable);
}
public void removeParent(Variable variable){
vars.remove(variable);
}
@Override
public List<Variable> getParents(){
ArrayList<Variable> parents;
parents = new ArrayList<Variable>();
for (int i=0;i<vars.size();i++) parents.add(vars.get(i));
return parents;
}
public int getNumberOfParents(){
return vars.size();
}
}
|
package com.devproserv.courses.model;
import com.devproserv.courses.jooq.tables.Users;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Supplier;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controls user in accordance to their role.
*
* @since 0.5.0
*/
public class UserRoles {
/**
* Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(UserRoles.class);
/**
* Database.
*/
private final Db dbase;
/**
* Login.
*/
private final String login;
/**
* Password.
*/
private final String pass;
/**
* Enum Roles.
*/
private enum UserRole {
/**
* Student role.
*/
STUD,
/**
* Lecturer role.
*/
LECT,
/**
* Administrator role.
*/
ADMIN
}
/**
* Roles.
*/
private final Map<UserRole, Supplier<Nest>> roles;
/**
* Constructor.
*
* @param login Login
* @param pass Password
*/
public UserRoles(final String login, final String pass) {
this(new Db(), login, pass);
}
/**
* Primary constructor.
*
* @param dbase Database
* @param login Login
* @param pass Password
*/
UserRoles(final Db dbase, final String login, final String pass) {
this.dbase = dbase;
this.login = login;
this.pass = pass;
this.roles = new EnumMap<>(UserRole.class);
}
/**
* Builder.
* @return This instance
*/
public UserRoles build() {
this.roles.put(UserRole.STUD, () -> new NestStudents(this.dbase, this.login, this.pass));
this.roles.put(UserRole.LECT, NestLecturers::new);
this.roles.put(UserRole.ADMIN, NestAdmins::new);
return this;
}
/**
* Defines the path.
*
* @param request HTTP request
* @return Response
*/
public Response response(final HttpServletRequest request) {
final Responsible user = this.makeUser();
final Response response = user.response();
final HttpSession session = request.getSession();
session.setAttribute(session.getId(), user);
return response;
}
/**
* Returns an user instance on base of login and password.
*
* @return Responsible instance
*/
private Responsible makeUser() {
Responsible user = new EmptyUser();
try (Connection con = this.dbase.dataSource().getConnection();
DSLContext ctx = DSL.using(con, SQLDialect.MYSQL)
) {
final Result<Record> res = ctx.select().from(Users.USERS)
.where(
Users.USERS.LOGIN.eq(this.login)
.and(Users.USERS.PASSWORD.eq(this.pass))
).fetch();
user = this.fetchUser(res);
} catch (final SQLException ex) {
LOGGER.error("Fetching user failed.", ex);
}
return user;
}
/**
* Fetches user from the result set.
*
* @param res Result
* @return Responsible instance
*/
private Responsible fetchUser(final Result<Record> res) {
final Responsible user;
if (res.isNotEmpty()) {
final UserRole role = UserRole.valueOf(res.get(0).getValue(Users.USERS.ROLE).name());
final Nest nest = this.roles.get(role).get();
user = nest.makeUser();
} else {
user = new EmptyUser();
}
return user;
}
}
|
package io.mycat.backend.mysql.nio.handler;
import io.mycat.memory.unsafe.row.UnsafeRow;
import io.mycat.sqlengine.mpp.*;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import io.mycat.MycatServer;
import io.mycat.backend.BackendConnection;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.mysql.LoadDataUtil;
import io.mycat.cache.LayerCachePool;
import io.mycat.config.MycatConfig;
import io.mycat.net.mysql.*;
import io.mycat.route.RouteResultset;
import io.mycat.route.RouteResultsetNode;
import io.mycat.server.NonBlockingSession;
import io.mycat.server.ServerConnection;
import io.mycat.server.parser.ServerParse;
import io.mycat.statistic.stat.QueryResult;
import io.mycat.statistic.stat.QueryResultDispatcher;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author mycat
*/
public class MultiNodeQueryHandler extends MultiNodeHandler implements LoadDataResponseHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiNodeQueryHandler.class);
private final RouteResultset rrs;
private final NonBlockingSession session;
// private final CommitNodeHandler icHandler;
private final AbstractDataNodeMerge dataMergeSvr;
private final boolean autocommit;
private String priamaryKeyTable = null;
private int primaryKeyIndex = -1;
private int fieldCount = 0;
private final ReentrantLock lock;
private long affectedRows;
private long selectRows;
private long insertId;
private volatile boolean fieldsReturned;
private int okCount;
private final boolean isCallProcedure;
private long startTime;
private long netInBytes;
private long netOutBytes;
private int execCount = 0;
private boolean prepared;
private List<FieldPacket> fieldPackets = new ArrayList<FieldPacket>();
private int isOffHeapuseOffHeapForMerge = 1;
/**
* Limit NM
*/
private int limitStart;
private int limitSize;
private int index = 0;
private int end = 0;
public MultiNodeQueryHandler(int sqlType, RouteResultset rrs,
boolean autocommit, NonBlockingSession session) {
super(session);
if (rrs.getNodes() == null) {
throw new IllegalArgumentException("routeNode is null!");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("execute mutinode query " + rrs.getStatement());
}
this.rrs = rrs;
isOffHeapuseOffHeapForMerge = MycatServer.getInstance().
getConfig().getSystem().getUseOffHeapForMerge();
if (ServerParse.SELECT == sqlType && rrs.needMerge()) {
/**
* Off Heap
*/
if(isOffHeapuseOffHeapForMerge == 1){
dataMergeSvr = new DataNodeMergeManager(this,rrs);
}else {
dataMergeSvr = new DataMergeService(this,rrs);
}
} else {
dataMergeSvr = null;
}
isCallProcedure = rrs.isCallStatement();
this.autocommit = session.getSource().isAutocommit();
this.session = session;
this.lock = new ReentrantLock();
// this.icHandler = new CommitNodeHandler(session);
this.limitStart = rrs.getLimitStart();
this.limitSize = rrs.getLimitSize();
this.end = limitStart + rrs.getLimitSize();
if (this.limitStart < 0)
this.limitStart = 0;
if (rrs.getLimitSize() < 0)
end = Integer.MAX_VALUE;
if ((dataMergeSvr != null)
&& LOGGER.isDebugEnabled()) {
LOGGER.debug("has data merge logic ");
}
if ( rrs != null && rrs.getStatement() != null) {
netInBytes += rrs.getStatement().getBytes().length;
}
}
protected void reset(int initCount) {
super.reset(initCount);
this.okCount = initCount;
this.execCount = 0;
this.netInBytes = 0;
this.netOutBytes = 0;
}
public NonBlockingSession getSession() {
return session;
}
public void execute() throws Exception {
final ReentrantLock lock = this.lock;
lock.lock();
try {
this.reset(rrs.getNodes().length);
this.fieldsReturned = false;
this.affectedRows = 0L;
this.insertId = 0L;
} finally {
lock.unlock();
}
MycatConfig conf = MycatServer.getInstance().getConfig();
startTime = System.currentTimeMillis();
LOGGER.debug("rrs.getRunOnSlave()-" + rrs.getRunOnSlave());
for (final RouteResultsetNode node : rrs.getNodes()) {
BackendConnection conn = session.getTarget(node);
if (session.tryExistsCon(conn, node)) {
LOGGER.debug("node.getRunOnSlave()-" + node.getRunOnSlave());
node.setRunOnSlave(rrs.getRunOnSlave()); // master/slave
LOGGER.debug("node.getRunOnSlave()-" + node.getRunOnSlave());
_execute(conn, node);
} else {
// create new connection
LOGGER.debug("node.getRunOnSlave()1-" + node.getRunOnSlave());
node.setRunOnSlave(rrs.getRunOnSlave()); // master/slave
LOGGER.debug("node.getRunOnSlave()2-" + node.getRunOnSlave());
PhysicalDBNode dn = conf.getDataNodes().get(node.getName());
dn.getConnection(dn.getDatabase(), autocommit, node, this, node);
// connectionAcquired
// this
// connectionAcquired :
// session.bindConnection(node, conn);
// _execute(conn, node);
}
}
}
private void _execute(BackendConnection conn, RouteResultsetNode node) {
if (clearIfSessionClosed(session)) {
return;
}
conn.setResponseHandler(this);
try {
conn.execute(node, session.getSource(), autocommit);
} catch (IOException e) {
connectionError(e, conn);
}
}
@Override
public void connectionAcquired(final BackendConnection conn) {
final RouteResultsetNode node = (RouteResultsetNode) conn
.getAttachment();
session.bindConnection(node, conn);
_execute(conn, node);
}
private boolean decrementOkCountBy(int finished) {
lock.lock();
try {
return --okCount == 0;
} finally {
lock.unlock();
}
}
@Override
public void okResponse(byte[] data, BackendConnection conn) {
this.netOutBytes += data.length;
boolean executeResponse = conn.syncAndExcute();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("received ok response ,executeResponse:"
+ executeResponse + " from " + conn);
}
if (executeResponse) {
ServerConnection source = session.getSource();
OkPacket ok = new OkPacket();
ok.read(data);
boolean isCanClose2Client =(!rrs.isCallStatement()) ||(rrs.isCallStatement() &&!rrs.getProcedure().isResultSimpleValue());;
if(!isCallProcedure)
{
if (clearIfSessionClosed(session))
{
return;
} else if (canClose(conn, false))
{
return;
}
}
lock.lock();
try {
if (!rrs.isGlobalTable()) {
affectedRows += ok.affectedRows;
} else {
affectedRows = ok.affectedRows;
}
if (ok.insertId > 0) {
insertId = (insertId == 0) ? ok.insertId : Math.min(
insertId, ok.insertId);
}
} finally {
lock.unlock();
}
// EndRowOK
boolean isEndPacket = isCallProcedure ? decrementOkCountBy(1): decrementCountBy(1);
if (isEndPacket && isCanClose2Client) {
if (this.autocommit) {// clear all connections
session.releaseConnections(false);
}
if (this.isFail() || session.closed()) {
tryErrorFinished(true);
return;
}
lock.lock();
try {
if (rrs.isLoadData()) {
byte lastPackId = source.getLoadDataInfileHandler()
.getLastPackId();
ok.packetId = ++lastPackId;// OK_PACKET
ok.message = ("Records: " + affectedRows + " Deleted: 0 Skipped: 0 Warnings: 0")
.getBytes();
source.getLoadDataInfileHandler().clear();
} else {
ok.packetId = ++packetId;// OK_PACKET
}
ok.affectedRows = affectedRows;
ok.serverStatus = source.isAutocommit() ? 2 : 1;
if (insertId > 0) {
ok.insertId = insertId;
source.setLastInsertId(insertId);
}
ok.write(source);
} catch (Exception e) {
handleDataProcessException(e);
} finally {
lock.unlock();
}
}
}
}
@Override
public void rowEofResponse(final byte[] eof, BackendConnection conn) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("on row end reseponse " + conn);
}
this.netOutBytes += eof.length;
if (errorRepsponsed.get()) {
// the connection has been closed or set to "txInterrupt" properly
//in tryErrorFinished() method! If we close it here, it can
// lead to tx error such as blocking rollback tx for ever.
// @author Uncle-pan
// @since 2016-03-25
// conn.close(this.error);
return;
}
final ServerConnection source = session.getSource();
if (!isCallProcedure) {
if (clearIfSessionClosed(session)) {
return;
} else if (canClose(conn, false)) {
return;
}
}
if (decrementCountBy(1)) {
if (!rrs.isCallStatement()||(rrs.isCallStatement()&&rrs.getProcedure().isResultSimpleValue())) {
if (this.autocommit) {// clear all connections
session.releaseConnections(false);
}
if (this.isFail() || session.closed()) {
tryErrorFinished(true);
return;
}
}
if (dataMergeSvr != null) {
try {
dataMergeSvr.outputMergeResult(session, eof);
} catch (Exception e) {
handleDataProcessException(e);
}
} else {
try {
lock.lock();
eof[3] = ++packetId;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("last packet id:" + packetId);
}
source.write(eof);
} finally {
lock.unlock();
}
}
}
execCount++;
if (execCount == rrs.getNodes().length) {
int resultSize = source.getWriteQueue().size()*MycatServer.getInstance().getConfig().getSystem().getBufferPoolPageSize();
//TODO: add by zhuam
QueryResult queryResult = new QueryResult(session.getSource().getUser(),
rrs.getSqlType(), rrs.getStatement(), selectRows, netInBytes, netOutBytes, startTime, System.currentTimeMillis(),resultSize);
QueryResultDispatcher.dispatchQuery( queryResult );
}
}
/**
* Mycat
* @param source
* @param eof
* @param
*/
public void outputMergeResult(final ServerConnection source, final byte[] eof, Iterator<UnsafeRow> iter) {
try {
lock.lock();
ByteBuffer buffer = session.getSource().allocate();
final RouteResultset rrs = this.dataMergeSvr.getRrs();
/**
* limitstart end
* Mycat
*/
int start = rrs.getLimitStart();
int end = start + rrs.getLimitSize();
int index = 0;
if (start < 0)
start = 0;
if (rrs.getLimitSize() < 0)
end = Integer.MAX_VALUE;
while (iter.hasNext()){
UnsafeRow row = iter.next();
if(index >= start){
row.packetId = ++packetId;
buffer = row.write(buffer,source,true);
}
index++;
if(index == end){
break;
}
}
eof[3] = ++packetId;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("last packet id:" + packetId);
}
/**
* Writer Bufferchannel
*/
source.write(source.writeToBuffer(eof, buffer));
} catch (Exception e) {
handleDataProcessException(e);
} finally {
lock.unlock();
dataMergeSvr.clear();
}
}
public void outputMergeResult(final ServerConnection source,
final byte[] eof, List<RowDataPacket> results) {
try {
lock.lock();
ByteBuffer buffer = session.getSource().allocate();
final RouteResultset rrs = this.dataMergeSvr.getRrs();
// limit
int start = rrs.getLimitStart();
int end = start + rrs.getLimitSize();
if (start < 0) {
start = 0;
}
if (rrs.getLimitSize() < 0) {
end = results.size();
}
// // ,rrs.getLimitSize()
// if (rrs.getOrderByCols() == null) {
// end = results.size();
// start = 0;
if (end > results.size()) {
end = results.size();
}
for (int i = start; i < end; i++) {
RowDataPacket row = results.get(i);
if( prepared ) {
BinaryRowDataPacket binRowDataPk = new BinaryRowDataPacket();
binRowDataPk.read(fieldPackets, row);
binRowDataPk.packetId = ++packetId;
//binRowDataPk.write(source);
buffer = binRowDataPk.write(buffer, session.getSource(), true);
} else {
row.packetId = ++packetId;
buffer = row.write(buffer, source, true);
}
}
eof[3] = ++packetId;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("last packet id:" + packetId);
}
source.write(source.writeToBuffer(eof, buffer));
} catch (Exception e) {
handleDataProcessException(e);
} finally {
lock.unlock();
dataMergeSvr.clear();
}
}
@Override
public void fieldEofResponse(byte[] header, List<byte[]> fields,
byte[] eof, BackendConnection conn) {
this.netOutBytes += header.length;
this.netOutBytes += eof.length;
for (int i = 0, len = fields.size(); i < len; ++i) {
byte[] field = fields.get(i);
this.netOutBytes += field.length;
}
ServerConnection source = null;
if (fieldsReturned) {
return;
}
lock.lock();
try {
if (fieldsReturned) {
return;
}
fieldsReturned = true;
boolean needMerg = (dataMergeSvr != null)
&& dataMergeSvr.getRrs().needMerge();
Set<String> shouldRemoveAvgField = new HashSet<>();
Set<String> shouldRenameAvgField = new HashSet<>();
if (needMerg) {
Map<String, Integer> mergeColsMap = dataMergeSvr.getRrs()
.getMergeCols();
if (mergeColsMap != null) {
for (Map.Entry<String, Integer> entry : mergeColsMap
.entrySet()) {
String key = entry.getKey();
int mergeType = entry.getValue();
if (MergeCol.MERGE_AVG == mergeType
&& mergeColsMap.containsKey(key + "SUM")) {
shouldRemoveAvgField.add((key + "COUNT")
.toUpperCase());
shouldRenameAvgField.add((key + "SUM")
.toUpperCase());
}
}
}
}
source = session.getSource();
ByteBuffer buffer = source.allocate();
fieldCount = fields.size();
if (shouldRemoveAvgField.size() > 0) {
ResultSetHeaderPacket packet = new ResultSetHeaderPacket();
packet.packetId = ++packetId;
packet.fieldCount = fieldCount - shouldRemoveAvgField.size();
buffer = packet.write(buffer, source, true);
} else {
header[3] = ++packetId;
buffer = source.writeToBuffer(header, buffer);
}
String primaryKey = null;
if (rrs.hasPrimaryKeyToCache()) {
String[] items = rrs.getPrimaryKeyItems();
priamaryKeyTable = items[0];
primaryKey = items[1];
}
Map<String, ColMeta> columToIndx = new HashMap<String, ColMeta>(
fieldCount);
for (int i = 0, len = fieldCount; i < len; ++i) {
boolean shouldSkip = false;
byte[] field = fields.get(i);
if (needMerg) {
FieldPacket fieldPkg = new FieldPacket();
fieldPkg.read(field);
fieldPackets.add(fieldPkg);
String fieldName = new String(fieldPkg.name).toUpperCase();
if (columToIndx != null
&& !columToIndx.containsKey(fieldName)) {
if (shouldRemoveAvgField.contains(fieldName)) {
shouldSkip = true;
}
if (shouldRenameAvgField.contains(fieldName)) {
String newFieldName = fieldName.substring(0,
fieldName.length() - 3);
fieldPkg.name = newFieldName.getBytes();
fieldPkg.packetId = ++packetId;
shouldSkip = true;
buffer = fieldPkg.write(buffer, source, false);
}
columToIndx.put(fieldName,
new ColMeta(i, fieldPkg.type));
}
} else {
FieldPacket fieldPkg = new FieldPacket();
fieldPkg.read(field);
fieldPackets.add(fieldPkg);
fieldCount = fields.size();
if (primaryKey != null && primaryKeyIndex == -1) {
// find primary key index
String fieldName = new String(fieldPkg.name);
if (primaryKey.equalsIgnoreCase(fieldName)) {
primaryKeyIndex = i;
}
} }
if (!shouldSkip) {
field[3] = ++packetId;
buffer = source.writeToBuffer(field, buffer);
}
}
eof[3] = ++packetId;
buffer = source.writeToBuffer(eof, buffer);
source.write(buffer);
if (dataMergeSvr != null) {
dataMergeSvr.onRowMetaData(columToIndx, fieldCount);
}
} catch (Exception e) {
handleDataProcessException(e);
} finally {
lock.unlock();
}
}
public void handleDataProcessException(Exception e) {
if (!errorRepsponsed.get()) {
this.error = e.toString();
LOGGER.warn("caught exception ", e);
setFail(e.toString());
this.tryErrorFinished(true);
}
}
@Override
public void rowResponse(final byte[] row, final BackendConnection conn) {
if (errorRepsponsed.get()) {
// the connection has been closed or set to "txInterrupt" properly
//in tryErrorFinished() method! If we close it here, it can
// lead to tx error such as blocking rollback tx for ever.
// @author Uncle-pan
// @since 2016-03-25
//conn.close(error);
return;
}
lock.lock();
try {
this.selectRows++;
RouteResultsetNode rNode = (RouteResultsetNode) conn.getAttachment();
String dataNode = rNode.getName();
if (dataMergeSvr != null) {
// even through discarding the all rest data, we can't
//close the connection for tx control such as rollback or commit.
// So the "isClosedByDiscard" variable is unnecessary.
// @author Uncle-pan
// @since 2016-03-25
dataMergeSvr.onNewRecord(dataNode, row);
} else {
RowDataPacket rowDataPkg =null;
// cache primaryKey-> dataNode
if (primaryKeyIndex != -1) {
rowDataPkg = new RowDataPacket(fieldCount);
rowDataPkg.read(row);
String primaryKey = new String(rowDataPkg.fieldValues.get(primaryKeyIndex));
LayerCachePool pool = MycatServer.getInstance().getRouterservice().getTableId2DataNodeCache();
pool.putIfAbsent(priamaryKeyTable, primaryKey, dataNode);
}
row[3] = ++packetId;
if( prepared ) {
if(rowDataPkg==null) {
rowDataPkg = new RowDataPacket(fieldCount);
rowDataPkg.read(row);
}
BinaryRowDataPacket binRowDataPk = new BinaryRowDataPacket();
binRowDataPk.read(fieldPackets, rowDataPkg);
binRowDataPk.write(session.getSource());
} else {
session.getSource().write(row);
}
}
} catch (Exception e) {
handleDataProcessException(e);
} finally {
lock.unlock();
}
}
@Override
public void clearResources() {
if (dataMergeSvr != null) {
dataMergeSvr.clear();
}
}
@Override
public void writeQueueAvailable() {
}
@Override
public void requestDataResponse(byte[] data, BackendConnection conn) {
LoadDataUtil.requestFileDataResponse(data, conn);
}
public boolean isPrepared() {
return prepared;
}
public void setPrepared(boolean prepared) {
this.prepared = prepared;
}
}
|
package net.towerwarz.towers.GatlingGun;
public class GatlingGunLv3 {
public String def = "MoreBarrels";
public int
int maxDmg = 8;
int minDmg = 4;
Random rand = new Random();
public int GatlingGunLv2Dmg = rand.nextInt((maxDmg - minDmg) + 1) + minDmg;
public double GatlingGunLv2SplashRadius = 0.01;
public double GatlingGunLv2ReloadRate = 0.01;
int spreadRadius=18
}
}
|
package com.feed_the_beast.ftbcurseappbot;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.feed_the_beast.ftbcurseappbot.persistence.CacheService;
import com.feed_the_beast.ftbcurseappbot.persistence.MongoConnection;
import com.feed_the_beast.ftbcurseappbot.runnables.BBStatusChecker;
import com.feed_the_beast.ftbcurseappbot.runnables.CFStatusChecker;
import com.feed_the_beast.ftbcurseappbot.runnables.GHStatusChecker;
import com.feed_the_beast.ftbcurseappbot.runnables.McStatusChecker;
import com.feed_the_beast.ftbcurseappbot.runnables.TravisStatusChecker;
import com.feed_the_beast.ftbcurseappbot.utils.CommonMarkUtils;
import com.feed_the_beast.ftbcurseappbot.webserver.WebService;
import com.feed_the_beast.javacurselib.common.enums.DevicePlatform;
import com.feed_the_beast.javacurselib.data.Apis;
import com.feed_the_beast.javacurselib.examples.app_v1.DefaultResponseTask;
import com.feed_the_beast.javacurselib.examples.app_v1.TraceResponseTask;
import com.feed_the_beast.javacurselib.rest.RestUserEndpoints;
import com.feed_the_beast.javacurselib.service.logins.login.LoginRequest;
import com.feed_the_beast.javacurselib.service.logins.login.LoginResponse;
import com.feed_the_beast.javacurselib.service.sessions.sessions.CreateSessionRequest;
import com.feed_the_beast.javacurselib.service.sessions.sessions.CreateSessionResponse;
import com.feed_the_beast.javacurselib.utils.CurseGUID;
import com.feed_the_beast.javacurselib.websocket.WebSocket;
import com.feed_the_beast.javacurselib.websocket.messages.handler.ResponseHandler;
import com.feed_the_beast.javacurselib.websocket.messages.notifications.NotificationsServiceContractType;
import com.google.common.eventbus.EventBus;
import com.google.common.reflect.TypeToken;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import retrofit2.adapter.java8.HttpException;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
public class Main {
public static final String VERSION = "0.0.1";
public static EventBus eventBus = new EventBus();
@Getter
private static boolean debug;
@Getter
private static String username = null;
@Getter
private static Optional<String> token = Optional.empty();
@Getter
private static Optional<CreateSessionResponse> session = Optional.empty();
@Getter
private static CacheService cacheService;
@Getter
private static RestUserEndpoints restUserEndpoints;
@Getter
private static CommentedConfigurationNode config = null;
@Getter
private static String botTrigger;
@Getter
private static Optional<List<String>> bBStatusChangeNotificationsEnabled = Optional.empty();
@Getter
private static Optional<List<String>> cFStatusChangeNotificationsEnabled = Optional.empty();
@Getter
private static Optional<List<String>> mcStatusChangeNotificationsEnabled = Optional.empty();
@Getter
private static Optional<List<String>> gHStatusChangeNotificationsEnabled = Optional.empty();
@Getter
private static Optional<List<String>> travisStatusChangeNotificationsEnabled = Optional.empty();
@Getter
private static CommonMarkUtils commonMarkUtils;
@Getter
private static WebSocket webSocket;
@Getter
private static ScheduledExecutorService scheduledTasks = Executors.newScheduledThreadPool(5);
public static void main (String args[]) {
log.info("FTB CurseApp bot V " + VERSION);
JCommander jc = null;
try {
jc = new JCommander(CommandArgs.getSettings(), args);
} catch (ParameterException e) {
log.error("Error w/ jcommander setup", e);
System.exit(1);
}
if (CommandArgs.getSettings().isHelp()) {
jc.setProgramName("FTB's CurseApp Bot");
jc.usage();
System.exit(0);
}
if (CommandArgs.getSettings().getConfigFile() == null || CommandArgs.getSettings().getConfigFile().isEmpty()) {
log.error("need an error message");
System.exit(1);
}
try {
ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(new File(CommandArgs.getSettings().getConfigFile())).build(); // Create the loader
config = loader.load(); // Load the configuration into memory
} catch (IOException e) {
log.error("error with config loading", e);
}
restUserEndpoints = new RestUserEndpoints();
restUserEndpoints.setupEndpoints();
LoginResponse lr = null;
username = config.getNode("credentials", "CurseAppLogin", "username").getString();
lr = restUserEndpoints.doLogin(new LoginRequest(username, config.getNode("credentials", "CurseAppLogin", "password").getString()));
log.info("Synchronous login done: for user " + lr.session.username);
restUserEndpoints.setAuthToken(lr.session.token);
CountDownLatch sessionLatch = new CountDownLatch(1);
CompletableFuture<CreateSessionResponse> createSessionResponseCompletableFuture = restUserEndpoints.session.create(new CreateSessionRequest(CurseGUID.newRandomUUID(), DevicePlatform.UNKNOWN));
createSessionResponseCompletableFuture.whenComplete((r, e) -> {
if (e != null) {
if (e.getCause() instanceof HttpException) {
log.error("Request failed: HTTP code: " + ((HttpException) e.getCause()).code());
// TODO: see comment in login response
} else {
// network or parser error, just print exception with causes
log.error("Request failed", e);
}
System.exit(1);
}
// all is ok. Set value
session = Optional.of(r);
// and make man thread to continue again
sessionLatch.countDown();
});
// ugly code/synchronization just to implement example
try {
sessionLatch.await();
// as soon as lock opened we know that sessionResponse is usable and it is safe to start websocket
} catch (InterruptedException e) {
System.exit(1);
// should not happen, just ignore
}
log.info("Async session done: " + session.get());
token = Optional.of(lr.session.token);
botTrigger = config.getNode("botSettings", "triggerKey").getString("!");
try {
bBStatusChangeNotificationsEnabled = Optional.ofNullable(config.getNode("botSettings", "BBStatusChangeNotificationsEnabled").getList(TypeToken.of(String.class)));
} catch (ObjectMappingException e) {
log.error("couldn't map bot settings - bb", e);
}
try {
cFStatusChangeNotificationsEnabled = Optional.ofNullable(config.getNode("botSettings", "CFStatusChangeNotificationsEnabled").getList(TypeToken.of(String.class)));
} catch (ObjectMappingException e) {
log.error("couldn't map bot settings - cf", e);
}
try {
gHStatusChangeNotificationsEnabled = Optional.ofNullable(config.getNode("botSettings", "GHStatusChangeNotificationsEnabled").getList(TypeToken.of(String.class)));
} catch (ObjectMappingException e) {
log.error("couldn't map bot settings - gh", e);
}
try {
mcStatusChangeNotificationsEnabled = Optional.ofNullable(config.getNode("botSettings", "MCStatusChangeNotificationsEnabled").getList(TypeToken.of(String.class)));
} catch (ObjectMappingException e) {
log.error("couldn't map bot settings - mc", e);
}
try {
travisStatusChangeNotificationsEnabled = Optional.ofNullable(config.getNode("botSettings", "TravisStatusChangeNotificationsEnabled").getList(TypeToken.of(String.class)));
} catch (ObjectMappingException e) {
log.error("couldn't map bot settings - travis", e);
}
log.info("bot trigger is " + botTrigger);
// startup persistance engine
MongoConnection.start();
// websocket testing code starts here
try {
webSocket = new WebSocket(lr, session.get(), new URI(Apis.NOTIFICATIONS));
} catch (Exception e) {
log.error("websocket failed", e);
System.exit(0);
}
CommandRegistry.registerBaseCommands();
scheduledTasks.scheduleAtFixedRate(new BBStatusChecker(webSocket), 0, 60, TimeUnit.SECONDS);
scheduledTasks.scheduleAtFixedRate(new CFStatusChecker(webSocket), 0, 60, TimeUnit.SECONDS);
scheduledTasks.scheduleAtFixedRate(new GHStatusChecker(webSocket), 0, 60, TimeUnit.SECONDS);
scheduledTasks.scheduleAtFixedRate(new McStatusChecker(webSocket), 0, 60, TimeUnit.SECONDS);
scheduledTasks.scheduleAtFixedRate(new TravisStatusChecker(webSocket), 0, 60, TimeUnit.SECONDS);
cacheService = new CacheService();
ResponseHandler responseHandler = webSocket.getResponseHandler();
responseHandler.addTask(new ConversationEvent(), NotificationsServiceContractType.CONVERSATION_MESSAGE_NOTIFICATION);
debug = config.getNode("botSettings", "debug").getBoolean(false);
if (debug) {
responseHandler.addTask(new TraceResponseTask(), NotificationsServiceContractType.CONVERSATION_MESSAGE_NOTIFICATION);
responseHandler.addTask(new DefaultResponseTask(), NotificationsServiceContractType.CONVERSATION_READ_NOTIFICATION);
responseHandler.addTask(new TraceResponseTask(), NotificationsServiceContractType.UNKNOWN);
}
commonMarkUtils = new CommonMarkUtils();
if (config.getNode("botSettings", "webEnabled").getBoolean(true)) {
WebService service = new WebService();
}
// to add your own handlers call ws.getResponseHandler() and configure it
CountDownLatch latch = new CountDownLatch(1);
webSocket.start();
try {
latch.await();
} catch (InterruptedException e) {
}
}
}
|
package nl.opengeogroep.safetymaps.server.stripes;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.mail.Message.RecipientType;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import net.sourceforge.stripes.action.*;
import nl.opengeogroep.safetymaps.server.db.Cfg;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
/**
*
* @author Matthijs Laan
*/
@StrictBinding
@UrlBinding("/action/mail")
public class MailActionBean implements ActionBean {
private ActionBeanContext context;
private static final Log log = LogFactory.getLog("cfg");
@Override
public ActionBeanContext getContext() {
return context;
}
@Override
public void setContext(ActionBeanContext context) {
this.context = context;
}
public Resolution mail() throws IOException {
Session session;
JSONObject response = new JSONObject();
response.put("result", false);
try {
Context ctx = new InitialContext();
session = (Session)ctx.lookup("java:comp/env/mail/session");
} catch(Exception e) {
log.error("Mail session not configured correctly, exception looking up JNDI resource", e);
response.put("error", "Server not configured correctly to send mail");
return new StreamingResolution("application/json", response.toString());
}
String mail, to, from, subject;
try {
String template = Cfg.getSetting("support_mail_template");
if(template == null) {
template = FileUtils.readFileToString(new File(context.getServletContext().getRealPath("/WEB-INF/mail.txt")));
}
final Map<String,String[]> parameters = new HashMap(context.getRequest().getParameterMap());
String replace = Cfg.getSetting("support_mail_replace_search");
String replacement = Cfg.getSetting("support_mail_replacement");
if(replace != null && replacement != null && parameters.containsKey("permalink")) {
String permalink = parameters.get("permalink")[0];
permalink = Pattern.compile(replace).matcher(permalink).replaceAll(replacement);
parameters.put("permalink", new String[] { permalink });
}
StrSubstitutor request = new StrSubstitutor(new StrLookup<String>() {
@Override
public String lookup(String key) {
String[] value = parameters.get(key);
if(value == null || value.length == 0) {
return "";
} else {
return value[0];
}
}
});
mail = request.replace(template);
to = Cfg.getSetting("support_mail_to");
from = Cfg.getSetting("support_mail_from");
if(from == null) {
from = context.getRequest().getParameter("name") + "<" + context.getRequest().getParameter("email") + ">";
}
subject = Cfg.getSetting("support_mail_subject");
if(to == null || from == null || subject == null) {
log.error("Missing safetymaps.settings keys for either support_mail_to, support_mail_from or support_mail_subject");
response.put("error", "Server configuration error formatting mail");
return new StreamingResolution("application/json", response.toString());
}
subject = request.replace(subject);
log.debug("Sending formatted mail to: " + to + ", subject: " + subject + ", body: " + mail);
log.info("Sending mail to " + to + ", received request from " + context.getRequest().getRemoteAddr());
} catch(Exception e) {
log.error("Error formatting mail", e);
response.put("error", "Server error formatting mail");
return new StreamingResolution("application/json", response.toString());
}
try {
javax.mail.Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(RecipientType.TO, new InternetAddress(to));
String sender = context.getRequest().getParameter("email");
if(sender != null) {
msg.addRecipient(RecipientType.CC, new InternetAddress(sender));
}
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(mail, "text/plain");
Transport.send(msg);
} catch(Exception e) {
log.error("Error formatting mail", e);
response.put("error", "Server error formatting mail");
return new StreamingResolution("application/json", response.toString());
}
response.put("result", true);
return new StreamingResolution("application/json", response.toString());
}
}
|
package com.fiftyonred.mock_jedis;
import com.fiftyonred.utils.WildcardMatcher;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.*;
import static com.fiftyonred.mock_jedis.DataContainer.CHARSET;
public class MockPipeline extends Pipeline {
private static final int NUM_DBS = 16;
private static final byte[] STRING_TYPE = "string".getBytes(CHARSET);
private static final byte[] LIST_TYPE = "list".getBytes(CHARSET);
private static final byte[] SET_TYPE = "set".getBytes(CHARSET);
private static final byte[] NONE_TYPE = "none".getBytes(CHARSET);
private static final byte[] OK_RESPONSE = "OK".getBytes(CHARSET);
private static final byte[] PONG_RESPONSE = "PONG".getBytes(CHARSET);
private final WildcardMatcher wildcardMatcher = new WildcardMatcher();
private final List<Map<DataContainer, KeyInformation>> allKeys;
private final List<Map<DataContainer, DataContainer>> allStorage;
private final List<Map<DataContainer, Map<DataContainer, DataContainer>>> allHashStorage;
private final List<Map<DataContainer, List<DataContainer>>> allListStorage;
private final List<Map<DataContainer, Set<DataContainer>>> allSetStorage;
private int currentDB;
private Map<DataContainer, KeyInformation> keys;
private Map<DataContainer, DataContainer> storage;
private Map<DataContainer, Map<DataContainer, DataContainer>> hashStorage;
private Map<DataContainer, List<DataContainer>> listStorage;
private Map<DataContainer, Set<DataContainer>> setStorage;
public MockPipeline() {
allKeys = new ArrayList<Map<DataContainer, KeyInformation>>(NUM_DBS);
allStorage = new ArrayList<Map<DataContainer, DataContainer>>(NUM_DBS);
allHashStorage = new ArrayList<Map<DataContainer, Map<DataContainer, DataContainer>>>(NUM_DBS);
allListStorage = new ArrayList<Map<DataContainer, List<DataContainer>>>(NUM_DBS);
allSetStorage = new ArrayList<Map<DataContainer, Set<DataContainer>>>(NUM_DBS);
for (int i = 0; i < NUM_DBS; ++i) {
allKeys.add(new HashMap<DataContainer, KeyInformation>());
allStorage.add(new HashMap<DataContainer, DataContainer>());
allHashStorage.add(new HashMap<DataContainer, Map<DataContainer, DataContainer>>());
allListStorage.add(new HashMap<DataContainer, List<DataContainer>>());
allSetStorage.add(new HashMap<DataContainer, Set<DataContainer>>());
}
select(0);
}
public int getCurrentDB() {
return currentDB;
}
protected static <T> T getRandomElementFromSet(final Set<T> set) {
return (T) set.toArray()[(int) (Math.random() * set.size())];
}
@Override
public Response<String> ping() {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
response.set(PONG_RESPONSE);
return response;
}
@Override
public Response<String> echo(final String string) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
response.set(echo(string.getBytes(CHARSET)).get());
return response;
}
@Override
public Response<byte[]> echo(final byte[] string) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
response.set(string);
return response;
}
@Override
public synchronized Response<Long> dbSize() {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
response.set((long) keys.size());
return response;
}
@Override
public synchronized Response<String> flushAll() {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
for (int dbNum = 0; dbNum < NUM_DBS; ++dbNum) {
allKeys.get(dbNum).clear();
allStorage.get(dbNum).clear();
allHashStorage.get(dbNum).clear();
allListStorage.get(dbNum).clear();
}
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<String> flushDB() {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
keys.clear();
storage.clear();
hashStorage.clear();
listStorage.clear();
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<String> rename(final String oldkey, final String newkey) {
return rename(DataContainer.from(oldkey), DataContainer.from(newkey));
}
@Override
public Response<String> rename(final byte[] oldkey, final byte[] newkey) {
return rename(DataContainer.from(oldkey), DataContainer.from(newkey));
}
private Response<String> rename(final DataContainer oldkey, final DataContainer newkey) {
if (oldkey.equals(newkey)) {
throw new JedisDataException("ERR source and destination objects are the same");
}
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final KeyInformation info = keys.get(oldkey);
switch (info.getType()) {
case HASH:
hashStorage.put(newkey, hashStorage.get(oldkey));
hashStorage.remove(oldkey);
break;
case LIST:
listStorage.put(newkey, listStorage.get(oldkey));
listStorage.remove(oldkey);
break;
case STRING:
default:
storage.put(newkey, storage.get(oldkey));
storage.remove(oldkey);
}
keys.put(newkey, info);
keys.remove(oldkey);
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<Long> renamenx(final String oldkey, final String newkey) {
return renamenx(DataContainer.from(oldkey), DataContainer.from(newkey));
}
@Override
public Response<Long> renamenx(final byte[] oldkey, final byte[] newkey) {
return renamenx(DataContainer.from(oldkey), DataContainer.from(newkey));
}
private Response<Long> renamenx(final DataContainer oldkey, final DataContainer newkey) {
if (oldkey.equals(newkey)) {
throw new JedisDataException("ERR source and destination objects are the same");
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final KeyInformation newInfo = keys.get(newkey);
if (newInfo == null) {
rename(oldkey, newkey);
response.set(1L);
} else {
response.set(0L);
}
return response;
}
@Override
public synchronized Response<String> set(final String key, final String value) {
return set(DataContainer.from(key), DataContainer.from(value));
}
@Override
public synchronized Response<String> set(final byte[] key, final byte[] value) {
return set(DataContainer.from(key), DataContainer.from(value));
}
private Response<String> set(final DataContainer key, final DataContainer value) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
createOrUpdateKey(key, KeyType.STRING, true);
storage.put(key, value);
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<Long> setnx(final String key, final String value) {
return setnx(DataContainer.from(key), DataContainer.from(value));
}
@Override
public synchronized Response<Long> setnx(final byte[] key, final byte[] value) {
return setnx(DataContainer.from(key), DataContainer.from(value));
}
private Response<Long> setnx(final DataContainer key, final DataContainer value) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final DataContainer result = getContainerFromStorage(key, false);
if (result == null) {
set(key, value);
response.set(1L);
} else {
response.set(0L);
}
return response;
}
@Override
public synchronized Response<String> get(final String key) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final DataContainer val = getContainerFromStorage(DataContainer.from(key), false);
response.set(DataContainer.toBytes(val));
return response;
}
@Override
public synchronized Response<byte[]> get(final byte[] key) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
final DataContainer val = getContainerFromStorage(DataContainer.from(key), false);
response.set(DataContainer.toBytes(val));
return response;
}
@Override
public synchronized Response<String> getSet(final String key, final String value) {
final Response<String> response = get(key);
set(key, value);
return response;
}
@Override
public synchronized Response<byte[]> getSet(final byte[] key, final byte[] value) {
final Response<byte[]> response = get(key);
set(key, value);
return response;
}
@Override
public Response<byte[]> dump(final byte[] key) {
return get(key);
}
@Override
public Response<byte[]> dump(final String key) {
return get(key.getBytes());
}
@Override
public Response<String> restore(final String key, final int ttl, final byte[] serializedValue) {
return setex(key.getBytes(CHARSET), ttl, serializedValue);
}
@Override
public Response<String> restore(final byte[] key, final int ttl, final byte[] serializedValue) {
return setex(key, ttl, serializedValue);
}
@Override
public synchronized Response<Boolean> exists(final String key) {
return exists(DataContainer.from(key));
}
@Override
public synchronized Response<Boolean> exists(final byte[] key) {
return exists(DataContainer.from(key));
}
private Response<Boolean> exists(final DataContainer key) {
final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN);
response.set(keys.containsKey(key) ? 1L : 0L);
return response;
}
@Override
public synchronized Response<String> type(final String key) {
return type(DataContainer.from(key));
}
@Override
public synchronized Response<String> type(final byte[] key) {
return type(DataContainer.from(key));
}
private Response<String> type(final DataContainer key) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final KeyInformation info = keys.get(key);
if (info != null && info.getType() == KeyType.STRING) {
response.set(STRING_TYPE);
} else if (info != null && info.getType() == KeyType.LIST) {
response.set(LIST_TYPE);
} else if (info != null && info.getType() == KeyType.SET) {
response.set(SET_TYPE);
} else {
response.set(NONE_TYPE);
}
return response;
}
@Override
public synchronized Response<Long> move(final String key, final int dbIndex) {
return move(DataContainer.from(key), dbIndex);
}
@Override
public synchronized Response<Long> move(final byte[] key, final int dbIndex) {
return move(DataContainer.from(key), dbIndex);
}
private Response<Long> move(final DataContainer key, final int dbIndex) {
if (dbIndex < 0 || dbIndex >= NUM_DBS) {
throw new JedisDataException("ERR index out of range");
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final KeyInformation info = keys.get(key);
if (info == null) {
response.set(0L);
} else {
final KeyInformation infoNew = allKeys.get(dbIndex).get(key);
if (infoNew == null) {
allKeys.get(dbIndex).put(key, info);
switch (info.getType()) {
case HASH:
allHashStorage.get(dbIndex).put(key, hashStorage.get(key));
hashStorage.remove(key);
break;
case LIST:
allListStorage.get(dbIndex).put(key, listStorage.get(key));
listStorage.remove(key);
break;
case STRING:
default:
allStorage.get(dbIndex).put(key, storage.get(key));
storage.remove(key);
}
keys.remove(key);
response.set(1L);
} else {
response.set(0L);
}
}
return response;
}
@Override
public synchronized Response<String> randomKey() {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
if (keys.isEmpty()) {
response.set(null);
} else {
final DataContainer result = getRandomElementFromSet(keys.keySet());
response.set(result.getBytes());
}
return response;
}
@Override
public Response<byte[]> randomKeyBinary() {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
final String result = randomKey().get();
response.set(result == null ? null : result.getBytes(CHARSET));
return response;
}
@Override
public Response<String> select(final int dbIndex) {
if (dbIndex < 0 || dbIndex >= NUM_DBS) {
throw new JedisDataException("ERR invalid DB index");
}
final Response<String> response = new Response<String>(BuilderFactory.STRING);
currentDB = dbIndex;
keys = allKeys.get(dbIndex);
storage = allStorage.get(dbIndex);
hashStorage = allHashStorage.get(dbIndex);
listStorage = allListStorage.get(dbIndex);
setStorage = allSetStorage.get(dbIndex);
response.set(OK_RESPONSE);
return response;
}
@Override
public Response<String> setex(final String key, final int seconds, final String value) {
return psetex(key, seconds * 1000, value);
}
@Override
public Response<String> setex(final byte[] key, final int seconds, final byte[] value) {
return psetex(key, seconds * 1000, value);
}
@Override
public synchronized Response<String> psetex(final String key, final int milliseconds, final String value) {
final Response<String> response = set(key, value);
pexpire(key, milliseconds);
return response;
}
@Override
public Response<String> psetex(final byte[] key, final int milliseconds, final byte[] value) {
final Response<String> response = set(key, value);
pexpire(key, milliseconds);
return response;
}
@Override
public Response<Long> expire(final String key, final int seconds) {
return expireAt(key, System.currentTimeMillis() / 1000 + seconds);
}
@Override
public Response<Long> expire(final byte[] key, final int seconds) {
return expireAt(key, System.currentTimeMillis() / 1000 + seconds);
}
@Override
public Response<Long> expireAt(final String key, final long unixTime) {
return pexpireAt(key, unixTime * 1000L);
}
@Override
public Response<Long> expireAt(final byte[] key, final long unixTime) {
return pexpireAt(key, unixTime * 1000L);
}
@Override
public Response<Long> pexpire(final String key, final int milliseconds) {
return pexpireAt(key, System.currentTimeMillis() + milliseconds);
}
@Override
public Response<Long> pexpire(final byte[] key, final int milliseconds) {
return pexpireAt(key, System.currentTimeMillis() + milliseconds);
}
@Override
public Response<Long> pexpire(final String key, final long milliseconds) {
return pexpireAt(key, System.currentTimeMillis() + milliseconds);
}
@Override
public Response<Long> pexpire(final byte[] key, final long milliseconds) {
return pexpireAt(key, System.currentTimeMillis() + milliseconds);
}
@Override
public synchronized Response<Long> pexpireAt(final String key, final long millisecondsTimestamp) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
response.set(pexpireAt(DataContainer.from(key), millisecondsTimestamp));
return response;
}
@Override
public synchronized Response<Long> pexpireAt(final byte[] key, final long millisecondsTimestamp) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
response.set(pexpireAt(DataContainer.from(key), millisecondsTimestamp));
return response;
}
public synchronized Long pexpireAt(final DataContainer key, final long millisecondsTimestamp) {
final KeyInformation info = keys.get(key);
if (info == null || info.isTTLSetAndKeyExpired()) {
return 0L;
} else {
info.setExpiration(millisecondsTimestamp);
return 1L;
}
}
@Override
public Response<Long> ttl(final String key) {
return ttl(DataContainer.from(key));
}
@Override
public Response<Long> ttl(final byte[] key) {
return ttl(DataContainer.from(key));
}
public Response<Long> ttl(final DataContainer key) {
Long pttlInResponse = pttl(key).get();
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
if (pttlInResponse != -1L) {
if (pttlInResponse > 0L && pttlInResponse < 1000L) {
pttlInResponse = 1000L;
}
response.set(pttlInResponse / 1000L);
} else {
response.set(pttlInResponse);
}
return response;
}
@Override
public synchronized Response<Long> append(final String key, final String value) {
return append(DataContainer.from(key), DataContainer.from(value));
}
@Override
public synchronized Response<Long> append(final byte[] key, final byte[] value) {
return append(DataContainer.from(key), DataContainer.from(value));
}
private Response<Long> append(final DataContainer key, final DataContainer value) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
DataContainer container = getContainerFromStorage(key, true);
final DataContainer newVal = container.append(value);
set(key, newVal);
response.set((long) newVal.getString().length());
return response;
}
@Override
public synchronized Response<Long> pttl(final String key) {
return pttl(DataContainer.from(key));
}
private Response<Long> pttl(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final KeyInformation info = keys.get(key);
response.set(info == null ? -1L : info.getTTL());
return response;
}
@Override
public synchronized Response<Long> persist(final String key) {
return persist(DataContainer.from(key));
}
@Override
public synchronized Response<Long> persist(final byte[] key) {
return persist(DataContainer.from(key));
}
private Response<Long> persist(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final KeyInformation info = keys.get(key);
if (info.getTTL() == -1) {
response.set(0L);
} else {
info.setExpiration(-1L);
response.set(1L);
}
return response;
}
@Override
public synchronized Response<List<String>> mget(final String... keys) {
if (keys.length <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'mget' command");
}
final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST);
final List<byte[]> result = new ArrayList<byte[]>(keys.length);
for (final String key : keys) {
final DataContainer val = getContainerFromStorage(DataContainer.from(key), false);
result.add(val == null ? null : val.getBytes());
}
response.set(result);
return response;
}
@Override
public synchronized Response<List<byte[]>> mget(final byte[]... keys) {
if (keys.length <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'mget' command");
}
final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST);
final List<byte[]> result = new ArrayList<byte[]>(keys.length);
for (final byte[] key : keys) {
final DataContainer val = getContainerFromStorage(DataContainer.from(key), false);
result.add(val == null ? null : val.getBytes());
}
response.set(result);
return response;
}
@Override
public synchronized Response<String> mset(final String... keysvalues) {
final int l = keysvalues.length;
if (l <= 0 || l % 2 != 0) {
throw new JedisDataException("ERR wrong number of arguments for 'mset' command");
}
for (int i = 0; i < l; i += 2) {
set(keysvalues[i], keysvalues[i + 1]);
}
final Response<String> response = new Response<String>(BuilderFactory.STRING);
response.set(OK_RESPONSE);
return response;
}
@Override
public Response<String> mset(final byte[]... keysvalues) {
return mset(convertToStrings(keysvalues));
}
@Override
public synchronized Response<Long> msetnx(final String... keysvalues) {
final int l = keysvalues.length;
if (l <= 0 || l % 2 != 0) {
throw new JedisDataException("ERR wrong number of arguments for 'msetnx' command");
}
long result = 1L;
for (int i = 0; i < l; i += 2) {
if (setnx(keysvalues[i], keysvalues[i + 1]).get() == 0L) {
result = 0L;
}
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
response.set(result);
return response;
}
@Override
public Response<Long> msetnx(final byte[]... keysvalues) {
return msetnx(convertToStrings(keysvalues));
}
@Override
public Response<Long> decr(final String key) {
return decrBy(key, 1L);
}
@Override
public Response<Long> decr(final byte[] key) {
return decrBy(key, 1L);
}
@Override
public Response<Long> decrBy(final String key, final long integer) {
return incrBy(key, -integer);
}
@Override
public Response<Long> decrBy(final byte[] key, final long integer) {
return incrBy(key, -integer);
}
@Override
public Response<Long> incr(final String key) {
return incrBy(key, 1L);
}
@Override
public Response<Long> incr(final byte[] key) {
return incrBy(key, 1L);
}
@Override
public synchronized Response<Long> incrBy(final String key, final long integer) {
return incrBy(DataContainer.from(key), integer);
}
@Override
public Response<Long> incrBy(final byte[] key, final long integer) {
return incrBy(DataContainer.from(key), integer);
}
private Response<Long> incrBy(final DataContainer key, final long integer) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final DataContainer val = getContainerFromStorage(key, true);
final long oldValue;
try {
oldValue = val == null || val.getString().isEmpty() ? 0L : Long.parseLong(val.getString());
} catch (final NumberFormatException ignored) {
throw new JedisDataException("ERR value is not an integer or out of range");
}
// check for overflow
if (oldValue > 0L ? integer > Long.MAX_VALUE - oldValue : integer < Long.MIN_VALUE - oldValue) {
throw new JedisDataException("ERR value is not an integer or out of range");
}
final long result = oldValue + integer;
storage.put(key, DataContainer.from(Long.toString(result)));
response.set(result);
return response;
}
@Override
public synchronized Response<Double> incrByFloat(final String key, final double increment) {
return incrByFloat(DataContainer.from(key), increment);
}
@Override
public Response<Double> incrByFloat(final byte[] key, final double increment) {
return incrByFloat(DataContainer.from(key), increment);
}
public synchronized Response<Double> incrByFloat(final DataContainer key, final double increment) {
final Response<Double> response = new Response<Double>(BuilderFactory.DOUBLE);
final DataContainer val = getContainerFromStorage(key, true);
final Double result;
try {
result = val == null || val.getString().isEmpty() ? increment : Double.parseDouble(val.getString()) + increment;
} catch (final NumberFormatException ignored) {
throw new JedisDataException("ERR value is not a valid float");
}
storage.put(key, DataContainer.from(result.toString()));
response.set(result.toString().getBytes(CHARSET));
return response;
}
@Override
public Response<List<String>> sort(final String key) {
return sort(key, new SortingParams());
}
@Override
public Response<Long> sort(final String key, final String dstkey) {
return sort(key, new SortingParams(), dstkey);
}
@Override
public Response<Long> sort(final byte[] key, final byte[] dstkey) {
return sort(key, new SortingParams(), dstkey);
}
private static Comparator<DataContainer> makeComparator(final Collection<String> params) {
final Comparator<DataContainer> comparator;
final int direction = params.contains(Protocol.Keyword.DESC.name().toLowerCase()) ? -1 : 1;
if (params.contains(Protocol.Keyword.ALPHA.name().toLowerCase())) {
comparator = new Comparator<DataContainer>() {
@Override
public int compare(final DataContainer o1, final DataContainer o2) {
return o1.compareTo(o2) * direction;
}
};
} else {
comparator = new Comparator<DataContainer>() {
@Override
public int compare(final DataContainer o1, final DataContainer o2) {
final Long i1, i2;
try {
i1 = Long.parseLong(o1.getString());
i2 = Long.parseLong(o2.getString());
} catch (final NumberFormatException e) {
throw new JedisDataException("ERR One or more scores can't be converted into double");
}
return i1.compareTo(i2) * direction;
}
};
}
return comparator;
}
@Override
public Response<List<String>> sort(final String key, final SortingParams sortingParameters) {
final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST);
List<DataContainer> sortedList = sort(DataContainer.from(key), sortingParameters);
response.set(DataContainer.toBytes(sortedList));
return response;
}
@Override
public Response<List<byte[]>> sort(final byte[] key, final SortingParams sortingParameters) {
final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST);
List<DataContainer> sortedList = sort(DataContainer.from(key), sortingParameters);
response.set(DataContainer.toBytes(sortedList));
return response;
}
public List<DataContainer> sort(final DataContainer key, final SortingParams sortingParameters) {
final List<DataContainer> result = new ArrayList<DataContainer>();
final KeyInformation info = keys.get(key);
if (info != null) {
switch (info.getType()) {
case LIST:
result.addAll(listStorage.get(key));
break;
case SET:
result.addAll(setStorage.get(key));
break;
case SORTED_SET:
throw new RuntimeException("Not implemented");
default:
throw new JedisDataException("WRONGTYPE Operation against a key holding the wrong kind of value");
}
}
final List<String> params = convertToStrings(sortingParameters.getParams());
Collections.sort(result, makeComparator(params));
final List<DataContainer> filteredResult = new ArrayList<DataContainer>(result.size());
final int limitpos = params.indexOf(Protocol.Keyword.LIMIT.name().toLowerCase());
if (limitpos >= 0) {
final int start = Math.max(Integer.parseInt(params.get(limitpos + 1)), 0);
final int end = Math.min(Integer.parseInt(params.get(limitpos + 2)) + start, result.size());
for (final DataContainer entry : result.subList(start, end)) {
filteredResult.add(entry);
}
} else {
for (final DataContainer entry : result) {
filteredResult.add(entry);
}
}
return filteredResult;
}
@Override
public synchronized Response<Long> sort(final String key, final SortingParams sortingParameters, final String dstkey) {
return sort(DataContainer.from(key), sortingParameters, DataContainer.from(dstkey));
}
@Override
public Response<Long> sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) {
return sort(DataContainer.from(key), sortingParameters, DataContainer.from(dstkey));
}
public synchronized Response<Long> sort(final DataContainer key, final SortingParams sortingParameters, final DataContainer dstkey) {
List<DataContainer> sorted = sort(key, sortingParameters);
del(dstkey);
keys.put(dstkey, new KeyInformation(KeyType.LIST));
listStorage.put(dstkey, sorted);
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
response.set((long) sorted.size());
return response;
}
@Override
public Response<List<byte[]>> sort(final byte[] key) {
return sort(key, new SortingParams());
}
@Override
public Response<Long> strlen(final String key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final DataContainer val = getContainerFromStorage(DataContainer.from(key), false);
response.set(val == null ? 0L : val.getString().length());
return response;
}
@Override
public Response<Long> strlen(final byte[] key) {
return strlen(new String(key));
}
@Override
public Response<Long> del(final String... keys) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
long result = 0L;
for (final String key : keys) {
result += del(key).get();
}
response.set(result);
return response;
}
@Override
public Response<Long> del(final byte[]... keys) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
long result = 0L;
for (final byte[] key : keys) {
result += del(key).get();
}
response.set(result);
return response;
}
@Override
public synchronized Response<Long> del(final String key) {
return del(DataContainer.from(key));
}
@Override
public synchronized Response<Long> del(final byte[] key) {
return del(DataContainer.from(key));
}
private Response<Long> del(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
long result = 0L;
final KeyInformation info = this.keys.remove(key);
if (info != null) {
switch (info.getType()) {
case HASH:
hashStorage.remove(key);
break;
case LIST:
listStorage.remove(key);
break;
case STRING:
default:
storage.remove(key);
}
++result;
}
response.set(result);
return response;
}
@Override
public synchronized Response<String> hget(final String key, final String field) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result == null) {
response.set(null);
return response;
}
final DataContainer fieldValue = result.get(DataContainer.from(field));
response.set(DataContainer.toBytes(fieldValue));
return response;
}
@Override
public synchronized Response<byte[]> hget(final byte[] key, final byte[] field) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result == null) {
response.set(null);
return response;
}
final DataContainer fieldValue = result.get(DataContainer.from(field));
response.set(DataContainer.toBytes(fieldValue));
return response;
}
@Override
public synchronized Response<Map<String, String>> hgetAll(final String key) {
final Response<Map<String, String>> response = new Response<Map<String, String>>(BuilderFactory.STRING_MAP);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
final List<byte[]> encodedResult = new ArrayList<byte[]>(result.size());
for (final Map.Entry<DataContainer, DataContainer> e : result.entrySet()) {
encodedResult.add(e.getKey().getBytes());
encodedResult.add(e.getValue().getBytes());
}
response.set(encodedResult);
} else {
response.set(new ArrayList<byte[]>(0));
}
return response;
}
@Override
public synchronized Response<Map<byte[], byte[]>> hgetAll(final byte[] key) {
final Response<Map<byte[], byte[]>> response = new Response<Map<byte[], byte[]>>(BuilderFactory.BYTE_ARRAY_MAP);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
final List<byte[]> encodedResult = new ArrayList<byte[]>(result.size());
for (final Map.Entry<DataContainer, DataContainer> e : result.entrySet()) {
encodedResult.add(e.getKey().getBytes());
encodedResult.add(e.getValue().getBytes());
}
response.set(encodedResult);
} else {
response.set(new ArrayList<byte[]>(0));
}
return response;
}
@Override
public synchronized Response<Set<String>> hkeys(final String key) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
response.set(DataContainer.toBytes(result.keySet()));
} else {
response.set(new ArrayList<byte[]>());
}
return response;
}
@Override
public synchronized Response<Set<byte[]>> hkeys(final byte[] key) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
response.set(DataContainer.toBytes(result.keySet()));
} else {
response.set(new ArrayList<byte[]>());
}
return response;
}
@Override
public synchronized Response<List<String>> hvals(final String key) {
final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
response.set(DataContainer.toBytes(result.values()));
} else {
response.set(new ArrayList<byte[]>());
}
return response;
}
@Override
public synchronized Response<List<byte[]>> hvals(final byte[] key) {
final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST);
final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false);
if (result != null) {
response.set(DataContainer.toBytes(result.values()));
} else {
response.set(new ArrayList<byte[]>());
}
return response;
}
@Override
public synchronized Response<Long> hset(final String key, final String field, final String value) {
return hset(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value));
}
@Override
public synchronized Response<Long> hset(final byte[] key, final byte[] field, final byte[] value) {
return hset(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value));
}
private Response<Long> hset(final DataContainer key, final DataContainer field, final DataContainer value) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true);
response.set(m.containsKey(field) ? 0L : 1L);
m.put(field, value);
return response;
}
@Override
public synchronized Response<Long> hsetnx(final String key, final String field, final String value) {
return hsetnx(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value));
}
@Override
public synchronized Response<Long> hsetnx(final byte[] key, final byte[] field, final byte[] value) {
return hsetnx(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value));
}
private Response<Long> hsetnx(final DataContainer key, final DataContainer field, final DataContainer value) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true);
long result = 0L;
if (!m.containsKey(field)) {
m.put(field, value);
result = 1L;
}
response.set(result);
return response;
}
@Override
public synchronized Response<List<String>> hmget(final String key, final String... fields) {
final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST);
final List<byte[]> result = new ArrayList<byte[]>();
final Map<DataContainer, DataContainer> hash = getHashFromStorage(DataContainer.from(key), false);
if (hash == null) {
for (final String ignored : fields) {
result.add(null);
}
response.set(result);
return response;
}
for (final String field : fields) {
final DataContainer v = hash.get(DataContainer.from(field));
result.add(DataContainer.toBytes(v));
}
response.set(result);
return response;
}
@Override
public synchronized Response<List<byte[]>> hmget(final byte[] key, final byte[]... fields) {
final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST);
final List<byte[]> result = new ArrayList<byte[]>();
final Map<DataContainer, DataContainer> hash = getHashFromStorage(DataContainer.from(key), false);
if (hash == null) {
for (final byte[] ignored : fields) {
result.add(null);
}
response.set(result);
return response;
}
for (final byte[] field : fields) {
final DataContainer v = hash.get(DataContainer.from(field));
result.add(DataContainer.toBytes(v));
}
response.set(result);
return response;
}
@Override
public synchronized Response<String> hmset(final String key, final Map<String, String> hash) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final Map<DataContainer, DataContainer> m = getHashFromStorage(DataContainer.from(key), true);
for (final Map.Entry<String, String> e : hash.entrySet()) {
m.put(DataContainer.from(e.getKey()), DataContainer.from(e.getValue()));
}
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<String> hmset(final byte[] key, final Map<byte[], byte[]> hash) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final Map<DataContainer, DataContainer> m = getHashFromStorage(DataContainer.from(key), true);
for (final Map.Entry<byte[], byte[]> e : hash.entrySet()) {
m.put(DataContainer.from(e.getKey()), DataContainer.from(e.getValue()));
}
response.set(OK_RESPONSE);
return response;
}
@Override
public synchronized Response<Long> hincrBy(final String key, final String field, final long value) {
return hincrBy(DataContainer.from(key), DataContainer.from(field), value);
}
@Override
public synchronized Response<Long> hincrBy(final byte[] key, final byte[] field, final long value) {
return hincrBy(DataContainer.from(key), DataContainer.from(field), value);
}
private Response<Long> hincrBy(final DataContainer key, final DataContainer field, final long value) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true);
DataContainer val = m.get(field);
if (val == null) {
val = DataContainer.from(Long.valueOf(0L).toString());
}
final Long result;
try {
result = Long.valueOf(val.getString()) + value;
} catch (final NumberFormatException ignored) {
throw new JedisDataException("ERR value is not an integer or out of range");
}
m.put(field, DataContainer.from(result.toString()));
response.set(result);
return response;
}
@Override
public synchronized Response<Double> hincrByFloat(final String key, final String field, final double increment) {
return hincrByFloat(DataContainer.from(key), DataContainer.from(field), increment);
}
@Override
public synchronized Response<Double> hincrByFloat(final byte[] key, final byte[] field, final double increment) {
return hincrByFloat(DataContainer.from(key), DataContainer.from(field), increment);
}
private Response<Double> hincrByFloat(final DataContainer key, final DataContainer field, final double increment) {
final Response<Double> response = new Response<Double>(BuilderFactory.DOUBLE);
final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true);
DataContainer val = m.get(field);
if (val == null) {
val = DataContainer.from(Double.valueOf(0.0D).toString());
}
final Double result;
try {
result = Double.parseDouble(val.toString()) + increment;
} catch (final NumberFormatException ignored) {
throw new JedisDataException("ERR value is not a valid float");
}
DataContainer resultContainer = DataContainer.from(result.toString());
m.put(field, resultContainer);
response.set(resultContainer.getBytes());
return response;
}
@Override
public synchronized Response<Long> hdel(final String key, final String... field) {
return hdel(DataContainer.from(key), DataContainer.from(field));
}
@Override
public synchronized Response<Long> hdel(final byte[] key, final byte[]... field) {
return hdel(DataContainer.from(key), DataContainer.from(field));
}
private Response<Long> hdel(final DataContainer key, final DataContainer... fields) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true);
long result = 0L;
for (final DataContainer currentField : fields) {
if (m.remove(currentField) != null) {
++result;
}
}
response.set(result);
return response;
}
@Override
public synchronized Response<Boolean> hexists(final String key, final String field) {
return hexists(DataContainer.from(key), DataContainer.from(field));
}
@Override
public synchronized Response<Boolean> hexists(final byte[] key, final byte[] field) {
return hexists(DataContainer.from(key), DataContainer.from(field));
}
private Response<Boolean> hexists(final DataContainer key, final DataContainer field) {
final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN);
final Map<DataContainer, DataContainer> hash = getHashFromStorage(key, false);
response.set(hash != null && hash.containsKey(field) ? 1L : 0L);
return response;
}
@Override
public synchronized Response<Long> hlen(final String key) {
return hlen(DataContainer.from(key));
}
@Override
public synchronized Response<Long> hlen(final byte[] key) {
return hlen(DataContainer.from(key));
}
private Response<Long> hlen(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Map<DataContainer, DataContainer> hash = getHashFromStorage(key, false);
if (hash != null) {
response.set((long) hash.size());
} else {
response.set(0L);
}
return response;
}
@Override
public synchronized Response<Long> lpush(final String key, final String... string) {
return lpush(DataContainer.from(key), DataContainer.from(string));
}
@Override
public synchronized Response<Long> lpush(final byte[] key, final byte[]... string) {
return lpush(DataContainer.from(key), DataContainer.from(string));
}
private Response<Long> lpush(final DataContainer key, final DataContainer... string) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
List<DataContainer> list = getListFromStorage(key, true);
if (list == null) {
list = new ArrayList<DataContainer>();
listStorage.put(key, list);
}
Collections.addAll(list, string);
response.set((long) list.size());
return response;
}
@Override
public synchronized Response<String> lpop(final String key) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final List<DataContainer> list = getListFromStorage(DataContainer.from(key), true);
if (list == null || list.isEmpty()) {
response.set(null);
} else {
response.set(list.remove(list.size() - 1).getBytes());
}
return response;
}
@Override
public synchronized Response<byte[]> lpop(final byte[] key) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
final List<DataContainer> list = getListFromStorage(DataContainer.from(key), true);
if (list == null || list.isEmpty()) {
response.set(null);
} else {
response.set(list.remove(list.size() - 1).getBytes());
}
return response;
}
@Override
public synchronized Response<Long> llen(final String key) {
return llen(DataContainer.from(key));
}
@Override
public Response<Long> llen(final byte[] key) {
return llen(DataContainer.from(key));
}
public synchronized Response<Long> llen(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final List<DataContainer> list = getListFromStorage(key, false);
if (list == null) {
response.set(0L);
} else {
response.set((long) list.size());
}
return response;
}
@Override
public Response<List<String>> lrange(final String key, long start, long end) {
final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST);
List<DataContainer> result = lrange(DataContainer.from(key), start, end);
response.set(DataContainer.toBytes(result));
return response;
}
@Override
public Response<List<byte[]>> lrange(final byte[] key, long start, long end) {
final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST);
List<DataContainer> result = lrange(DataContainer.from(key), start, end);
response.set(DataContainer.toBytes(result));
return response;
}
public List<DataContainer> lrange(final DataContainer key, long start, long end) {
final List<DataContainer> full = getListFromStorage(key, false);
List<DataContainer> result = new ArrayList<DataContainer>();
if (start < 0L) {
start = Math.max(full.size() + start, 0L);
}
if (end < 0L) {
end = full.size() + end;
}
if (start > full.size() || start > end) {
return Collections.emptyList();
}
end = Math.min(full.size() - 1, end);
for (int i = (int) start; i <= end; i++) {
result.add(full.get(i));
}
return result;
}
@Override
public void sync() {
// do nothing
}
@Override
public synchronized Response<Set<String>> keys(final String pattern) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
Set<DataContainer> result = keys(DataContainer.from(pattern));
response.set(DataContainer.toBytes(result));
return response;
}
@Override
public synchronized Response<Set<byte[]>> keys(final byte[] pattern) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
Set<DataContainer> result = keys(DataContainer.from(pattern));
response.set(DataContainer.toBytes(result));
return response;
}
private Set<DataContainer> keys(final DataContainer pattern) {
Set<DataContainer> result = new HashSet<DataContainer>();
for (final DataContainer key : keys.keySet()) {
if (wildcardMatcher.match(key.getString(), pattern.getString())) {
result.add(key);
}
}
return result;
}
protected boolean createOrUpdateKey(final DataContainer key, final KeyType type, final boolean resetTTL) {
KeyInformation info = keys.get(key);
if (info == null) {
info = new KeyInformation(type);
keys.put(key, info);
return true;
} else {
if (info.getType() != type) {
throw new JedisDataException("ERR Operation against a key holding the wrong kind of value");
}
if (resetTTL) {
info.setExpiration(-1L);
}
return false;
}
}
protected DataContainer getContainerFromStorage(final DataContainer key, final boolean createIfNotExist) {
final KeyInformation info = keys.get(key);
if (info == null) {
if (createIfNotExist) {
createOrUpdateKey(key, KeyType.STRING, true);
DataContainer container = DataContainer.from("");
storage.put(key, container);
return container;
}
return null; // no such key exists
}
if (info.getType() != KeyType.STRING) {
throw new JedisDataException("ERR Operation against a key holding the wrong kind of value");
}
if (info.isTTLSetAndKeyExpired()) {
storage.remove(key);
keys.remove(key);
return null;
}
return storage.get(key);
}
protected Map<DataContainer, DataContainer> getHashFromStorage(final DataContainer key, final boolean createIfNotExist) {
final KeyInformation info = keys.get(key);
if (info == null) {
if (createIfNotExist) {
createOrUpdateKey(key, KeyType.HASH, false);
final Map<DataContainer, DataContainer> result = new HashMap<DataContainer, DataContainer>();
hashStorage.put(key, result);
return result;
}
return null; // no such key exists
}
if (info.getType() != KeyType.HASH) {
throw new JedisDataException("ERR Operation against a key holding the wrong kind of value");
}
if (info.isTTLSetAndKeyExpired()) {
hashStorage.remove(key);
keys.remove(key);
return null;
}
return hashStorage.get(key);
}
protected List<DataContainer> getListFromStorage(final DataContainer key, final boolean createIfNotExist) {
final KeyInformation info = keys.get(key);
if (info == null) {
if (createIfNotExist) {
createOrUpdateKey(key, KeyType.LIST, false);
final List<DataContainer> result = new ArrayList<DataContainer>();
listStorage.put(key, result);
return result;
}
return null; // no such key exists
}
if (info.getType() != KeyType.LIST) {
throw new JedisDataException("ERR Operation against a key holding the wrong kind of value");
}
if (info.isTTLSetAndKeyExpired()) {
listStorage.remove(key);
keys.remove(key);
return null;
}
return listStorage.get(key);
}
protected Set<DataContainer> getSetFromStorage(final DataContainer key, final boolean createIfNotExist) {
final KeyInformation info = keys.get(key);
if (info == null) {
if (createIfNotExist) {
createOrUpdateKey(key, KeyType.SET, false);
final Set<DataContainer> result = new HashSet<DataContainer>();
setStorage.put(key, result);
return result;
}
return null; // no such key exists
}
if (info.getType() != KeyType.SET) {
throw new JedisDataException("ERR Operation against a key holding the wrong kind of value");
}
if (info.isTTLSetAndKeyExpired()) {
setStorage.remove(key);
keys.remove(key);
return null;
}
return setStorage.get(key);
}
protected static String[] convertToStrings(final byte[][] b) {
final int l = b.length;
final String[] result = new String[l];
for (int i = 0; i < l; ++i) {
result[i] = new String(b[i], CHARSET);
}
return result;
}
protected static List<String> convertToStrings(final Collection<byte[]> collection) {
final List<String> result = new LinkedList<String>();
for (final byte[] entry : collection) {
result.add(new String(entry, CHARSET));
}
return result;
}
@Override
public synchronized Response<Long> sadd(final String key, final String... member) {
return sadd(DataContainer.from(key), DataContainer.from(member));
}
@Override
public synchronized Response<Long> sadd(final byte[] key, final byte[]... member) {
return sadd(DataContainer.from(key), DataContainer.from(member));
}
private Response<Long> sadd(final DataContainer key, final DataContainer... members) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> set = getSetFromStorage(key, true);
Long added = 0L;
for (final DataContainer s : members) {
if (set.add(s)) {
added++;
}
}
response.set(added);
return response;
}
@Override
public synchronized Response<Long> srem(final String key, final String... member) {
return srem(DataContainer.from(key), DataContainer.from(member));
}
@Override
public synchronized Response<Long> srem(final byte[] key, final byte[]... member) {
return srem(DataContainer.from(key), DataContainer.from(member));
}
private Response<Long> srem(final DataContainer key, final DataContainer... member) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> set = getSetFromStorage(key, true);
Long removed = 0L;
for (final DataContainer s : member) {
if (set.remove(s)) {
removed++;
}
}
response.set(removed);
return response;
}
@Override
public synchronized Response<Long> scard(final String key) {
return scard(DataContainer.from(key));
}
@Override
public synchronized Response<Long> scard(final byte[] key) {
return scard(DataContainer.from(key));
}
private Response<Long> scard(final DataContainer key) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> set = getSetFromStorage(key, true);
response.set((long) set.size());
return response;
}
@Override
public synchronized Response<Set<String>> sdiff(final String... keys) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
DataContainer[] keyContainers = DataContainer.from(keys);
Collection<DataContainer> collection = sinter(keyContainers);
List<byte[]> data = DataContainer.toBytes(collection);
response.set(data);
return response;
}
@Override
public synchronized Response<Set<byte[]>> sdiff(final byte[]... keys) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
DataContainer[] keyContainers = DataContainer.from(keys);
Collection<DataContainer> collection = sinter(keyContainers);
List<byte[]> data = DataContainer.toBytes(collection);
response.set(data);
return response;
}
private Set<DataContainer> sdiff(final DataContainer... keys) {
final int l = keys.length;
if (l <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sdiff' command");
}
final Set<DataContainer> result = new HashSet<DataContainer>(getSetFromStorage(keys[0], true));
for (int i = 1; i < l; ++i) {
final Set<DataContainer> set = getSetFromStorage(keys[i], true);
result.removeAll(set);
}
return result;
}
@Override
public synchronized Response<Long> sdiffstore(final String dstKey, final String... keys) {
return sdiffstore(DataContainer.from(dstKey), DataContainer.from(keys));
}
@Override
public synchronized Response<Long> sdiffstore(final byte[] dstKey, final byte[]... keys) {
return sdiffstore(DataContainer.from(dstKey), DataContainer.from(keys));
}
private Response<Long> sdiffstore(final DataContainer dstKey, final DataContainer... keys) {
if (keys.length <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sdiff' command");
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> diff = sdiff(keys);
final Set<DataContainer> dst = getSetFromStorage(dstKey, true);
if (!dst.isEmpty()) {
dst.clear();
}
dst.addAll(diff);
response.set((long) diff.size());
return response;
}
@Override
public synchronized Response<Set<String>> sinter(final String... keys) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
DataContainer[] keyContainers = DataContainer.from(keys);
Collection<DataContainer> collection = sinter(keyContainers);
List<byte[]> data = DataContainer.toBytes(collection);
response.set(data);
return response;
}
@Override
public synchronized Response<Set<byte[]>> sinter(final byte[]... keys) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
DataContainer[] keyContainers = DataContainer.from(keys);
Collection<DataContainer> collection = sinter(keyContainers);
List<byte[]> data = DataContainer.toBytes(collection);
response.set(data);
return response;
}
private Set<DataContainer> sinter(final DataContainer... keys) {
final int l = keys.length;
if (l <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sinter' command");
}
final Set<DataContainer> firstSet = new HashSet<DataContainer>(getSetFromStorage(keys[0], true));
for (int i = 1; i < l; ++i) {
final Set<DataContainer> set = getSetFromStorage(keys[i], true);
firstSet.retainAll(set);
}
return firstSet;
}
@Override
public synchronized Response<Long> sinterstore(final String dstKey, final String... keys) {
return sinterstore(DataContainer.from(dstKey), DataContainer.from(keys));
}
@Override
public synchronized Response<Long> sinterstore(final byte[] dstkey, final byte[]... keys) {
return sinterstore(DataContainer.from(dstkey), DataContainer.from(keys));
}
private Response<Long> sinterstore(final DataContainer dstKey, final DataContainer... keys) {
if (keys.length <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sinterstore' command");
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> inter = sinter(keys);
final Set<DataContainer> dst = getSetFromStorage(dstKey, true);
if (!dst.isEmpty()) {
dst.clear();
}
dst.addAll(inter);
response.set((long) inter.size());
return response;
}
@Override
public synchronized Response<Boolean> sismember(final String key, final String member) {
return sismember(DataContainer.from(key), DataContainer.from(member));
}
@Override
public synchronized Response<Boolean> sismember(final byte[] key, final byte[] member) {
return sismember(DataContainer.from(key), DataContainer.from(member));
}
private Response<Boolean> sismember(final DataContainer key, final DataContainer member) {
final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN);
final Set<DataContainer> set = getSetFromStorage(key, false);
response.set(set != null && set.contains(member) ? 1L : 0L);
return response;
}
@Override
public synchronized Response<Long> smove(final String srckey, final String dstkey, final String member) {
return smove(DataContainer.from(srckey), DataContainer.from(dstkey), DataContainer.from(member));
}
@Override
public synchronized Response<Long> smove(final byte[] srckey, final byte[] dstkey, final byte[] member) {
return smove(DataContainer.from(srckey), DataContainer.from(dstkey), DataContainer.from(member));
}
private Response<Long> smove(final DataContainer srckey, final DataContainer dstkey, final DataContainer member) {
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> src = getSetFromStorage(srckey, false);
final Set<DataContainer> dst = getSetFromStorage(dstkey, true);
if (src.remove(member)) {
dst.add(member);
response.set(1L);
} else {
response.set(0L);
}
return response;
}
@Override
public synchronized Response<String> spop(final String key) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
DataContainer result = spop(DataContainer.from(key));
response.set(DataContainer.toBytes(result));
return response;
}
@Override
public synchronized Response<byte[]> spop(final byte[] key) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
DataContainer result = spop(DataContainer.from(key));
response.set(DataContainer.toBytes(result));
return response;
}
private DataContainer spop(final DataContainer key) {
DataContainer member = srandmember(key);
if (member != null) {
final Set<DataContainer> src = getSetFromStorage(key, false);
src.remove(member);
}
return member;
}
@Override
public synchronized Response<String> srandmember(final String key) {
final Response<String> response = new Response<String>(BuilderFactory.STRING);
final DataContainer result = srandmember(DataContainer.from(key));
response.set(result == null ? null : result.getBytes());
return response;
}
@Override
public synchronized Response<byte[]> srandmember(final byte[] key) {
final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY);
final DataContainer result = srandmember(DataContainer.from(key));
response.set(result == null ? null : result.getBytes());
return response;
}
private DataContainer srandmember(final DataContainer key) {
final Set<DataContainer> src = getSetFromStorage(key, false);
if (src == null) {
return null;
} else {
return getRandomElementFromSet(src);
}
}
@Override
public synchronized Response<Set<String>> smembers(final String key) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
final Set<DataContainer> members = smembers(DataContainer.from(key));
response.set(DataContainer.toBytes(members));
return response;
}
@Override
public synchronized Response<Set<byte[]>> smembers(final byte[] key) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
final Set<DataContainer> members = smembers(DataContainer.from(key));
response.set(DataContainer.toBytes(members));
return response;
}
private Set<DataContainer> smembers(final DataContainer key) {
return getSetFromStorage(key, true);
}
@Override
public synchronized Response<Set<String>> sunion(final String... keys) {
final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET);
Set<DataContainer> result = sunion(DataContainer.from(keys));
response.set(DataContainer.toBytes(result));
return response;
}
@Override
public synchronized Response<Set<byte[]>> sunion(final byte[]... keys) {
final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET);
Set<DataContainer> result = sunion(DataContainer.from(keys));
response.set(DataContainer.toBytes(result));
return response;
}
private Set<DataContainer> sunion(final DataContainer... keys) {
final int l = keys.length;
if (l <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sunion' command");
}
final Set<DataContainer> result = new HashSet<DataContainer>(getSetFromStorage(keys[0], true));
for (int i = 1; i < l; ++i) {
final Set<DataContainer> set = getSetFromStorage(keys[i], true);
result.addAll(set);
}
return result;
}
@Override
public synchronized Response<Long> sunionstore(final String dstkey, final String... keys) {
return sunionstore(DataContainer.from(dstkey), DataContainer.from(keys));
}
@Override
public synchronized Response<Long> sunionstore(final byte[] dstkey, final byte[]... keys) {
return sunionstore(DataContainer.from(dstkey), DataContainer.from(keys));
}
private Response<Long> sunionstore(final DataContainer dstkey, final DataContainer... keys) {
if (keys.length <= 0) {
throw new JedisDataException("ERR wrong number of arguments for 'sunionstore' command");
}
final Response<Long> response = new Response<Long>(BuilderFactory.LONG);
final Set<DataContainer> inter = sunion(keys);
final Set<DataContainer> dst = getSetFromStorage(dstkey, true);
if (!dst.isEmpty()) {
dst.clear();
}
dst.addAll(inter);
response.set((long) inter.size());
return response;
}
}
|
package org.ftc8702.configurations.production;
import android.graphics.Color;
import com.qualcomm.hardware.HardwareFactory;
import com.qualcomm.hardware.motors.TetrixMotor;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.ftc8702.components.motors.MecanumWheelDriveTrain;
import org.ftc8702.opmodes.production.SkystoneFlexArm;
import org.ftc8702.opmodes.production.SkystoneHugger;
import org.ftc8702.opmodes.production.SkystoneIntake;
import org.ftc8702.opmodes.production.SkystoneJaJa;
import ftcbootstrap.components.utils.TelemetryUtil;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.CRServoImpl;
import com.qualcomm.robotcore.hardware.CRServoImplEx;
public class SkystoneAutoConfig extends AbstractRobotConfiguration {
public ColorSensor colorSensor;
public MecanumWheelDriveTrain driveTrain;
public SkystoneJaJa jaja;
public SkystoneHugger hugger;
public SkystoneFlexArm FlexArm;
public SkystoneIntake Intake;
private HardwareMap hardwareMap;
@Override
public void init(HardwareMap hardwareMap, TelemetryUtil telemetryUtil) {
this.hardwareMap = hardwareMap;
setTelemetry(telemetryUtil);
ProdMecanumRobotConfiguration mecanumConfig = ProdMecanumRobotConfiguration.newConfig(hardwareMap, telemetryUtil);
driveTrain = new MecanumWheelDriveTrain(mecanumConfig.motorFL,mecanumConfig.motorFR,mecanumConfig.motorBL,mecanumConfig.motorBR);
jaja = new SkystoneJaJa(hardwareMap.get(Servo.class, "foundationGrabberL"), hardwareMap.get(Servo.class, "foundationGrabberR"));
FlexArm = new SkystoneFlexArm(mecanumConfig.SliderArmLeft, mecanumConfig.SliderArmRight);
Intake = new SkystoneIntake(mecanumConfig.IntakeWheelLeft, mecanumConfig.IntakeWheelRight);
colorSensor = hardwareMap.get(ColorSensor.class, "colorSensor");
hugger = new SkystoneHugger(hardwareMap.get(Servo.class, "huggerTop"),hardwareMap.get(Servo.class, "huggerBottom"));
// telemetryUtil.addData("Color Sensor", colorSensor+"");
telemetryUtil.sendTelemetry();
}
}
|
package com.github.anba.es6draft.parser;
import static com.github.anba.es6draft.semantics.StaticSemantics.*;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.github.anba.es6draft.ast.*;
import com.github.anba.es6draft.ast.BreakableStatement.Abrupt;
import com.github.anba.es6draft.ast.MethodDefinition.MethodType;
import com.github.anba.es6draft.parser.ParserException.ExceptionType;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.internal.SmallArrayList;
/**
* Parser for ECMAScript6 source code
* <ul>
* <li>11 Expressions
* <li>12 Statements and Declarations
* <li>13 Functions and Generators
* <li>14 Scripts and Modules
* </ul>
*/
public class Parser {
private static final boolean MODULES_ENABLED = false;
private static final boolean DEBUG = false;
private static final Binding NO_INHERITED_BINDING = null;
private static final Set<String> EMPTY_LABEL_SET = Collections.emptySet();
private final String sourceFile;
private final int sourceLine;
private final EnumSet<Option> options;
private TokenStream ts;
private ParseContext context;
private enum StrictMode {
Unknown, Strict, NonStrict
}
private enum StatementType {
Iteration, Breakable, Statement
}
private enum ContextKind {
Script, Function, Generator, ArrowFunction
}
private static class ParseContext {
final ParseContext parent;
final ContextKind kind;
boolean superReference = false;
boolean yieldAllowed = false;
StrictMode strictMode = StrictMode.Unknown;
boolean explicitStrict = false;
ParserException strictError = null;
List<FunctionNode> deferred = null;
ArrayDeque<ObjectLiteral> objectLiterals = null;
Map<String, LabelContext> labelSet = null;
LabelContext labels = null;
ScopeContext scopeContext;
final FunctionContext funContext;
ParseContext() {
this.parent = null;
this.kind = null;
this.funContext = null;
}
ParseContext(ParseContext parent, ContextKind kind) {
this.parent = parent;
this.kind = kind;
this.funContext = new FunctionContext(this);
this.scopeContext = funContext;
if (parent.strictMode == StrictMode.Strict) {
this.strictMode = parent.strictMode;
}
}
void setReferencesSuper() {
ParseContext cx = this;
while (cx.kind == ContextKind.ArrowFunction) {
cx = cx.parent;
}
cx.superReference = true;
}
boolean hasSuperReference() {
return superReference;
}
int countLiterals() {
return (objectLiterals != null ? objectLiterals.size() : 0);
}
void addLiteral(ObjectLiteral object) {
if (objectLiterals == null) {
objectLiterals = new ArrayDeque<>(4);
}
objectLiterals.push(object);
}
void removeLiteral(ObjectLiteral object) {
objectLiterals.removeFirstOccurrence(object);
}
}
private static class FunctionContext extends ScopeContext implements FunctionScope {
final ScopeContext enclosing;
Set<String> parameterNames = null;
boolean directEval = false;
FunctionContext(ParseContext context) {
super(null);
this.enclosing = context.parent.scopeContext;
}
private boolean isStrict() {
if (node instanceof FunctionNode) {
return IsStrict((FunctionNode) node);
} else {
assert node instanceof Script;
return IsStrict((Script) node);
}
}
@Override
public ScopeContext getEnclosingScope() {
return enclosing;
}
@Override
public boolean isDynamic() {
return directEval && !isStrict();
}
@Override
public Set<String> parameterNames() {
return parameterNames;
}
@Override
public Set<String> lexicallyDeclaredNames() {
return lexDeclaredNames;
}
@Override
public List<Declaration> lexicallyScopedDeclarations() {
return lexScopedDeclarations;
}
@Override
public Set<String> varDeclaredNames() {
return varDeclaredNames;
}
@Override
public List<StatementListItem> varScopedDeclarations() {
return varScopedDeclarations;
}
}
private static class BlockContext extends ScopeContext implements BlockScope {
final boolean dynamic;
BlockContext(ScopeContext parent, boolean dynamic) {
super(parent);
this.dynamic = dynamic;
}
@Override
public Set<String> lexicallyDeclaredNames() {
return lexDeclaredNames;
}
@Override
public List<Declaration> lexicallyScopedDeclarations() {
return lexScopedDeclarations;
}
@Override
public boolean isDynamic() {
return dynamic;
}
}
private abstract static class ScopeContext implements Scope {
final ScopeContext parent;
ScopedNode node = null;
HashSet<String> varDeclaredNames = null;
HashSet<String> lexDeclaredNames = null;
List<StatementListItem> varScopedDeclarations = null;
List<Declaration> lexScopedDeclarations = null;
ScopeContext(ScopeContext parent) {
this.parent = parent;
}
@Override
public Scope getParent() {
return parent;
}
@Override
public ScopedNode getNode() {
return node;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("var: ").append(varDeclaredNames != null ? varDeclaredNames : "<null>");
sb.append("\t");
sb.append("lex: ").append(lexDeclaredNames != null ? lexDeclaredNames : "<null>");
return sb.toString();
}
boolean isTopLevel() {
return (parent == null);
}
boolean addVarDeclaredName(String name) {
if (varDeclaredNames == null) {
varDeclaredNames = new HashSet<>();
}
varDeclaredNames.add(name);
return (lexDeclaredNames == null || !lexDeclaredNames.contains(name));
}
boolean addLexDeclaredName(String name) {
if (lexDeclaredNames == null) {
lexDeclaredNames = new HashSet<>();
}
return lexDeclaredNames.add(name)
&& (varDeclaredNames == null || !varDeclaredNames.contains(name));
}
void addVarScopedDeclaration(StatementListItem decl) {
if (varScopedDeclarations == null) {
varScopedDeclarations = newSmallList();
}
varScopedDeclarations.add(decl);
}
void addLexScopedDeclaration(Declaration decl) {
if (lexScopedDeclarations == null) {
lexScopedDeclarations = newSmallList();
}
lexScopedDeclarations.add(decl);
}
}
private static class LabelContext {
final LabelContext parent;
final StatementType type;
final Set<String> labelSet;
final EnumSet<Abrupt> abrupts = EnumSet.noneOf(Abrupt.class);
LabelContext(LabelContext parent, StatementType type, Set<String> labelSet) {
this.parent = parent;
this.type = type;
this.labelSet = labelSet;
}
void mark(Abrupt abrupt) {
abrupts.add(abrupt);
}
}
public enum Option {
Strict, FunctionCode, LocalScope, DirectEval, EvalScript
}
public Parser(String sourceFile, int sourceLine) {
this(sourceFile, sourceLine, EnumSet.noneOf(Option.class));
}
public Parser(String sourceFile, int sourceLine, EnumSet<Option> options) {
this.sourceFile = sourceFile;
this.sourceLine = sourceLine;
this.options = options;
context = new ParseContext();
context.strictMode = options.contains(Option.Strict) ? StrictMode.Strict
: StrictMode.NonStrict;
}
private ParseContext newContext(ContextKind kind) {
return context = new ParseContext(context, kind);
}
private ParseContext restoreContext() {
if (context.parent.strictError == null) {
context.parent.strictError = context.strictError;
}
return context = context.parent;
}
private BlockContext enterWithContext() {
BlockContext cx = new BlockContext(context.scopeContext, true);
context.scopeContext = cx;
return cx;
}
private ScopeContext exitWithContext() {
return exitScopeContext();
}
private BlockContext enterBlockContext() {
BlockContext cx = new BlockContext(context.scopeContext, false);
context.scopeContext = cx;
return cx;
}
private BlockContext reenterBlockContext(BlockContext cx) {
context.scopeContext = cx;
return cx;
}
private ScopeContext exitBlockContext() {
return exitScopeContext();
}
private ScopeContext exitScopeContext() {
ScopeContext scope = context.scopeContext;
ScopeContext parent = scope.parent;
assert parent != null : "exitScopeContext() on top-level";
HashSet<String> varDeclaredNames = scope.varDeclaredNames;
if (varDeclaredNames != null) {
scope.varDeclaredNames = null;
for (String name : varDeclaredNames) {
addVarDeclaredName(parent, name);
}
}
return context.scopeContext = parent;
}
private void addFunctionDecl(FunctionDeclaration funDecl) {
addFunctionDecl(funDecl, funDecl.getIdentifier());
}
private void addGeneratorDecl(GeneratorDeclaration genDecl) {
// TODO: for now same rules as function declaration
addFunctionDecl(genDecl, genDecl.getIdentifier());
}
private void addFunctionDecl(Declaration decl, BindingIdentifier bindingIdentifier) {
String name = BoundName(bindingIdentifier);
ScopeContext parentScope = context.parent.scopeContext;
if (parentScope.isTopLevel()) {
// top-level function declaration
parentScope.addVarScopedDeclaration(decl);
if (!parentScope.addVarDeclaredName(name)) {
reportSyntaxError(Messages.Key.VariableRedeclaration, name);
}
} else {
// block-scoped function declaration
parentScope.addLexScopedDeclaration(decl);
if (!parentScope.addLexDeclaredName(name)) {
reportSyntaxError(Messages.Key.VariableRedeclaration, name);
}
}
}
private void addLexScopedDeclaration(Declaration decl) {
context.scopeContext.addLexScopedDeclaration(decl);
}
private void addVarScopedDeclaration(VariableStatement decl) {
context.funContext.addVarScopedDeclaration(decl);
}
private void addVarDeclaredName(ScopeContext scope, String name) {
if (!scope.addVarDeclaredName(name)) {
reportSyntaxError(Messages.Key.VariableRedeclaration, name);
}
}
private void addLexDeclaredName(ScopeContext scope, String name) {
if (!scope.addLexDeclaredName(name)) {
reportSyntaxError(Messages.Key.VariableRedeclaration, name);
}
}
/**
* <strong>[12.1] Block</strong>
* <p>
* Static Semantics: Early Errors<br>
* <ul>
* <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also
* occurs in the VarDeclaredNames of StatementList.
* </ul>
*/
@SuppressWarnings("unused")
private void addVarDeclaredName(Binding binding) {
if (binding instanceof BindingIdentifier) {
addVarDeclaredName((BindingIdentifier) binding);
} else {
assert binding instanceof BindingPattern;
addVarDeclaredName((BindingPattern) binding);
}
}
private void addVarDeclaredName(BindingIdentifier bindingIdentifier) {
String name = BoundName(bindingIdentifier);
addVarDeclaredName(context.scopeContext, name);
}
private void addVarDeclaredName(BindingPattern bindingPattern) {
for (String name : BoundNames(bindingPattern)) {
addVarDeclaredName(context.scopeContext, name);
}
}
/**
* <strong>[12.1] Block</strong>
* <p>
* Static Semantics: Early Errors<br>
* <ul>
* <li>It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any
* duplicate entries.
* <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also
* occurs in the VarDeclaredNames of StatementList.
* </ul>
*/
private void addLexDeclaredName(Binding binding) {
if (binding instanceof BindingIdentifier) {
addLexDeclaredName((BindingIdentifier) binding);
} else {
assert binding instanceof BindingPattern;
addLexDeclaredName((BindingPattern) binding);
}
}
private void addLexDeclaredName(BindingIdentifier bindingIdentifier) {
String name = BoundName(bindingIdentifier);
addLexDeclaredName(context.scopeContext, name);
}
private void addLexDeclaredName(BindingPattern bindingPattern) {
for (String name : BoundNames(bindingPattern)) {
addLexDeclaredName(context.scopeContext, name);
}
}
private void removeLexDeclaredName(ScopeContext scope, Binding binding) {
HashSet<String> lexDeclaredNames = scope.lexDeclaredNames;
if (binding instanceof BindingIdentifier) {
BindingIdentifier bindingIdentifier = (BindingIdentifier) binding;
String name = BoundName(bindingIdentifier);
lexDeclaredNames.remove(name);
} else {
assert binding instanceof BindingPattern;
BindingPattern bindingPattern = (BindingPattern) binding;
for (String name : BoundNames(bindingPattern)) {
lexDeclaredNames.remove(name);
}
}
}
private LabelContext enterLabelled(StatementType type, Set<String> labelSet) {
LabelContext cx = context.labels = new LabelContext(context.labels, type, labelSet);
if (!labelSet.isEmpty() && context.labelSet == null) {
context.labelSet = new HashMap<>();
}
for (String label : labelSet) {
if (context.labelSet.containsKey(label)) {
reportSyntaxError(Messages.Key.DuplicateLabel, label);
}
context.labelSet.put(label, cx);
}
return cx;
}
private LabelContext exitLabelled() {
for (String label : context.labels.labelSet) {
context.labelSet.remove(label);
}
return context.labels = context.labels.parent;
}
private LabelContext enterIteration(Set<String> labelSet) {
return enterLabelled(StatementType.Iteration, labelSet);
}
private void exitIteration() {
exitLabelled();
}
private LabelContext enterBreakable(Set<String> labelSet) {
return enterLabelled(StatementType.Breakable, labelSet);
}
private void exitBreakable() {
exitLabelled();
}
private LabelContext findContinueTarget(String label) {
for (LabelContext cx = context.labels; cx != null; cx = cx.parent) {
if (label == null ? cx.type == StatementType.Iteration : cx.labelSet.contains(label)) {
return cx;
}
}
return null;
}
private LabelContext findBreakTarget(String label) {
for (LabelContext cx = context.labels; cx != null; cx = cx.parent) {
if (label == null || cx.labelSet.contains(label)) {
return cx;
}
}
return null;
}
private static <T> List<T> newSmallList() {
return new SmallArrayList<>();
}
private static <T> List<T> newList() {
return new SmallArrayList<>();
}
private static <T> List<T> merge(List<T> list1, List<T> list2) {
if (!(list1.isEmpty() || list2.isEmpty())) {
List<T> merged = new ArrayList<>();
merged.addAll(list1);
merged.addAll(list2);
return merged;
}
return list1.isEmpty() ? list2 : list1;
}
private ParserException reportException(ParserException exception) {
throw exception;
}
private ParserException reportTokenMismatch(Token expected, Token actual) {
if (actual == Token.EOF) {
throw new ParserEOFException(Messages.Key.UnexpectedToken, ts.getLine(),
actual.toString(), expected.toString());
}
throw new ParserException(ExceptionType.SyntaxError, ts.getLine(),
Messages.Key.UnexpectedToken, actual.toString(), expected.toString());
}
private ParserException reportTokenMismatch(String expected, Token actual) {
if (actual == Token.EOF) {
throw new ParserEOFException(Messages.Key.UnexpectedToken, ts.getLine(),
actual.toString(), expected);
}
throw new ParserException(ExceptionType.SyntaxError, ts.getLine(),
Messages.Key.UnexpectedToken, actual.toString(), expected);
}
private static ParserException reportError(ExceptionType type, int line,
Messages.Key messageKey, String... args) {
throw new ParserException(type, line, messageKey, args);
}
private static ParserException reportSyntaxError(Messages.Key messageKey, int line,
String... args) {
throw reportError(ExceptionType.SyntaxError, line, messageKey, args);
}
private ParserException reportSyntaxError(Messages.Key messageKey, String... args) {
throw reportError(ExceptionType.SyntaxError, ts.getLine(), messageKey, args);
}
private ParserException reportReferenceError(Messages.Key messageKey, String... args) {
throw reportError(ExceptionType.ReferenceError, ts.getLine(), messageKey, args);
}
private void reportStrictModeError(ExceptionType type, int line, Messages.Key messageKey,
String... args) {
if (context.strictMode == StrictMode.Unknown) {
if (context.strictError == null) {
context.strictError = new ParserException(type, line, messageKey, args);
}
} else if (context.strictMode == StrictMode.Strict) {
reportError(type, line, messageKey, args);
}
}
private void reportStrictModeSyntaxError(Messages.Key messageKey, int line, String... args) {
reportStrictModeError(ExceptionType.SyntaxError, line, messageKey, args);
}
void reportStrictModeSyntaxError(Messages.Key messageKey, String... args) {
reportStrictModeError(ExceptionType.SyntaxError, ts.getLine(), messageKey, args);
}
void reportStrictModeReferenceError(Messages.Key messageKey, String... args) {
reportStrictModeError(ExceptionType.ReferenceError, ts.getLine(), messageKey, args);
}
/**
* Peeks the next token in the token-stream
*/
private Token peek() {
return ts.peekToken();
}
/**
* Checks whether the next token in the token-stream is equal to the input token
*/
private boolean LOOKAHEAD(Token token) {
return ts.peekToken() == token;
}
/**
* Returns the current token in the token-stream
*/
private Token token() {
return ts.currentToken();
}
/**
* Consumes the current token in the token-stream and advances the stream to the next token
*/
private void consume(Token tok) {
if (tok != token())
reportTokenMismatch(tok, token());
Token next = ts.nextToken();
if (DEBUG)
System.out.printf("consume(%s) -> %s\n", tok, next);
}
/**
* Consumes the current token in the token-stream and advances the stream to the next token
*/
private void consume(String name) {
String string = ts.getString();
consume(Token.NAME);
if (!name.equals(string))
reportSyntaxError(Messages.Key.UnexpectedName, string, name);
}
public Script parse(CharSequence source) throws ParserException {
if (ts != null)
throw new IllegalStateException();
ts = new TokenStream(this, new StringTokenStreamInput(source), sourceLine);
return script();
}
public Script parseFunction(CharSequence formals, CharSequence bodyText) throws ParserException {
if (ts != null)
throw new IllegalStateException();
newContext(ContextKind.Script);
try {
applyStrictMode(false);
FunctionExpression function;
newContext(ContextKind.Function);
try {
ts = new TokenStream(this, new StringTokenStreamInput(formals), sourceLine);
ts.init();
FormalParameterList parameters = formalParameterList(Token.EOF);
if (token() != Token.EOF) {
reportSyntaxError(Messages.Key.InvalidFormalParameterList);
}
if (ts.position() != formals.length()) {
// more input after last token (whitespace, comments), add newline to handle
// last token is single-line comment case
formals = formals + "\n";
}
ts = new TokenStream(this, new StringTokenStreamInput(bodyText), sourceLine);
ts.init();
List<StatementListItem> statements = functionBody(Token.EOF);
if (token() != Token.EOF) {
reportSyntaxError(Messages.Key.InvalidFunctionBody);
}
String header = String.format("function anonymous (%s) ", formals);
String body = String.format("\n%s\n", bodyText);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
function = new FunctionExpression(scope, "anonymous", parameters, statements,
header, body);
scope.node = function;
function = inheritStrictness(function);
} finally {
restoreContext();
}
boolean strict = (context.strictMode == StrictMode.Strict);
List<StatementListItem> body = newSmallList();
body.add(new ExpressionStatement(function));
FunctionContext scope = context.funContext;
Script script = new Script(sourceFile, scope, body, options, strict);
scope.node = script;
return script;
} finally {
restoreContext();
}
}
public Script parseGenerator(CharSequence formals, CharSequence bodyText)
throws ParserException {
if (ts != null)
throw new IllegalStateException();
newContext(ContextKind.Script);
try {
applyStrictMode(false);
GeneratorExpression generator;
newContext(ContextKind.Generator);
try {
ts = new TokenStream(this, new StringTokenStreamInput(formals), sourceLine);
ts.init();
FormalParameterList parameters = formalParameterList(Token.EOF);
if (token() != Token.EOF) {
reportSyntaxError(Messages.Key.InvalidFormalParameterList);
}
if (ts.position() != formals.length()) {
// more input after last token (whitespace, comments), add newline to handle
// last token is single-line comment case
formals = formals + "\n";
}
ts = new TokenStream(this, new StringTokenStreamInput(bodyText), sourceLine);
ts.init();
List<StatementListItem> statements = functionBody(Token.EOF);
if (token() != Token.EOF) {
reportSyntaxError(Messages.Key.InvalidFunctionBody);
}
String header = String.format("function* anonymous (%s) ", formals);
String body = String.format("\n%s\n", bodyText);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
generator = new GeneratorExpression(scope, "anonymous", parameters, statements,
header, body);
scope.node = generator;
generator = inheritStrictness(generator);
} finally {
restoreContext();
}
boolean strict = (context.strictMode == StrictMode.Strict);
List<StatementListItem> body = newSmallList();
body.add(new ExpressionStatement(generator));
FunctionContext scope = context.funContext;
Script script = new Script(sourceFile, scope, body, options, strict);
scope.node = script;
return script;
} finally {
restoreContext();
}
}
/**
* <strong>[14.1] Script</strong>
*
* <pre>
* Script :
* ScriptBody<sub>opt</sub>
* ScriptBody :
* OuterStatementList
* </pre>
*/
private Script script() {
newContext(ContextKind.Script);
try {
ts.init();
List<StatementListItem> prologue = directivePrologue();
List<StatementListItem> body = outerStatementList();
boolean strict = (context.strictMode == StrictMode.Strict);
FunctionContext scope = context.funContext;
Script script = new Script(sourceFile, scope, merge(prologue, body), options, strict);
scope.node = script;
return script;
} finally {
restoreContext();
}
}
/**
* <strong>[14.1] Script</strong>
*
* <pre>
* OuterStatementList :
* OuterItem
* OuterStatementList OuterItem
* OuterItem :
* ModuleDeclaration
* ImportDeclaration
* StatementListItem
* </pre>
*/
private List<StatementListItem> outerStatementList() {
List<StatementListItem> list = newList();
while (token() != Token.EOF) {
if (MODULES_ENABLED) {
// TODO: implement modules
if (token() == Token.IMPORT) {
importDeclaration();
} else if (token() == Token.NAME && "module".equals(getName(token()))
&& peek() == Token.STRING && !ts.hasNextLineTerminator()) {
moduleDeclaration();
} else {
list.add(statementListItem());
}
} else {
list.add(statementListItem());
}
}
return list;
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ImportDeclaration ::= "import" ImportClause ("," ImportClause)* ";"
* </pre>
*/
private void importDeclaration() {
consume(Token.IMPORT);
importClause();
while (token() == Token.COMMA) {
consume(Token.COMMA);
importClause();
}
semicolon();
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ImportClause ::= StringLiteral "as" Identifier
* | ImportSpecifierSet "from" ModuleSpecifier
* </pre>
*/
private void importClause() {
if (token() == Token.STRING) {
moduleImport();
} else {
importSpecifierSet();
consume("from");
moduleSpecifier();
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ModuleImport ::= StringLiteral "as" Identifier
* </pre>
*/
private void moduleImport() {
consume(Token.STRING);
consume("as");
identifier();
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ImportSpecifierSet ::= "{" ImportSpecifier ("," ImportSpecifier)* "}"
* </pre>
*/
private void importSpecifierSet() {
consume(Token.LC);
importSpecifier();
while (token() != Token.RC) {
consume(Token.COMMA);
importSpecifier();
}
consume(Token.RC);
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ImportSpecifier ::= Identifier (":" Identifier)?
* </pre>
*/
private void importSpecifier() {
identifier();
if (token() == Token.COLON) {
consume(Token.COLON);
identifier();
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ModuleSpecifier ::= StringLiteral | Identifier
* </pre>
*/
private void moduleSpecifier() {
if (token() == Token.STRING) {
consume(Token.STRING);
} else {
identifier();
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ModuleDeclaration ::= "module" [NoNewline] StringLiteral "{" ModuleBody "}"
* </pre>
*/
private void moduleDeclaration() {
consume("module");
consume(Token.STRING);
consume(Token.LC);
moduleBody();
consume(Token.RC);
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ModuleBody ::= ModuleElement*
* ModuleElement ::= ScriptElement
* | ExportDeclaration
* </pre>
*/
private List<StatementListItem> moduleBody() {
List<StatementListItem> list = newList();
while (token() != Token.RC) {
if (token() == Token.IMPORT) {
importDeclaration();
} else if (token() == Token.EXPORT) {
exportDeclaration();
} else if (token() == Token.NAME && "module".equals(getName(token()))
&& peek() == Token.STRING && !ts.hasNextLineTerminator()) {
moduleDeclaration();
} else {
list.add(statementListItem());
}
}
return list;
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ExportDeclaration ::= "export" ExportSpecifierSet ("," ExportSpecifierSet)* ";"
* | "export" VariableDeclaration
* | "export" FunctionDeclaration
* | "export" "get" Identifier "(" ")" "{" FunctionBody "}"
* | "export" "set" Identifier "(" DestructuringPattern ")" "{" FunctionBody "}"
* | "export" "=" Expression ";"
* </pre>
*/
private void exportDeclaration() {
consume(Token.EXPORT);
switch (token()) {
case VAR:
variableStatement();
break;
case LET:
case CONST:
// "export" VariableDeclaration
lexicalDeclaration(true);
break;
case FUNCTION:
// "export" FunctionDeclaration
if (LOOKAHEAD(Token.MUL)) {
generatorDeclaration();
} else {
functionDeclaration();
}
break;
case CLASS:
classDeclaration();
break;
case ASSIGN:
// "export" "=" Expression ";"
consume(Token.ASSIGN);
expression(true);
semicolon();
break;
case NAME: {
// "export" "get" Identifier "(" ")" "{" FunctionBody "}"
// "export" "set" Identifier "(" DestructuringPattern ")" "{" FunctionBody "}"
String name = getName(Token.NAME);
if (("get".equals(name) || "set".equals(name)) && isIdentifier(peek())) {
if ("get".equals(name)) {
consume("get");
identifier();
consume(Token.LP);
consume(Token.RP);
consume(Token.LC);
functionBody(Token.RC);
consume(Token.RC);
} else {
consume("set");
identifier();
consume(Token.LP);
binding();
consume(Token.RP);
consume(Token.LC);
functionBody(Token.RC);
consume(Token.RC);
}
break;
}
// fall-through
}
default:
// "export" ExportSpecifierSet ("," ExportSpecifierSet)* ";"
exportSpecifierSet();
while (token() == Token.COMMA) {
exportSpecifierSet();
}
semicolon();
break;
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ExportSpecifierSet ::= "{" ExportSpecifier ("," ExportSpecifier)* "}"
* | Identifier
* | "*" ("from" Path)?
* ExportSpecifier ::= Identifier (":" Path)?
*
* Path ::= Identifier ("." Identifier)*
* </pre>
*/
private void exportSpecifierSet() {
switch (token()) {
case LC:
// "{" ExportSpecifier ("," ExportSpecifier)* "}"
consume(Token.LC);
exportSpecifier();
while (token() == Token.COMMA) {
consume(Token.COMMA);
exportSpecifier();
}
consume(Token.RC);
break;
case MUL:
// "*" ("from" Path)?
consume(Token.MUL);
if (token() == Token.NAME && "from".equals(getName(Token.NAME))) {
consume("from");
path();
}
break;
default:
identifier();
break;
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* ExportSpecifier ::= Identifier (":" Path)?
* </pre>
*/
private void exportSpecifier() {
identifier();
if (token() == Token.COLON) {
consume(Token.COLON);
path();
}
}
/**
* <strong>[14.2] Modules</strong>
*
* <pre>
* Path ::= Identifier ("." Identifier)*
* </pre>
*/
private void path() {
identifier();
while (token() == Token.DOT) {
consume(Token.DOT);
identifier();
}
}
/**
* <strong>[14.1] Directive Prologues and the Use Strict Directive</strong>
*
* <pre>
* DirectivePrologue :
* Directive<sub>opt</sub>
* Directive:
* StringLiteral ;
* Directive StringLiteral ;
* </pre>
*/
private List<StatementListItem> directivePrologue() {
List<StatementListItem> statements = newSmallList();
boolean strict = false;
directive: while (token() == Token.STRING) {
boolean hasEscape = ts.hasEscape(); // peek() may clear hasEscape flag
Token next = peek();
switch (next) {
case SEMI:
case RC:
case EOF:
break;
default:
if (ts.hasNextLineTerminator() && !isOperator(next)) {
break;
}
break directive;
}
// got a directive
String string = ts.getString();
if (!hasEscape && "use strict".equals(string)) {
strict = true;
}
consume(Token.STRING);
semicolon();
statements.add(new ExpressionStatement(new StringLiteral(string)));
}
applyStrictMode(strict);
return statements;
}
private static boolean isOperator(Token token) {
switch (token) {
case DOT:
case LB:
case LP:
case TEMPLATE:
case COMMA:
case HOOK:
case ASSIGN:
case ASSIGN_ADD:
case ASSIGN_BITAND:
case ASSIGN_BITOR:
case ASSIGN_BITXOR:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_MUL:
case ASSIGN_SHL:
case ASSIGN_SHR:
case ASSIGN_SUB:
case ASSIGN_USHR:
case OR:
case AND:
case BITAND:
case BITOR:
case BITXOR:
case EQ:
case NE:
case SHEQ:
case SHNE:
case LT:
case LE:
case GT:
case GE:
case INSTANCEOF:
case IN:
case SHL:
case SHR:
case USHR:
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
return true;
default:
return false;
}
}
private void applyStrictMode(boolean strict) {
if (strict) {
context.strictMode = StrictMode.Strict;
context.explicitStrict = true;
if (context.strictError != null) {
reportException(context.strictError);
}
} else {
if (context.strictMode == StrictMode.Unknown) {
context.strictMode = context.parent.strictMode;
}
}
}
private static FunctionNode.StrictMode toFunctionStrictness(boolean strict, boolean explicit) {
if (strict) {
if (explicit) {
return FunctionNode.StrictMode.ExplicitStrict;
}
return FunctionNode.StrictMode.ImplicitStrict;
}
return FunctionNode.StrictMode.NonStrict;
}
private <FUNCTION extends FunctionNode> FUNCTION inheritStrictness(FUNCTION function) {
if (context.strictMode != StrictMode.Unknown) {
boolean strict = (context.strictMode == StrictMode.Strict);
function.setStrictMode(toFunctionStrictness(strict, context.explicitStrict));
if (context.deferred != null) {
for (FunctionNode func : context.deferred) {
func.setStrictMode(toFunctionStrictness(strict, false));
}
context.deferred = null;
}
} else {
// this case only applies for functions with default parameters
assert context.parent.strictMode == StrictMode.Unknown;
ParseContext parent = context.parent;
if (parent.deferred == null) {
parent.deferred = newSmallList();
}
parent.deferred.add(function);
if (context.deferred != null) {
parent.deferred.addAll(context.deferred);
context.deferred = null;
}
}
return function;
}
/**
* <strong>[13.1] Function Definitions</strong>
*
* <pre>
* FunctionDeclaration :
* function BindingIdentifier ( FormalParameterList ) { FunctionBody }
* </pre>
*/
private FunctionDeclaration functionDeclaration() {
newContext(ContextKind.Function);
try {
consume(Token.FUNCTION);
int startFunction = ts.position() - "function".length();
BindingIdentifier identifier = bindingIdentifier();
consume(Token.LP);
FormalParameterList parameters = formalParameterList(Token.RP);
consume(Token.RP);
consume(Token.LC);
int startBody = ts.position();
List<StatementListItem> statements = functionBody(Token.RC);
consume(Token.RC);
int endFunction = ts.position() - 1;
String header = ts.range(startFunction, startBody - 1);
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
FunctionDeclaration function = new FunctionDeclaration(scope, identifier, parameters,
statements, header, body);
scope.node = function;
addFunctionDecl(function);
return inheritStrictness(function);
} finally {
restoreContext();
}
}
/**
* <strong>[13.1] Function Definitions</strong>
*
* <pre>
* FunctionExpression :
* function BindingIdentifier<sub>opt</sub> ( FormalParameterList ) { FunctionBody }
* </pre>
*/
private FunctionExpression functionExpression() {
newContext(ContextKind.Function);
try {
consume(Token.FUNCTION);
int startFunction = ts.position() - "function".length();
BindingIdentifier identifier = null;
if (token() != Token.LP) {
identifier = bindingIdentifier();
}
consume(Token.LP);
FormalParameterList parameters = formalParameterList(Token.RP);
consume(Token.RP);
consume(Token.LC);
int startBody = ts.position();
List<StatementListItem> statements = functionBody(Token.RC);
consume(Token.RC);
int endFunction = ts.position() - 1;
String header = ts.range(startFunction, startBody - 1);
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
FunctionExpression function = new FunctionExpression(scope, identifier, parameters,
statements, header, body);
scope.node = function;
return inheritStrictness(function);
} finally {
restoreContext();
}
}
/**
* <strong>[13.1] Function Definitions</strong>
*
* <pre>
* FormalParameterList :
* [empty]
* FunctionRestParameter
* FormalsList
* FormalsList, FunctionRestParameter
* FormalsList :
* FormalParameter
* FormalsList, FormalParameter
* FunctionRestParameter :
* ... BindingIdentifier
* FormalParameter :
* BindingElement
* </pre>
*/
private FormalParameterList formalParameterList(Token end) {
List<FormalParameter> formals = newSmallList();
boolean needComma = false;
while (token() != end) {
if (needComma) {
consume(Token.COMMA);
needComma = false;
} else if (token() == Token.TRIPLE_DOT) {
consume(Token.TRIPLE_DOT);
formals.add(new BindingRestElement(bindingIdentifierStrict()));
break;
} else {
formals.add(bindingElement());
needComma = true;
}
}
return new FormalParameterList(formals);
}
private static <T> T containsAny(Set<T> set, List<T> list) {
for (T element : list) {
if (set.contains(element)) {
return element;
}
}
return null;
}
private void formalParameterList_StaticSemantics(FormalParameterList parameters) {
// TODO: Early Error if intersection of BoundNames(FormalParameterList) and
// VarDeclaredNames(FunctionBody) is not the empty set
// => only for non-simple parameter list?
// => doesn't quite follow the current Function Declaration Instantiation algorithm
assert context.scopeContext == context.funContext;
FunctionContext scope = context.funContext;
HashSet<String> lexDeclaredNames = scope.lexDeclaredNames;
List<String> boundNames = BoundNames(parameters);
HashSet<String> names = new HashSet<>(boundNames);
scope.parameterNames = names;
boolean hasLexDeclaredNames = !(lexDeclaredNames == null || lexDeclaredNames.isEmpty());
boolean strict = (context.strictMode != StrictMode.NonStrict);
boolean simple = IsSimpleParameterList(parameters);
if (!strict && simple) {
if (hasLexDeclaredNames) {
String redeclared = containsAny(lexDeclaredNames, boundNames);
if (redeclared != null) {
reportSyntaxError(Messages.Key.FormalParameterRedeclaration, redeclared);
}
}
return;
}
boolean hasDuplicates = (boundNames.size() != names.size());
boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments"));
if (strict) {
if (hasDuplicates) {
reportStrictModeSyntaxError(Messages.Key.StrictModeDuplicateFormalParameter);
}
if (hasEvalOrArguments) {
reportStrictModeSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
}
if (!simple) {
if (hasDuplicates) {
reportSyntaxError(Messages.Key.StrictModeDuplicateFormalParameter);
}
if (hasEvalOrArguments) {
reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
}
if (hasLexDeclaredNames) {
String redeclared = containsAny(lexDeclaredNames, boundNames);
if (redeclared != null) {
reportSyntaxError(Messages.Key.FormalParameterRedeclaration, redeclared);
}
}
}
/**
* <strong>[13.1] Function Definitions</strong>
*
* <pre>
* FunctionBody :
* StatementList<sub>opt</sub>
* </pre>
*/
private List<StatementListItem> functionBody(Token end) {
// enable 'yield' if in generator
context.yieldAllowed = (context.kind == ContextKind.Generator);
List<StatementListItem> prologue = directivePrologue();
List<StatementListItem> body = statementList(end);
return merge(prologue, body);
}
/**
* <strong>[13.2] Arrow Function Definitions</strong>
*
* <pre>
* ArrowFunction :
* ArrowParameters => ConciseBody
* ArrowParameters :
* BindingIdentifier
* ( ArrowFormalParameterList )
* ArrowFormalParameterList :
* [empty]
* FunctionRestParameter
* CoverFormalsList
* CoverFormalsList , FunctionRestParameter
* ConciseBody :
* [LA ∉ { <b>{</b> }] AssignmentExpression
* { FunctionBody }
* CoverFormalsList :
* Expression
* </pre>
*/
private ArrowFunction arrowFunction() {
newContext(ContextKind.ArrowFunction);
try {
StringBuilder source = new StringBuilder();
source.append("function anonymous");
FormalParameterList parameters;
if (token() == Token.LP) {
consume(Token.LP);
int start = ts.position() - 1;
parameters = formalParameterList(Token.RP);
consume(Token.RP);
source.append(ts.range(start, ts.position()));
} else {
BindingIdentifier identifier = bindingIdentifier();
FormalParameter parameter = new BindingElement(identifier, null);
parameters = new FormalParameterList(singletonList(parameter));
source.append('(').append(identifier.getName()).append(')');
}
consume(Token.ARROW);
if (token() == Token.LC) {
consume(Token.LC);
int startBody = ts.position();
List<StatementListItem> statements = functionBody(Token.RC);
consume(Token.RC);
int endFunction = ts.position() - 1;
String header = source.toString();
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
ArrowFunction function = new ArrowFunction(scope, parameters, statements, header,
body);
scope.node = function;
return inheritStrictness(function);
} else {
// need to call manually b/c functionBody() isn't used here
applyStrictMode(false);
int startBody = ts.position();
Expression expression = assignmentExpression(true);
int endFunction = ts.position();
String header = source.toString();
String body = "return " + ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
ArrowFunction function = new ArrowFunction(scope, parameters, expression, header,
body);
scope.node = function;
return inheritStrictness(function);
}
} finally {
restoreContext();
}
}
/**
* <strong>[13.3] Method Definitions</strong>
*
* <pre>
* MethodDefinition :
* PropertyName ( FormalParameterList ) { FunctionBody }
* * PropertyName ( FormalParameterList ) { FunctionBody }
* get PropertyName ( ) { FunctionBody }
* set PropertyName ( PropertySetParameterList ) { FunctionBody }
* PropertySetParameterList :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private MethodDefinition methodDefinition(boolean alwaysStrict) {
MethodType type = methodType();
newContext(type != MethodType.Generator ? ContextKind.Function : ContextKind.Generator);
if (alwaysStrict) {
context.strictMode = StrictMode.Strict;
}
try {
PropertyName propertyName;
FormalParameterList parameters;
List<StatementListItem> statements;
int startFunction, startBody, endFunction;
switch (type) {
case Getter:
consume(Token.NAME);
propertyName = propertyName();
consume(Token.LP);
startFunction = ts.position() - 1;
parameters = new FormalParameterList(Collections.<FormalParameter> emptyList());
consume(Token.RP);
consume(Token.LC);
startBody = ts.position();
statements = functionBody(Token.RC);
consume(Token.RC);
endFunction = ts.position() - 1;
break;
case Setter:
consume(Token.NAME);
propertyName = propertyName();
consume(Token.LP);
startFunction = ts.position() - 1;
FormalParameter setParameter = new BindingElement(binding(), null);
parameters = new FormalParameterList(singletonList(setParameter));
consume(Token.RP);
consume(Token.LC);
startBody = ts.position();
statements = functionBody(Token.RC);
consume(Token.RC);
endFunction = ts.position() - 1;
break;
case Generator:
consume(Token.MUL);
case Function:
default:
propertyName = propertyName();
consume(Token.LP);
startFunction = ts.position() - 1;
parameters = formalParameterList(Token.RP);
consume(Token.RP);
consume(Token.LC);
startBody = ts.position();
statements = functionBody(Token.RC);
consume(Token.RC);
endFunction = ts.position() - 1;
break;
}
String header = ts.range(startFunction, startBody - 1);
if (type != MethodType.Generator) {
header = "function " + header;
} else {
header = "function* " + header;
}
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
MethodDefinition method = new MethodDefinition(scope, type, propertyName, parameters,
statements, context.hasSuperReference(), header, body);
scope.node = method;
return inheritStrictness(method);
} finally {
restoreContext();
}
}
private MethodType methodType() {
Token tok = token();
if (tok == Token.MUL) {
return MethodType.Generator;
}
if (tok == Token.NAME) {
String name = getName(tok);
if (("get".equals(name) || "set".equals(name)) && isPropertyName(peek())) {
return "get".equals(name) ? MethodType.Getter : MethodType.Setter;
}
}
return MethodType.Function;
}
private boolean isPropertyName(Token token) {
return token == Token.STRING || token == Token.NUMBER || isIdentifierName(token);
}
/**
* <strong>[13.4] Generator Definitions</strong>
*
* <pre>
* GeneratorDeclaration :
* function * BindingIdentifier ( FormalParameterList ) { FunctionBody }
* </pre>
*/
private GeneratorDeclaration generatorDeclaration() {
newContext(ContextKind.Generator);
try {
consume(Token.FUNCTION);
int startFunction = ts.position() - "function".length();
consume(Token.MUL);
BindingIdentifier identifier = bindingIdentifier();
consume(Token.LP);
FormalParameterList parameters = formalParameterList(Token.RP);
consume(Token.RP);
consume(Token.LC);
int startBody = ts.position();
List<StatementListItem> statements = functionBody(Token.RC);
consume(Token.RC);
int endFunction = ts.position() - 1;
String header = ts.range(startFunction, startBody - 1);
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
GeneratorDeclaration generator = new GeneratorDeclaration(scope, identifier,
parameters, statements, header, body);
scope.node = generator;
addGeneratorDecl(generator);
return inheritStrictness(generator);
} finally {
restoreContext();
}
}
/**
* <strong>[13.4] Generator Definitions</strong>
*
* <pre>
* GeneratorExpression :
* function * BindingIdentifier<sub>opt</sub> ( FormalParameterList ) { FunctionBody }
* </pre>
*/
private GeneratorExpression generatorExpression() {
newContext(ContextKind.Generator);
try {
consume(Token.FUNCTION);
int startFunction = ts.position() - "function".length();
consume(Token.MUL);
BindingIdentifier identifier = null;
if (token() != Token.LP) {
identifier = bindingIdentifier();
}
consume(Token.LP);
FormalParameterList parameters = formalParameterList(Token.RP);
consume(Token.RP);
consume(Token.LC);
int startBody = ts.position();
List<StatementListItem> statements = functionBody(Token.RC);
consume(Token.RC);
int endFunction = ts.position() - 1;
String header = ts.range(startFunction, startBody - 1);
String body = ts.range(startBody, endFunction);
formalParameterList_StaticSemantics(parameters);
FunctionContext scope = context.funContext;
GeneratorExpression generator = new GeneratorExpression(scope, identifier, parameters,
statements, header, body);
scope.node = generator;
return inheritStrictness(generator);
} finally {
restoreContext();
}
}
/**
* <strong>[13.4] Generator Definitions</strong>
*
* <pre>
* YieldExpression :
* yield YieldDelegator<sub>opt</sub> AssignmentExpression
* YieldDelegator :
* *
* </pre>
*/
private YieldExpression yieldExpression() {
if (!context.yieldAllowed) {
reportSyntaxError(Messages.Key.InvalidYieldStatement);
}
consume(Token.YIELD);
boolean delegatedYield = false;
if (token() == Token.MUL) {
consume(Token.MUL);
delegatedYield = true;
}
if (token() == Token.YIELD) {
// disallow `yield yield x` but allow `yield (yield x)`
// TODO: track spec changes, syntax not yet settled
reportSyntaxError(Messages.Key.InvalidYieldStatement);
}
// TODO: NoLineTerminator() restriction or context dependent?
Expression expr;
if (delegatedYield || !(token() == Token.SEMI || token() == Token.RC)) {
expr = assignmentExpression(true);
} else {
// extension: allow Spidermonkey syntax
expr = null;
}
return new YieldExpression(delegatedYield, expr);
}
/**
* <strong>[13.5] Class Definitions</strong>
*
* <pre>
* ClassDeclaration :
* class BindingIdentifier ClassTail
* ClassTail :
* ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> }
* ClassHeritage :
* extends AssignmentExpression
* </pre>
*/
private ClassDeclaration classDeclaration() {
consume(Token.CLASS);
BindingIdentifier name = bindingIdentifierStrict();
Expression heritage = null;
if (token() == Token.EXTENDS) {
consume(Token.EXTENDS);
heritage = assignmentExpression(true);
}
consume(Token.LC);
List<MethodDefinition> staticMethods = newList();
List<MethodDefinition> prototypeMethods = newList();
classBody(staticMethods, prototypeMethods);
consume(Token.RC);
ClassDeclaration decl = new ClassDeclaration(name, heritage, staticMethods,
prototypeMethods);
addLexDeclaredName(name);
addLexScopedDeclaration(decl);
return decl;
}
/**
* <strong>[13.5] Class Definitions</strong>
*
* <pre>
* ClassExpression :
* class BindingIdentifier<sub>opt</sub> ClassTail
* ClassTail :
* ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> }
* ClassHeritage :
* extends AssignmentExpression
* </pre>
*/
private ClassExpression classExpression() {
consume(Token.CLASS);
BindingIdentifier name = null;
if (token() != Token.EXTENDS && token() != Token.LC) {
name = bindingIdentifierStrict();
}
Expression heritage = null;
if (token() == Token.EXTENDS) {
consume(Token.EXTENDS);
heritage = assignmentExpression(true);
}
consume(Token.LC);
if (name != null) {
enterBlockContext();
addLexDeclaredName(name);
}
List<MethodDefinition> staticMethods = newList();
List<MethodDefinition> prototypeMethods = newList();
classBody(staticMethods, prototypeMethods);
if (name != null) {
exitBlockContext();
}
consume(Token.RC);
return new ClassExpression(name, heritage, staticMethods, prototypeMethods);
}
/**
* <strong>[13.5] Class Definitions</strong>
*
* <pre>
* ClassBody :
* ClassElementList
* ClassElementList :
* ClassElement
* ClassElementList ClassElement
* ClassElement :
* MethodDefinition
* static MethodDefinition
* ;
* </pre>
*/
private void classBody(List<MethodDefinition> staticMethods,
List<MethodDefinition> prototypeMethods) {
while (token() != Token.RC) {
if (token() == Token.SEMI) {
consume(Token.SEMI);
} else if (token() == Token.STATIC) {
consume(Token.STATIC);
staticMethods.add(methodDefinition(true));
} else {
prototypeMethods.add(methodDefinition(true));
}
}
classBody_StaticSemantics(staticMethods, true);
classBody_StaticSemantics(prototypeMethods, false);
}
private void classBody_StaticSemantics(List<MethodDefinition> defs, boolean isStatic) {
final int VALUE = 0, GETTER = 1, SETTER = 2;
Map<String, Integer> values = new HashMap<>();
for (MethodDefinition def : defs) {
String key = PropName(def);
if (isStatic) {
if ("prototype".equals(key)) {
reportSyntaxError(Messages.Key.InvalidPrototypeMethod);
}
} else {
if ("constructor".equals(key) && SpecialMethod(def)) {
reportSyntaxError(Messages.Key.InvalidConstructorMethod);
}
}
MethodDefinition.MethodType type = def.getType();
final int kind = type == MethodType.Getter ? GETTER
: type == MethodType.Setter ? SETTER : VALUE;
if (values.containsKey(key)) {
int prev = values.get(key);
if (kind == VALUE) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key);
}
if (kind == GETTER && prev != SETTER) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key);
}
if (kind == SETTER && prev != GETTER) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key);
}
values.put(key, prev | kind);
} else {
values.put(key, kind);
}
}
}
/**
* <strong>[12] Statements</strong>
*
* <pre>
* Statement :
* BlockStatement
* VariableStatement
* EmptyStatement
* ExpressionStatement
* IfStatement
* BreakableStatement
* ContinueStatement
* BreakStatement
* ReturnStatement
* WithStatement
* LabelledStatement
* ThrowStatement
* TryStatement
* DebuggerStatement
*
* BreakableStatement :
* IterationStatement
* SwitchStatement
* </pre>
*/
private Statement statement() {
switch (token()) {
case LC:
return block(NO_INHERITED_BINDING);
case VAR:
return variableStatement();
case SEMI:
return emptyStatement();
case IF:
return ifStatement();
case FOR:
return forStatement(EMPTY_LABEL_SET);
case WHILE:
return whileStatement(EMPTY_LABEL_SET);
case DO:
return doWhileStatement(EMPTY_LABEL_SET);
case CONTINUE:
return continueStatement();
case BREAK:
return breakStatement();
case RETURN:
return returnStatement();
case WITH:
return withStatement();
case SWITCH:
return switchStatement(EMPTY_LABEL_SET);
case THROW:
return throwStatement();
case TRY:
return tryStatement();
case DEBUGGER:
return debuggerStatement();
case NAME:
if (LOOKAHEAD(Token.COLON)) {
return labelledStatement();
}
default:
return expressionStatement();
}
}
/**
* <strong>[12.1] Block</strong>
*
* <pre>
* BlockStatement :
* Block
* Block :
* { StatementList<sub>opt</sub> }
* </pre>
*/
private BlockStatement block(Binding inherited) {
consume(Token.LC);
BlockContext scope = enterBlockContext();
if (inherited != null) {
addLexDeclaredName(inherited);
}
List<StatementListItem> list = statementList(Token.RC);
exitBlockContext();
consume(Token.RC);
BlockStatement block = new BlockStatement(scope, list);
scope.node = block;
return block;
}
/**
* <strong>[12.1] Block</strong>
*
* <pre>
* StatementList :
* StatementItem
* StatementList StatementListItem
* </pre>
*/
private List<StatementListItem> statementList(Token end) {
List<StatementListItem> list = newList();
while (token() != end) {
list.add(statementListItem());
}
return list;
}
/**
* <strong>[12.1] Block</strong>
*
* <pre>
* StatementListItem :
* Statement
* Declaration
* Declaration :
* FunctionDeclaration
* GeneratorDeclaration
* ClassDeclaration
* LexicalDeclaration
* </pre>
*/
private StatementListItem statementListItem() {
switch (token()) {
case FUNCTION:
if (LOOKAHEAD(Token.MUL)) {
return generatorDeclaration();
} else {
return functionDeclaration();
}
case CLASS:
return classDeclaration();
case LET:
case CONST:
return lexicalDeclaration(true);
default:
return statement();
}
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* LexicalDeclaration :
* LetOrConst BindingList ;
* LexicalDeclarationNoIn :
* LetOrConst BindingListNoIn
* LetOrConst :
* let
* const
* </pre>
*/
private LexicalDeclaration lexicalDeclaration(boolean allowIn) {
LexicalDeclaration.Type type;
if (token() == Token.LET) {
consume(Token.LET);
type = LexicalDeclaration.Type.Let;
} else {
consume(Token.CONST);
type = LexicalDeclaration.Type.Const;
}
List<LexicalBinding> list = bindingList((type == LexicalDeclaration.Type.Const), allowIn);
if (allowIn) {
semicolon();
}
LexicalDeclaration decl = new LexicalDeclaration(type, list);
addLexScopedDeclaration(decl);
return decl;
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* BindingList :
* LexicalBinding
* BindingList, LexicalBinding
* BindingListNoIn :
* LexicalBindingNoIn
* BindingListNoIn, LexicalBindingNoIn
* </pre>
*/
private List<LexicalBinding> bindingList(boolean isConst, boolean allowIn) {
List<LexicalBinding> list = newSmallList();
list.add(lexicalBinding(isConst, allowIn));
while (token() == Token.COMMA) {
consume(Token.COMMA);
list.add(lexicalBinding(isConst, allowIn));
}
return list;
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* LexicalBinding :
* BindingIdentifier Initialiser<sub>opt</sub>
* BindingPattern Initialiser
* LexicalBindingNoIn :
* BindingIdentifier InitialiserNoIn<sub>opt</sub>
* BindingPattern InitialiserNoIn
* </pre>
*/
private LexicalBinding lexicalBinding(boolean isConst, boolean allowIn) {
Binding binding;
Expression initialiser = null;
if (token() == Token.LC || token() == Token.LB) {
BindingPattern bindingPattern = bindingPattern();
addLexDeclaredName(bindingPattern);
if (allowIn) {
initialiser = initialiser(allowIn);
} else if (token() == Token.ASSIGN) {
// make initialiser optional if `allowIn == false`
initialiser = initialiser(allowIn);
}
binding = bindingPattern;
} else {
BindingIdentifier bindingIdentifier = bindingIdentifier();
addLexDeclaredName(bindingIdentifier);
if (token() == Token.ASSIGN) {
initialiser = initialiser(allowIn);
} else if (isConst && allowIn) {
// `allowIn == false` indicates for-loop, cf. validateFor{InOf}
reportSyntaxError(Messages.Key.ConstMissingInitialiser);
}
binding = bindingIdentifier;
}
return new LexicalBinding(binding, initialiser);
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* BindingIdentifier :
* Identifier
* </pre>
*/
private BindingIdentifier bindingIdentifier() {
String identifier = identifier();
if (context.strictMode != StrictMode.NonStrict) {
if ("arguments".equals(identifier) || "eval".equals(identifier)) {
reportStrictModeSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
}
return new BindingIdentifier(identifier);
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* BindingIdentifier :
* Identifier
* </pre>
*/
private BindingIdentifier bindingIdentifierStrict() {
String identifier = identifier();
if ("arguments".equals(identifier) || "eval".equals(identifier)) {
reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
return new BindingIdentifier(identifier);
}
/**
* <strong>[12.2.1] Let and Const Declarations</strong>
*
* <pre>
* Initialiser :
* = AssignmentExpression
* InitialiserNoIn :
* = AssignmentExpressionNoIn
* </pre>
*/
private Expression initialiser(boolean allowIn) {
consume(Token.ASSIGN);
return assignmentExpression(allowIn);
}
/**
* <strong>[12.2.2] Variable Statement</strong>
*
* <pre>
* VariableStatement :
* var VariableDeclarationList ;
* </pre>
*/
private VariableStatement variableStatement() {
consume(Token.VAR);
List<VariableDeclaration> decls = variableDeclarationList(true);
semicolon();
VariableStatement varStmt = new VariableStatement(decls);
addVarScopedDeclaration(varStmt);
return varStmt;
}
/**
* <strong>[12.2.2] Variable Statement</strong>
*
* <pre>
* VariableDeclarationList :
* VariableDeclaration
* VariableDeclarationList , VariableDeclaration
* VariableDeclarationListNoIn :
* VariableDeclarationNoIn
* VariableDeclarationListNoIn , VariableDeclarationNoIn
* </pre>
*/
private List<VariableDeclaration> variableDeclarationList(boolean allowIn) {
List<VariableDeclaration> list = newSmallList();
list.add(variableDeclaration(allowIn));
while (token() == Token.COMMA) {
consume(Token.COMMA);
list.add(variableDeclaration(allowIn));
}
return list;
}
/**
* <strong>[12.2.2] Variable Statement</strong>
*
* <pre>
* VariableDeclaration :
* BindingIdentifier Initialiser<sub>opt</sub>
* BindingPattern Initialiser
* VariableDeclarationNoIn :
* BindingIdentifier InitialiserNoIn<sub>opt</sub>
* BindingPattern InitialiserNoIn
* </pre>
*/
private VariableDeclaration variableDeclaration(boolean allowIn) {
Binding binding;
Expression initialiser = null;
if (token() == Token.LC || token() == Token.LB) {
BindingPattern bindingPattern = bindingPattern();
addVarDeclaredName(bindingPattern);
if (allowIn) {
initialiser = initialiser(allowIn);
} else if (token() == Token.ASSIGN) {
// make initialiser optional if `allowIn == false`
initialiser = initialiser(allowIn);
}
binding = bindingPattern;
} else {
BindingIdentifier bindingIdentifier = bindingIdentifier();
addVarDeclaredName(bindingIdentifier);
if (token() == Token.ASSIGN) {
initialiser = initialiser(allowIn);
}
binding = bindingIdentifier;
}
return new VariableDeclaration(binding, initialiser);
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* BindingPattern :
* ObjectBindingPattern
* ArrayBindingPattern
* </pre>
*/
private BindingPattern bindingPattern() {
if (token() == Token.LC) {
return objectBindingPattern();
} else {
return arrayBindingPattern();
}
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* ObjectBindingPattern :
* { }
* { BindingPropertyList }
* { BindingPropertyList , }
* BindingPropertyList :
* BindingProperty
* BindingPropertyList , BindingProperty
* BindingProperty :
* SingleNameBinding
* PropertyName : BindingElement
* BindingElement :
* SingleNameBinding
* BindingPattern Initialiser<sub>opt</sub>
* SingleNameBinding :
* BindingIdentifier Initialiser<sub>opt</sub>
* PropertyName :
* IdentifierName
* StringLiteral
* NumericLiteral
* </pre>
*/
private ObjectBindingPattern objectBindingPattern() {
List<BindingProperty> list = newSmallList();
consume(Token.LC);
if (token() != Token.RC) {
list.add(bindingProperty());
while (token() != Token.RC) {
consume(Token.COMMA);
list.add(bindingProperty());
}
}
consume(Token.RC);
objectBindingPattern_StaticSemantics(list);
return new ObjectBindingPattern(list);
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* BindingProperty :
* SingleNameBinding
* PropertyName : BindingElement
* BindingElement :
* SingleNameBinding
* BindingPattern Initialiser<sub>opt</sub>
* SingleNameBinding :
* BindingIdentifier Initialiser<sub>opt</sub>
* BindingIdentifier :
* Identifier
* </pre>
*/
private BindingProperty bindingProperty() {
if (LOOKAHEAD(Token.COLON)) {
PropertyName propertyName = propertyName();
consume(Token.COLON);
Binding binding;
if (token() == Token.LC) {
binding = objectBindingPattern();
} else if (token() == Token.LB) {
binding = arrayBindingPattern();
} else {
binding = bindingIdentifierStrict();
}
Expression initialiser = null;
if (token() == Token.ASSIGN) {
initialiser = initialiser(true);
}
return new BindingProperty(propertyName, binding, initialiser);
} else {
BindingIdentifier binding = bindingIdentifierStrict();
Expression initialiser = null;
if (token() == Token.ASSIGN) {
initialiser = initialiser(true);
}
return new BindingProperty(binding, initialiser);
}
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* ArrayBindingPattern :
* [ Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ]
* [ BindingElementList ]
* [ BindingElementList , Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ]
* BindingElementList :
* Elision<sub>opt</sub> BindingElement
* BindingElementList , Elision<sub>opt</sub> BindingElement
* BindingRestElement :
* ... BindingIdentifier
* </pre>
*/
private ArrayBindingPattern arrayBindingPattern() {
List<BindingElementItem> list = newSmallList();
consume(Token.LB);
boolean needComma = false;
Token tok;
while ((tok = token()) != Token.RB) {
if (needComma) {
consume(Token.COMMA);
needComma = false;
} else if (tok == Token.COMMA) {
consume(Token.COMMA);
list.add(new BindingElision());
} else if (tok == Token.TRIPLE_DOT) {
consume(Token.TRIPLE_DOT);
list.add(new BindingRestElement(bindingIdentifierStrict()));
break;
} else {
list.add(bindingElementStrict());
needComma = true;
}
}
consume(Token.RB);
arrayBindingPattern_StaticSemantics(list);
return new ArrayBindingPattern(list);
}
/**
* <pre>
* Binding :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private Binding binding() {
switch (token()) {
case LC:
return objectBindingPattern();
case LB:
return arrayBindingPattern();
default:
return bindingIdentifier();
}
}
/**
* <pre>
* Binding :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private Binding bindingStrict() {
switch (token()) {
case LC:
return objectBindingPattern();
case LB:
return arrayBindingPattern();
default:
return bindingIdentifierStrict();
}
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* BindingElement :
* SingleNameBinding
* BindingPattern Initialiser<sub>opt</sub>
* SingleNameBinding :
* BindingIdentifier Initialiser<sub>opt</sub>
* </pre>
*/
private BindingElement bindingElement() {
Binding binding = binding();
Expression initialiser = null;
if (token() == Token.ASSIGN) {
initialiser = initialiser(true);
}
return new BindingElement(binding, initialiser);
}
/**
* <strong>[12.2.4] Destructuring Binding Patterns</strong>
*
* <pre>
* BindingElement :
* SingleNameBinding
* BindingPattern Initialiser<sub>opt</sub>
* SingleNameBinding :
* BindingIdentifier Initialiser<sub>opt</sub>
* </pre>
*/
private BindingElement bindingElementStrict() {
Binding binding = bindingStrict();
Expression initialiser = null;
if (token() == Token.ASSIGN) {
initialiser = initialiser(true);
}
return new BindingElement(binding, initialiser);
}
private static String BoundName(BindingIdentifier binding) {
return binding.getName();
}
private static String BoundName(BindingRestElement element) {
return element.getBindingIdentifier().getName();
}
private void objectBindingPattern_StaticSemantics(List<BindingProperty> list) {
for (BindingProperty property : list) {
// BindingProperty : PropertyName ':' BindingElement
// BindingProperty : BindingIdentifier Initialiser<opt>
Binding binding = property.getBinding();
if (binding instanceof BindingIdentifier) {
String name = BoundName(((BindingIdentifier) binding));
if ("arguments".equals(name) || "eval".equals(name)) {
reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
} else {
assert binding instanceof BindingPattern;
assert property.getPropertyName() != null;
// already done implicitly
// objectBindingPattern_StaticSemantics(((ObjectBindingPattern) binding).getList());
// arrayBindingPattern_StaticSemantics(((ArrayBindingPattern)
// binding).getElements());
}
}
}
private void arrayBindingPattern_StaticSemantics(List<BindingElementItem> list) {
for (BindingElementItem element : list) {
if (element instanceof BindingElement) {
Binding binding = ((BindingElement) element).getBinding();
if (binding instanceof ArrayBindingPattern) {
// already done implicitly
// arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) binding)
// .getElements());
} else if (binding instanceof ObjectBindingPattern) {
// already done implicitly
// objectBindingPattern_StaticSemantics(((ObjectBindingPattern)
// binding).getList());
} else {
assert (binding instanceof BindingIdentifier);
String name = BoundName(((BindingIdentifier) binding));
if ("arguments".equals(name) || "eval".equals(name)) {
reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
}
} else if (element instanceof BindingRestElement) {
String name = BoundName(((BindingRestElement) element));
if ("arguments".equals(name) || "eval".equals(name)) {
reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier);
}
} else {
assert element instanceof BindingElision;
}
}
}
/**
* <strong>[12.3] Empty Statement</strong>
*
* <pre>
* EmptyStatement:
* ;
* </pre>
*/
private EmptyStatement emptyStatement() {
consume(Token.SEMI);
return new EmptyStatement();
}
/**
* <strong>[12.4] Expression Statement</strong>
*
* <pre>
* ExpressionStatement :
* [LA ∉ { <b>{, function, class</b> }] Expression ;
* </pre>
*/
private ExpressionStatement expressionStatement() {
switch (token()) {
case LC:
case FUNCTION:
case CLASS:
reportSyntaxError(Messages.Key.InvalidToken, token().toString());
default:
Expression expr = expression(true);
semicolon();
return new ExpressionStatement(expr);
}
}
/**
* <strong>[12.5] The <code>if</code> Statement</strong>
*
* <pre>
* IfStatement :
* if ( Expression ) Statement else Statement
* if ( Expression ) Statement
* </pre>
*/
private IfStatement ifStatement() {
consume(Token.IF);
consume(Token.LP);
Expression test = expression(true);
consume(Token.RP);
Statement then = statement();
Statement otherwise = null;
if (token() == Token.ELSE) {
consume(Token.ELSE);
otherwise = statement();
}
return new IfStatement(test, then, otherwise);
}
/**
* <strong>[12.6.1] The <code>do-while</code> Statement</strong>
*
* <pre>
* IterationStatement :
* do Statement while ( Expression ) ;
* </pre>
*/
private DoWhileStatement doWhileStatement(Set<String> labelSet) {
consume(Token.DO);
LabelContext labelCx = enterIteration(labelSet);
Statement stmt = statement();
exitIteration();
consume(Token.WHILE);
consume(Token.LP);
Expression test = expression(true);
consume(Token.RP);
if (token() == Token.SEMI) {
consume(Token.SEMI);
}
return new DoWhileStatement(labelCx.abrupts, labelCx.labelSet, test, stmt);
}
/**
* <strong>[12.6.2] The <code>while</code> Statement</strong>
*
* <pre>
* IterationStatement :
* while ( Expression ) Statement
* </pre>
*/
private WhileStatement whileStatement(Set<String> labelSet) {
consume(Token.WHILE);
consume(Token.LP);
Expression test = expression(true);
consume(Token.RP);
LabelContext labelCx = enterIteration(labelSet);
Statement stmt = statement();
exitIteration();
return new WhileStatement(labelCx.abrupts, labelCx.labelSet, test, stmt);
}
/**
* <strong>[12.6.3] The <code>for</code> Statement</strong> <br>
* <strong>[12.6.4] The <code>for-in</code> and <code>for-of</code> Statements</strong>
*
* <pre>
* IterationStatement :
* for ( ExpressionNoIn<sub>opt</sub> ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement
* for ( var VariableDeclarationListNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement
* for ( LexicalDeclarationNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement
* for ( LeftHandSideExpression in Expression ) Statement
* for ( var ForBinding in Expression ) Statement
* for ( ForDeclaration in Expression ) Statement
* for ( LeftHandSideExpression of Expression ) Statement
* for ( var ForBinding of Expression ) Statement
* for ( ForDeclaration of Expression ) Statement
* ForDeclaration :
* LetOrConst ForBinding
* ForBinding :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private IterationStatement forStatement(Set<String> labelSet) {
consume(Token.FOR);
consume(Token.LP);
BlockContext lexBlockContext = null;
Node head;
switch (token()) {
case VAR:
consume(Token.VAR);
VariableStatement varStmt = new VariableStatement(variableDeclarationList(false));
addVarScopedDeclaration(varStmt);
head = varStmt;
break;
case LET:
case CONST:
lexBlockContext = enterBlockContext();
head = lexicalDeclaration(false);
break;
case SEMI:
head = null;
break;
default:
head = expression(false);
break;
}
if (token() == Token.SEMI) {
head = validateFor(head);
consume(Token.SEMI);
Expression test = null;
if (token() != Token.SEMI) {
test = expression(true);
}
consume(Token.SEMI);
Expression step = null;
if (token() != Token.RP) {
step = expression(true);
}
consume(Token.RP);
LabelContext labelCx = enterIteration(labelSet);
Statement stmt = statement();
exitIteration();
if (lexBlockContext != null) {
exitBlockContext();
}
ForStatement iteration = new ForStatement(lexBlockContext, labelCx.abrupts,
labelCx.labelSet, head, test, step, stmt);
if (lexBlockContext != null) {
lexBlockContext.node = iteration;
}
return iteration;
} else if (token() == Token.IN) {
head = validateForInOf(head);
consume(Token.IN);
Expression expr;
if (lexBlockContext == null) {
expr = expression(true);
} else {
exitBlockContext();
expr = expression(true);
reenterBlockContext(lexBlockContext);
}
consume(Token.RP);
LabelContext labelCx = enterIteration(labelSet);
Statement stmt = statement();
exitIteration();
if (lexBlockContext != null) {
exitBlockContext();
}
ForInStatement iteration = new ForInStatement(lexBlockContext, labelCx.abrupts,
labelCx.labelSet, head, expr, stmt);
if (lexBlockContext != null) {
lexBlockContext.node = iteration;
}
return iteration;
} else {
head = validateForInOf(head);
consume("of");
Expression expr;
if (lexBlockContext == null) {
expr = assignmentExpression(true);
} else {
exitBlockContext();
expr = assignmentExpression(true);
reenterBlockContext(lexBlockContext);
}
consume(Token.RP);
LabelContext labelCx = enterIteration(labelSet);
Statement stmt = statement();
exitIteration();
if (lexBlockContext != null) {
exitBlockContext();
}
ForOfStatement iteration = new ForOfStatement(lexBlockContext, labelCx.abrupts,
labelCx.labelSet, head, expr, stmt);
if (lexBlockContext != null) {
lexBlockContext.node = iteration;
}
return iteration;
}
}
/**
* @see #forStatement()
*/
private Node validateFor(Node head) {
if (head instanceof VariableStatement) {
for (VariableDeclaration decl : ((VariableStatement) head).getElements()) {
if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) {
reportSyntaxError(Messages.Key.DestructuringMissingInitialiser);
}
}
} else if (head instanceof LexicalDeclaration) {
boolean isConst = ((LexicalDeclaration) head).getType() == LexicalDeclaration.Type.Const;
for (LexicalBinding decl : ((LexicalDeclaration) head).getElements()) {
if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) {
reportSyntaxError(Messages.Key.DestructuringMissingInitialiser);
}
if (isConst && decl.getInitialiser() == null) {
reportSyntaxError(Messages.Key.ConstMissingInitialiser);
}
}
}
return head;
}
/**
* @see #forStatement()
*/
private Node validateForInOf(Node head) {
if (head instanceof VariableStatement) {
// expected: single variable declaration with no initialiser
List<VariableDeclaration> elements = ((VariableStatement) head).getElements();
if (elements.size() == 1 && elements.get(0).getInitialiser() == null) {
return head;
}
} else if (head instanceof LexicalDeclaration) {
// expected: single lexical binding with no initialiser
List<LexicalBinding> elements = ((LexicalDeclaration) head).getElements();
if (elements.size() == 1 && elements.get(0).getInitialiser() == null) {
return head;
}
} else if (head instanceof Expression) {
// expected: left-hand side expression
LeftHandSideExpression lhs = validateAssignment((Expression) head);
if (lhs == null) {
reportSyntaxError(Messages.Key.InvalidAssignmentTarget);
}
return lhs;
}
throw reportSyntaxError(Messages.Key.InvalidForInOfHead);
}
/**
* Static Semantics: IsValidSimpleAssignmentTarget
*/
private LeftHandSideExpression validateSimpleAssignment(Expression lhs) {
if (lhs instanceof Identifier) {
if (context.strictMode != StrictMode.NonStrict) {
String name = ((Identifier) lhs).getName();
if ("eval".equals(name) || "arguments".equals(name)) {
reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidAssignmentTarget);
}
}
return (Identifier) lhs;
} else if (lhs instanceof ElementAccessor) {
return (ElementAccessor) lhs;
} else if (lhs instanceof PropertyAccessor) {
return (PropertyAccessor) lhs;
} else if (lhs instanceof SuperExpression) {
SuperExpression superExpr = (SuperExpression) lhs;
if (superExpr.getExpression() != null || superExpr.getName() != null) {
return superExpr;
}
}
// everything else => invalid lhs
return null;
}
/**
* Static Semantics: IsValidSimpleAssignmentTarget
*/
private LeftHandSideExpression validateAssignment(Expression lhs) {
// rewrite object/array literal to destructuring form
if (lhs instanceof ObjectLiteral) {
ObjectAssignmentPattern pattern = toDestructuring((ObjectLiteral) lhs);
if (lhs.isParenthesised()) {
pattern.addParentheses();
}
return pattern;
} else if (lhs instanceof ArrayLiteral) {
ArrayAssignmentPattern pattern = toDestructuring((ArrayLiteral) lhs);
if (lhs.isParenthesised()) {
pattern.addParentheses();
}
return pattern;
}
return validateSimpleAssignment(lhs);
}
private ObjectAssignmentPattern toDestructuring(ObjectLiteral object) {
List<AssignmentProperty> list = newSmallList();
for (PropertyDefinition p : object.getProperties()) {
AssignmentProperty property;
if (p instanceof PropertyValueDefinition) {
// AssignmentProperty : PropertyName ':' AssignmentElement
// AssignmentElement : DestructuringAssignmentTarget Initialiser{opt}
// DestructuringAssignmentTarget : LeftHandSideExpression
PropertyValueDefinition def = (PropertyValueDefinition) p;
PropertyName propertyName = def.getPropertyName();
Expression propertyValue = def.getPropertyValue();
LeftHandSideExpression target;
Expression initialiser;
if (propertyValue instanceof AssignmentExpression) {
AssignmentExpression assignment = (AssignmentExpression) propertyValue;
if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) {
reportSyntaxError(Messages.Key.InvalidDestructuring, p.getLine());
}
target = destructuringAssignmentTarget(assignment.getLeft());
initialiser = assignment.getRight();
} else {
target = destructuringAssignmentTarget(propertyValue);
initialiser = null;
}
property = new AssignmentProperty(propertyName, target, initialiser);
} else if (p instanceof PropertyNameDefinition) {
// AssignmentProperty : Identifier
PropertyNameDefinition def = (PropertyNameDefinition) p;
property = assignmentProperty(def.getPropertyName(), null);
} else if (p instanceof CoverInitialisedName) {
// AssignmentProperty : Identifier Initialiser
CoverInitialisedName def = (CoverInitialisedName) p;
property = assignmentProperty(def.getPropertyName(), def.getInitialiser());
} else {
assert p instanceof MethodDefinition;
throw reportSyntaxError(Messages.Key.InvalidDestructuring, p.getLine());
}
list.add(property);
}
context.removeLiteral(object);
return new ObjectAssignmentPattern(list);
}
private ArrayAssignmentPattern toDestructuring(ArrayLiteral array) {
List<AssignmentElementItem> list = newSmallList();
for (Expression e : array.getElements()) {
AssignmentElementItem element;
if (e instanceof Elision) {
// Elision
element = (Elision) e;
} else if (e instanceof SpreadElement) {
// AssignmentRestElement : ... DestructuringAssignmentTarget
// DestructuringAssignmentTarget : LeftHandSideExpression
Expression expression = ((SpreadElement) e).getExpression();
// FIXME: spec bug (need to assert only simple-assignment-target) (Bug 1439)
LeftHandSideExpression target = destructuringSimpleAssignmentTarget(expression);
element = new AssignmentRestElement(target);
} else {
// AssignmentElement : DestructuringAssignmentTarget Initialiser{opt}
// DestructuringAssignmentTarget : LeftHandSideExpression
LeftHandSideExpression target;
Expression initialiser;
if (e instanceof AssignmentExpression) {
AssignmentExpression assignment = (AssignmentExpression) e;
if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) {
reportSyntaxError(Messages.Key.InvalidDestructuring, e.getLine());
}
target = destructuringAssignmentTarget(assignment.getLeft());
initialiser = assignment.getRight();
} else {
target = destructuringAssignmentTarget(e);
initialiser = null;
}
element = new AssignmentElement(target, initialiser);
}
list.add(element);
}
return new ArrayAssignmentPattern(list);
}
private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs) {
return destructuringAssignmentTarget(lhs, true);
}
private LeftHandSideExpression destructuringSimpleAssignmentTarget(Expression lhs) {
return destructuringAssignmentTarget(lhs, false);
}
private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs, boolean extended) {
if (lhs instanceof Identifier) {
String name = ((Identifier) lhs).getName();
if ("eval".equals(name) || "arguments".equals(name)) {
reportSyntaxError(Messages.Key.InvalidAssignmentTarget, lhs.getLine());
}
return (Identifier) lhs;
} else if (lhs instanceof ElementAccessor) {
return (ElementAccessor) lhs;
} else if (lhs instanceof PropertyAccessor) {
return (PropertyAccessor) lhs;
} else if (extended && lhs instanceof ObjectAssignmentPattern) {
return (ObjectAssignmentPattern) lhs;
} else if (extended && lhs instanceof ArrayAssignmentPattern) {
return (ArrayAssignmentPattern) lhs;
} else if (extended && lhs instanceof ObjectLiteral) {
ObjectAssignmentPattern pattern = toDestructuring((ObjectLiteral) lhs);
if (lhs.isParenthesised()) {
pattern.addParentheses();
}
return pattern;
} else if (extended && lhs instanceof ArrayLiteral) {
ArrayAssignmentPattern pattern = toDestructuring((ArrayLiteral) lhs);
if (lhs.isParenthesised()) {
pattern.addParentheses();
}
return pattern;
} else if (lhs instanceof SuperExpression) {
SuperExpression superExpr = (SuperExpression) lhs;
if (superExpr.getExpression() != null || superExpr.getName() != null) {
return superExpr;
}
}
// FIXME: spec bug (IsInvalidAssignmentPattern not defined) (Bug 716)
// everything else => invalid lhs
throw reportSyntaxError(Messages.Key.InvalidDestructuring, lhs.getLine());
}
private AssignmentProperty assignmentProperty(Identifier identifier, Expression initialiser) {
switch (identifier.getName()) {
case "eval":
case "arguments":
case "this":
case "super":
reportSyntaxError(Messages.Key.InvalidDestructuring, identifier.getLine());
}
return new AssignmentProperty(identifier, initialiser);
}
/**
* <strong>[12.7] The <code>continue</code> Statement</strong>
*
* <pre>
* ContinueStatement :
* continue ;
* continue [no <i>LineTerminator</i> here] Identifier ;
* </pre>
*/
private ContinueStatement continueStatement() {
String label;
consume(Token.CONTINUE);
if (noLineTerminator() && isIdentifier(token())) {
label = identifier();
} else {
label = null;
}
semicolon();
LabelContext target = findContinueTarget(label);
if (target == null && label == null) {
reportSyntaxError(Messages.Key.InvalidContinueTarget);
}
if (target == null && label != null) {
reportSyntaxError(Messages.Key.LabelTargetNotFound, label);
}
if (target.type != StatementType.Iteration) {
reportSyntaxError(Messages.Key.InvalidContinueTarget);
}
target.mark(Abrupt.Continue);
return new ContinueStatement(label);
}
/**
* <strong>[12.8] The <code>break</code> Statement</strong>
*
* <pre>
* BreakStatement :
* break ;
* break [no <i>LineTerminator</i> here] Identifier ;
* </pre>
*/
private BreakStatement breakStatement() {
String label;
consume(Token.BREAK);
if (noLineTerminator() && isIdentifier(token())) {
label = identifier();
} else {
label = null;
}
semicolon();
LabelContext target = findBreakTarget(label);
if (target == null && label == null) {
reportSyntaxError(Messages.Key.InvalidBreakTarget);
}
if (target == null && label != null) {
reportSyntaxError(Messages.Key.LabelTargetNotFound, label);
}
target.mark(Abrupt.Break);
return new BreakStatement(label);
}
/**
* <strong>[12.9] The <code>return</code> Statement</strong>
*
* <pre>
* ReturnStatement :
* return ;
* return [no <i>LineTerminator</i> here] Expression ;
* </pre>
*/
private ReturnStatement returnStatement() {
if (context.kind == ContextKind.Script) {
reportSyntaxError(Messages.Key.InvalidReturnStatement);
}
Expression expr = null;
consume(Token.RETURN);
if (noLineTerminator() && !(token() == Token.SEMI || token() == Token.RC)) {
expr = expression(true);
}
semicolon();
return new ReturnStatement(expr);
}
/**
* <strong>[12.10] The <code>with</code> Statement</strong>
*
* <pre>
* WithStatement :
* with ( Expression ) Statement
* </pre>
*/
private WithStatement withStatement() {
reportStrictModeSyntaxError(Messages.Key.StrictModeWithStatement);
consume(Token.WITH);
consume(Token.LP);
Expression expr = expression(true);
consume(Token.RP);
BlockContext scope = enterWithContext();
Statement stmt = statement();
exitWithContext();
WithStatement withStatement = new WithStatement(scope, expr, stmt);
scope.node = withStatement;
return withStatement;
}
/**
* <strong>[12.11] The <code>switch</code> Statement</strong>
*
* <pre>
* SwitchStatement :
* switch ( Expression ) CaseBlock
* CaseBlock :
* { CaseClauses<sub>opt</sub> }
* { CaseClauses<sub>opt</sub> DefaultClause CaseClauses<sub>opt</sub> }
* CaseClauses :
* CaseClause
* CaseClauses CaseClause
* CaseClause :
* case Expression : StatementList<sub>opt</sub>
* DefaultClause :
* default : StatementList<sub>opt</sub>
* </pre>
*/
private SwitchStatement switchStatement(Set<String> labelSet) {
List<SwitchClause> clauses = newList();
consume(Token.SWITCH);
consume(Token.LP);
Expression expr = expression(true);
consume(Token.RP);
consume(Token.LC);
LabelContext labelCx = enterBreakable(labelSet);
BlockContext scope = enterBlockContext();
boolean hasDefault = false;
for (;;) {
Expression caseExpr;
Token tok = token();
if (tok == Token.CASE) {
consume(Token.CASE);
caseExpr = expression(true);
consume(Token.COLON);
} else if (tok == Token.DEFAULT && !hasDefault) {
hasDefault = true;
consume(Token.DEFAULT);
consume(Token.COLON);
caseExpr = null;
} else {
break;
}
List<StatementListItem> list = newList();
statementlist: for (;;) {
switch (token()) {
case CASE:
case DEFAULT:
case RC:
break statementlist;
default:
list.add(statementListItem());
}
}
clauses.add(new SwitchClause(caseExpr, list));
}
exitBlockContext();
exitBreakable();
consume(Token.RC);
SwitchStatement switchStatement = new SwitchStatement(scope, labelCx.abrupts,
labelCx.labelSet, expr, clauses);
scope.node = switchStatement;
return switchStatement;
}
/**
* <strong>[12.12] Labelled Statements</strong>
*
* <pre>
* LabelledStatement :
* Identifier : Statement
* </pre>
*/
private Statement labelledStatement() {
HashSet<String> labelSet = new HashSet<>(4);
labels: for (;;) {
switch (token()) {
case FOR:
return forStatement(labelSet);
case WHILE:
return whileStatement(labelSet);
case DO:
return doWhileStatement(labelSet);
case SWITCH:
return switchStatement(labelSet);
case NAME:
if (LOOKAHEAD(Token.COLON)) {
String name = identifier();
consume(Token.COLON);
labelSet.add(name);
break;
}
case LC:
case VAR:
case SEMI:
case IF:
case CONTINUE:
case BREAK:
case RETURN:
case WITH:
case THROW:
case TRY:
case DEBUGGER:
default:
break labels;
}
}
assert !labelSet.isEmpty();
LabelContext labelCx = enterLabelled(StatementType.Statement, labelSet);
Statement stmt = statement();
exitLabelled();
return new LabelledStatement(labelCx.abrupts, labelCx.labelSet, stmt);
}
/**
* <strong>[12.13] The <code>throw</code> Statement</strong>
*
* <pre>
* ThrowStatement :
* throw [no <i>LineTerminator</i> here] Expression ;
* </pre>
*/
private ThrowStatement throwStatement() {
consume(Token.THROW);
if (!noLineTerminator()) {
reportSyntaxError(Messages.Key.UnexpectedEndOfLine);
}
Expression expr = expression(true);
semicolon();
return new ThrowStatement(expr);
}
/**
* <strong>[12.14] The <code>try</code> Statement</strong>
*
* <pre>
* TryStatement :
* try Block Catch
* try Block Finally
* try Block Catch Finally
* Catch :
* catch ( CatchParameter ) Block
* Finally :
* finally Block
* CatchParameter :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private TryStatement tryStatement() {
BlockStatement tryBlock, finallyBlock = null;
CatchNode catchNode = null;
consume(Token.TRY);
tryBlock = block(NO_INHERITED_BINDING);
Token tok = token();
if (tok == Token.CATCH) {
consume(Token.CATCH);
BlockContext catchScope = enterBlockContext();
consume(Token.LP);
Binding catchParameter = binding();
addLexDeclaredName(catchParameter);
consume(Token.RP);
// catch-block receives a blacklist of forbidden lexical declarable names
BlockStatement catchBlock = block(catchParameter);
removeLexDeclaredName((ScopeContext) catchBlock.getScope(), catchParameter);
exitBlockContext();
catchNode = new CatchNode(catchScope, catchParameter, catchBlock);
catchScope.node = catchNode;
if (token() == Token.FINALLY) {
consume(Token.FINALLY);
finallyBlock = block(NO_INHERITED_BINDING);
}
} else {
consume(Token.FINALLY);
finallyBlock = block(NO_INHERITED_BINDING);
}
return new TryStatement(tryBlock, catchNode, finallyBlock);
}
/**
* <strong>[12.15] The <code>debugger</code> Statement</strong>
*
* <pre>
* DebuggerStatement :
* debugger ;
* </pre>
*/
private DebuggerStatement debuggerStatement() {
consume(Token.DEBUGGER);
semicolon();
return new DebuggerStatement();
}
/**
* <strong>[11.1] Primary Expressions</strong>
*
* <pre>
* PrimaryExpresion :
* this
* Identifier
* Literal
* ArrayInitialiser
* ObjectLiteral
* FunctionExpression
* ClassExpression
* GeneratorExpression
* GeneratorComprehension
* [Lexical goal <i>InputElementRegExp</i>] RegularExpressionLiteral
* TemplateLiteral
* CoverParenthesizedExpressionAndArrowParameterList
* Literal :
* NullLiteral
* ValueLiteral
* ValueLiteral :
* BooleanLiteral
* NumericLiteral
* StringLiteral
* </pre>
*/
private Expression primaryExpression() {
Token tok = token();
switch (tok) {
case THIS:
consume(tok);
return new ThisExpression();
case NULL:
consume(tok);
return new NullLiteral();
case FALSE:
case TRUE:
consume(tok);
return new BooleanLiteral(tok == Token.TRUE);
case NUMBER:
double number = ts.getNumber();
consume(tok);
return new NumericLiteral(number);
case STRING:
String string = ts.getString();
consume(tok);
return new StringLiteral(string);
case DIV:
case ASSIGN_DIV:
return regularExpressionLiteral(tok);
case LB:
return arrayInitialiser();
case LC:
return objectLiteral();
case FUNCTION:
if (LOOKAHEAD(Token.MUL)) {
return generatorExpression();
} else {
return functionExpression();
}
case CLASS:
return classExpression();
case LP:
if (LOOKAHEAD(Token.FOR)) {
return generatorComprehension();
} else {
return coverParenthesizedExpressionAndArrowParameterList();
}
case TEMPLATE:
return templateLiteral(false);
default:
return new Identifier(identifier());
}
}
/**
* <strong>[11.1] Primary Expressions</strong>
*
* <pre>
* CoverParenthesizedExpressionAndArrowParameterList :
* ( Expression )
* ( )
* ( ... Identifier )
* ( Expression , ... Identifier)
* </pre>
*/
private Expression coverParenthesizedExpressionAndArrowParameterList() {
consume(Token.LP);
Expression expr;
if (token() == Token.RP) {
expr = arrowFunctionEmptyParameters();
} else if (token() == Token.TRIPLE_DOT) {
expr = arrowFunctionRestParameter();
} else {
// inlined `expression(true)`
expr = assignmentExpressionNoValidation(true);
if (token() == Token.COMMA) {
List<Expression> list = new ArrayList<>();
list.add(expr);
while (token() == Token.COMMA) {
consume(Token.COMMA);
if (token() == Token.TRIPLE_DOT) {
list.add(arrowFunctionRestParameter());
break;
}
expr = assignmentExpression(true);
list.add(expr);
}
expr = new CommaExpression(list);
}
}
expr.addParentheses();
consume(Token.RP);
return expr;
}
private EmptyExpression arrowFunctionEmptyParameters() {
if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) {
reportSyntaxError(Messages.Key.EmptyParenthesisedExpression);
}
return new EmptyExpression();
}
private SpreadElement arrowFunctionRestParameter() {
consume(Token.TRIPLE_DOT);
SpreadElement spread = new SpreadElement(new Identifier(identifier()));
if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) {
reportSyntaxError(Messages.Key.InvalidSpreadExpression);
}
return spread;
}
/**
* <strong>[11.1.4] Array Initialiser</strong>
*
* <pre>
* ArrayInitialiser :
* ArrayLiteral
* ArrayComprehension
* </pre>
*/
private ArrayInitialiser arrayInitialiser() {
if (LOOKAHEAD(Token.FOR)) {
return arrayComprehension();
} else {
return arrayLiteral();
}
}
/**
* <strong>[11.1.4] Array Initialiser</strong>
*
* <pre>
* ArrayLiteral :
* [ Elision<sub>opt</sub> ]
* [ ElementList ]
* [ ElementList , Elision<sub>opt</sub> ]
* ElementList :
* Elision<sub>opt</sub> AssignmentExpression
* Elision<sub>opt</sub> SpreadElement
* ElementList , Elision<sub>opt</sub> AssignmentExpression
* ElementList , Elision<sub>opt</sub> SpreadElement
* Elision :
* ,
* Elision ,
* SpreadElement :
* ... AssignmentExpression
* </pre>
*/
private ArrayInitialiser arrayLiteral() {
consume(Token.LB);
List<Expression> list = newList();
boolean needComma = false;
for (Token tok; (tok = token()) != Token.RB;) {
if (needComma) {
consume(Token.COMMA);
needComma = false;
} else if (tok == Token.COMMA) {
consume(Token.COMMA);
list.add(new Elision());
} else if (tok == Token.TRIPLE_DOT) {
consume(Token.TRIPLE_DOT);
list.add(new SpreadElement(assignmentExpression(true)));
needComma = true;
} else {
list.add(assignmentExpressionNoValidation(true));
needComma = true;
}
}
consume(Token.RB);
return new ArrayLiteral(list);
}
/**
* <strong>[11.1.4.2] Array Comprehension</strong>
*
* <pre>
* ArrayComprehension :
* [ Comprehension ]
* </pre>
*/
private ArrayComprehension arrayComprehension() {
consume(Token.LB);
Comprehension comprehension = comprehension();
consume(Token.RB);
return new ArrayComprehension(comprehension);
}
/**
* <strong>[11.1.4.2] Array Comprehension</strong>
*
* <pre>
* Comprehension :
* ComprehensionQualification AssignmentExpression
* ComprehensionQualification :
* ComprehensionFor ComprehensionQualifierList<sub>opt</sub>
* ComprehensionQualifierList :
* ComprehensionQualifier
* ComprehensionQualifierList ComprehensionQualifier
* ComprehensionQualifier :
* ComprehensionFor
* ComprehensionIf
* </pre>
*/
private Comprehension comprehension() {
assert token() == Token.FOR;
List<ComprehensionQualifier> list = newSmallList();
int scopes = 0;
for (;;) {
ComprehensionQualifier qualifier;
if (token() == Token.FOR) {
scopes += 1;
qualifier = comprehensionFor();
} else if (token() == Token.IF) {
qualifier = comprehensionIf();
} else {
break;
}
list.add(qualifier);
}
Expression expression = assignmentExpression(true);
while (scopes
exitBlockContext();
}
return new Comprehension(list, expression);
}
/**
* <strong>[11.1.4.2] Array Comprehension</strong>
*
* <pre>
* ComprehensionFor :
* for ( ForBinding of AssignmentExpression )
* ForBinding :
* BindingIdentifier
* BindingPattern
* </pre>
*/
private ComprehensionFor comprehensionFor() {
consume(Token.FOR);
consume(Token.LP);
Binding b = binding();
consume("of");
Expression expression = assignmentExpression(true);
consume(Token.RP);
BlockContext scope = enterBlockContext();
addLexDeclaredName(b);
return new ComprehensionFor(scope, b, expression);
}
/**
* <strong>[11.1.4.2] Array Comprehension</strong>
*
* <pre>
* ComprehensionIf :
* if ( AssignmentExpression )
* </pre>
*/
private ComprehensionIf comprehensionIf() {
consume(Token.IF);
consume(Token.LP);
Expression expression = assignmentExpression(true);
consume(Token.RP);
return new ComprehensionIf(expression);
}
/**
* <strong>[11.1.5] Object Initialiser</strong>
*
* <pre>
* ObjectLiteral :
* { }
* { PropertyDefinitionList }
* { PropertyDefinitionList , }
* PropertyDefinitionList :
* PropertyDefinition
* PropertyDefinitionList , PropertyDefinition
* </pre>
*/
private ObjectLiteral objectLiteral() {
List<PropertyDefinition> defs = newList();
consume(Token.LC);
while (token() != Token.RC) {
defs.add(propertyDefinition());
if (token() == Token.COMMA) {
consume(Token.COMMA);
} else {
break;
}
}
consume(Token.RC);
ObjectLiteral object = new ObjectLiteral(defs);
context.addLiteral(object);
return object;
}
private void objectLiteral_StaticSemantics(int oldCount) {
ArrayDeque<ObjectLiteral> literals = context.objectLiterals;
for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) {
objectLiteral_StaticSemantics(literals.pop());
}
}
private void objectLiteral_StaticSemantics(ObjectLiteral object) {
final int VALUE = 0, GETTER = 1, SETTER = 2;
Map<String, Integer> values = new HashMap<>();
for (PropertyDefinition def : object.getProperties()) {
PropertyName propertyName = def.getPropertyName();
String key = propertyName.getName();
final int kind;
if (def instanceof PropertyValueDefinition || def instanceof PropertyNameDefinition) {
kind = VALUE;
} else if (def instanceof MethodDefinition) {
MethodDefinition method = (MethodDefinition) def;
if (method.hasSuperReference()) {
throw reportSyntaxError(Messages.Key.SuperOutsideClass, def.getLine());
}
MethodDefinition.MethodType type = method.getType();
kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER
: VALUE;
} else {
assert def instanceof CoverInitialisedName;
// Always throw a Syntax Error if this production is present
throw reportSyntaxError(Messages.Key.MissingColonAfterPropertyId, def.getLine(),
key);
}
// It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any
// duplicate entries [...]
if (values.containsKey(key)) {
int prev = values.get(key);
if (kind == VALUE && prev != VALUE) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, def.getLine(), key);
}
if (kind == VALUE && prev == VALUE) {
reportStrictModeSyntaxError(Messages.Key.DuplicatePropertyDefinition,
def.getLine(), key);
}
if (kind == GETTER && prev != SETTER) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, def.getLine(), key);
}
if (kind == SETTER && prev != GETTER) {
reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, def.getLine(), key);
}
values.put(key, prev | kind);
} else {
values.put(key, kind);
}
}
}
/**
* <strong>[11.1.5] Object Initialiser</strong>
*
* <pre>
* PropertyDefinition :
* IdentifierName
* CoverInitialisedName
* PropertyName : AssignmentExpression
* MethodDefinition
* CoverInitialisedName :
* IdentifierName Initialiser
* </pre>
*/
private PropertyDefinition propertyDefinition() {
if (LOOKAHEAD(Token.COLON)) {
PropertyName propertyName = propertyName();
consume(Token.COLON);
Expression propertyValue = assignmentExpressionNoValidation(true);
return new PropertyValueDefinition(propertyName, propertyValue);
}
if (LOOKAHEAD(Token.COMMA) || LOOKAHEAD(Token.RC)) {
// Static Semantics: It is a Syntax Error if IdentifierName is a
// ReservedWord.
return new PropertyNameDefinition(new Identifier(identifier()));
}
if (LOOKAHEAD(Token.ASSIGN)) {
Identifier identifier = new Identifier(identifier());
consume(Token.ASSIGN);
Expression initialiser = assignmentExpression(true);
return new CoverInitialisedName(identifier, initialiser);
}
return methodDefinition(false);
}
/**
* <strong>[11.1.5] Object Initialiser</strong>
*
* <pre>
* PropertyName :
* IdentifierName
* StringLiteral
* NumericLiteral
* </pre>
*/
private PropertyName propertyName() {
switch (token()) {
case STRING:
String string = ts.getString();
consume(Token.STRING);
return new StringLiteral(string);
case NUMBER:
double number = ts.getNumber();
consume(Token.NUMBER);
return new NumericLiteral(number);
default:
return new Identifier(identifierName());
}
}
/**
* <strong>[11.1.7] Generator Comprehensions</strong>
*
* <pre>
* GeneratorComprehension :
* ( Comprehension )
* </pre>
*/
private GeneratorComprehension generatorComprehension() {
consume(Token.LP);
Comprehension comprehension = comprehension();
consume(Token.RP);
return new GeneratorComprehension(comprehension);
}
/**
* <strong>[11.1.8] Regular Expression Literals</strong>
*
* <pre>
* </pre>
*/
private Expression regularExpressionLiteral(Token tok) {
String[] re = ts.readRegularExpression(tok);
consume(tok);
regularExpressionLiteral_StaticSemantics(re[0], re[1]);
return new RegularExpressionLiteral(re[0], re[1]);
}
private void regularExpressionLiteral_StaticSemantics(String p, String f) {
// flags :: g | i | m | u | y
final int global = 0b00001, ignoreCase = 0b00010, multiline = 0b00100, unicode = 0b01000, sticky = 0b10000;
int flags = 0b00000;
for (int i = 0, len = f.length(); i < len; ++i) {
char c = f.charAt(i);
int flag = (c == 'g' ? global : c == 'i' ? ignoreCase : c == 'm' ? multiline
: c == 'u' ? unicode : c == 'y' ? sticky : -1);
if (flag != -1 && (flags & flag) == 0) {
flags |= flag;
} else {
switch (flag) {
case global:
throw reportSyntaxError(Messages.Key.DuplicateRegExpFlag, "global");
case ignoreCase:
throw reportSyntaxError(Messages.Key.DuplicateRegExpFlag, "ignoreCase");
case multiline:
throw reportSyntaxError(Messages.Key.DuplicateRegExpFlag, "multiline");
case unicode:
throw reportSyntaxError(Messages.Key.DuplicateRegExpFlag, "unicode");
case sticky:
throw reportSyntaxError(Messages.Key.DuplicateRegExpFlag, "sticky");
default:
throw reportSyntaxError(Messages.Key.InvalidRegExpFlag, String.valueOf(c));
}
}
}
int iflags = 0;
if ((flags & ignoreCase) != 0) {
iflags |= Pattern.CASE_INSENSITIVE;
}
if ((flags & multiline) != 0) {
iflags |= Pattern.MULTILINE;
}
try {
RegExpParser parser = new RegExpParser(p);
String regexp = parser.toPattern();
Pattern.compile(regexp, iflags);
} catch (PatternSyntaxException e) {
throw reportSyntaxError(Messages.Key.InvalidRegExpPattern, e.getMessage());
}
}
/**
* <strong>[11.1.9] Template Literals</strong>
*
* <pre>
* TemplateLiteral :
* NoSubstitutionTemplate
* TemplateHead Expression [Lexical goal <i>InputElementTemplateTail</i>] TemplateSpans
* TemplateSpans :
* TemplateTail
* TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateTail
* TemplateMiddleList :
* TemplateMiddle Expression
* TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateMiddle Expression
* </pre>
*/
private TemplateLiteral templateLiteral(boolean tagged) {
List<Expression> elements = newList();
String[] values = ts.readTemplateLiteral(Token.TEMPLATE);
elements.add(new TemplateCharacters(values[0], values[1]));
while (token() == Token.LC) {
consume(Token.LC);
elements.add(expression(true));
values = ts.readTemplateLiteral(Token.RC);
elements.add(new TemplateCharacters(values[0], values[1]));
}
consume(Token.TEMPLATE);
return new TemplateLiteral(tagged, elements);
}
/**
* <strong>[11.2] Left-Hand-Side Expressions</strong>
*
* <pre>
* MemberExpression :
* PrimaryExpression
* MemberExpression [ Expression ]
* MemberExpression . IdentifierName
* MemberExpression QuasiLiteral
* super [ Expression ]
* super . IdentifierName
* new MemberExpression Arguments
* NewExpression :
* MemberExpression
* new NewExpression
* CallExpression :
* MemberExpression Arguments
* super Arguments
* CallExpression Arguments
* CallExpression [ Expression ]
* CallExpression . IdentifierName
* CallExpression QuasiLiteral
* LeftHandSideExpression :
* NewExpression
* CallExpression
* </pre>
*/
private Expression leftHandSideExpression(boolean allowCall) {
Expression lhs;
if (token() == Token.NEW) {
consume(Token.NEW);
Expression expr = leftHandSideExpression(false);
List<Expression> args = null;
if (token() == Token.LP) {
args = arguments();
} else {
args = emptyList();
}
lhs = new NewExpression(expr, args);
} else if (token() == Token.SUPER) {
if (context.kind == ContextKind.Script && !options.contains(Option.FunctionCode)) {
reportSyntaxError(Messages.Key.InvalidSuperExpression);
}
context.setReferencesSuper();
consume(Token.SUPER);
switch (token()) {
case DOT:
consume(Token.DOT);
String name = identifierName();
lhs = new SuperExpression(name);
break;
case LB:
consume(Token.LB);
Expression expr = expression(true);
consume(Token.RB);
lhs = new SuperExpression(expr);
break;
case LP:
if (!allowCall) {
lhs = new SuperExpression();
} else {
List<Expression> args = arguments();
lhs = new SuperExpression(args);
}
break;
case TEMPLATE:
// handle "new super``" case
throw reportSyntaxError(Messages.Key.InvalidToken, token().toString());
default:
if (!allowCall) {
lhs = new SuperExpression();
} else {
throw reportSyntaxError(Messages.Key.InvalidToken, token().toString());
}
break;
}
} else {
lhs = primaryExpression();
}
lhs.setLine(ts.getLine());
for (;;) {
switch (token()) {
case DOT:
consume(Token.DOT);
String name = identifierName();
lhs = new PropertyAccessor(lhs, name);
lhs.setLine(ts.getLine());
break;
case LB:
consume(Token.LB);
Expression expr = expression(true);
consume(Token.RB);
lhs = new ElementAccessor(lhs, expr);
lhs.setLine(ts.getLine());
break;
case LP:
if (!allowCall) {
return lhs;
}
if (lhs instanceof Identifier && "eval".equals(((Identifier) lhs).getName())) {
context.funContext.directEval = true;
}
List<Expression> args = arguments();
lhs = new CallExpression(lhs, args);
lhs.setLine(ts.getLine());
break;
case TEMPLATE:
TemplateLiteral templ = templateLiteral(true);
lhs = new TemplateCallExpression(lhs, templ);
lhs.setLine(ts.getLine());
break;
default:
return lhs;
}
}
}
/**
* <strong>[11.2] Left-Hand-Side Expressions</strong>
*
* <pre>
* Arguments :
* ()
* ( ArgumentList )
* ArgumentList :
* AssignmentExpression
* ... AssignmentExpression
* ArgumentList , AssignmentExpression
* ArgumentList , ... AssignmentExpression
* </pre>
*/
private List<Expression> arguments() {
List<Expression> args = newSmallList();
boolean needComma = false;
consume(Token.LP);
while (token() != Token.RP) {
if (needComma) {
consume(Token.COMMA);
needComma = false;
} else {
Expression expr;
if (token() == Token.TRIPLE_DOT) {
consume(Token.TRIPLE_DOT);
expr = new SpreadElement(assignmentExpression(true));
} else {
expr = assignmentExpression(true);
}
args.add(expr);
needComma = true;
}
}
consume(Token.RP);
return args;
}
/**
* <strong>[11.3] Postfix Expressions</strong><br>
* <strong>[11.4] Unary Operators</strong>
*
* <pre>
* PostfixExpression :
* LeftHandSideExpression
* LeftHandSideExpression [no <i>LineTerminator</i> here] ++
* LeftHandSideExpression [no <i>LineTerminator</i> here] --
* UnaryExpression :
* PostfixExpression
* delete UnaryExpression
* void UnaryExpression
* typeof UnaryExpression
* ++ UnaryExpression
* -- UnaryExpression
* + UnaryExpression
* - UnaryExpression
* ~ UnaryExpression
* ! UnaryExpression
* </pre>
*/
private Expression unaryExpression() {
Token tok = token();
switch (tok) {
case DELETE:
case VOID:
case TYPEOF:
case INC:
case DEC:
case ADD:
case SUB:
case BITNOT:
case NOT:
consume(tok);
UnaryExpression unary = new UnaryExpression(unaryOp(tok, false), unaryExpression());
unary.setLine(ts.getLine());
if (tok == Token.INC || tok == Token.DEC) {
if (validateSimpleAssignment(unary.getOperand()) == null) {
reportReferenceError(Messages.Key.InvalidIncDecTarget);
}
}
if (tok == Token.DELETE) {
Expression operand = unary.getOperand();
if (operand instanceof Identifier) {
reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidDeleteOperand);
}
}
return unary;
default:
Expression lhs = leftHandSideExpression(true);
if (noLineTerminator()) {
tok = token();
if (tok == Token.INC || tok == Token.DEC) {
if (validateSimpleAssignment(lhs) == null) {
reportReferenceError(Messages.Key.InvalidIncDecTarget);
}
consume(tok);
return new UnaryExpression(unaryOp(tok, true), lhs);
}
}
return lhs;
}
}
private static UnaryExpression.Operator unaryOp(Token tok, boolean postfix) {
switch (tok) {
case DELETE:
return UnaryExpression.Operator.DELETE;
case VOID:
return UnaryExpression.Operator.VOID;
case TYPEOF:
return UnaryExpression.Operator.TYPEOF;
case INC:
return postfix ? UnaryExpression.Operator.POST_INC : UnaryExpression.Operator.PRE_INC;
case DEC:
return postfix ? UnaryExpression.Operator.POST_DEC : UnaryExpression.Operator.PRE_DEC;
case ADD:
return UnaryExpression.Operator.POS;
case SUB:
return UnaryExpression.Operator.NEG;
case BITNOT:
return UnaryExpression.Operator.BITNOT;
case NOT:
return UnaryExpression.Operator.NOT;
default:
return null;
}
}
private Expression binaryExpression(boolean allowIn) {
Expression lhs = unaryExpression();
return binaryExpression(allowIn, lhs, BinaryExpression.Operator.OR.getPrecedence());
}
private Expression binaryExpression(boolean allowIn, Expression lhs, int minpred) {
// Recursive-descent parsers require multiple levels of recursion to
// parse binary expressions, to avoid this we're using precedence
// climbing here
for (;;) {
Token tok = token();
if (tok == Token.IN && !allowIn) {
break;
}
BinaryExpression.Operator op = binaryOp(tok);
int pred = (op != null ? op.getPrecedence() : -1);
if (pred < minpred) {
break;
}
consume(tok);
Expression rhs = unaryExpression();
for (;;) {
BinaryExpression.Operator op2 = binaryOp(token());
int pred2 = (op2 != null ? op2.getPrecedence() : -1);
if (pred2 <= pred) {
break;
}
rhs = binaryExpression(allowIn, rhs, pred2);
}
lhs = new BinaryExpression(op, lhs, rhs);
}
return lhs;
}
private static BinaryExpression.Operator binaryOp(Token token) {
switch (token) {
case OR:
return BinaryExpression.Operator.OR;
case AND:
return BinaryExpression.Operator.AND;
case BITOR:
return BinaryExpression.Operator.BITOR;
case BITXOR:
return BinaryExpression.Operator.BITXOR;
case BITAND:
return BinaryExpression.Operator.BITAND;
case EQ:
return BinaryExpression.Operator.EQ;
case NE:
return BinaryExpression.Operator.NE;
case SHEQ:
return BinaryExpression.Operator.SHEQ;
case SHNE:
return BinaryExpression.Operator.SHNE;
case LT:
return BinaryExpression.Operator.LT;
case LE:
return BinaryExpression.Operator.LE;
case GT:
return BinaryExpression.Operator.GT;
case GE:
return BinaryExpression.Operator.GE;
case IN:
return BinaryExpression.Operator.IN;
case INSTANCEOF:
return BinaryExpression.Operator.INSTANCEOF;
case SHL:
return BinaryExpression.Operator.SHL;
case SHR:
return BinaryExpression.Operator.SHR;
case USHR:
return BinaryExpression.Operator.USHR;
case ADD:
return BinaryExpression.Operator.ADD;
case SUB:
return BinaryExpression.Operator.SUB;
case MUL:
return BinaryExpression.Operator.MUL;
case DIV:
return BinaryExpression.Operator.DIV;
case MOD:
return BinaryExpression.Operator.MOD;
default:
return null;
}
}
/**
* <strong>[11.12] Conditional Operator</strong><br>
* <strong>[11.13] Assignment Operators</strong>
*
* <pre>
* ConditionalExpression :
* LogicalORExpression
* LogicalORExpression ? AssignmentExpression : AssignmentExpression
* ConditionalExpressionNoIn :
* LogicalORExpressionNoIn
* LogicalORExpressionNoIn ? AssignmentExpression : AssignmentExpressionNoIn
* AssignmentExpression :
* ConditionalExpression
* YieldExpression
* ArrowFunction
* LeftHandSideExpression = AssignmentExpression
* LeftHandSideExpression AssignmentOperator AssignmentExpression
* AssignmentExpressionNoIn :
* ConditionalExpressionNoIn
* YieldExpression
* ArrowFunction
* LeftHandSideExpression = AssignmentExpressionNoIn
* LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn
* </pre>
*/
private Expression assignmentExpression(boolean allowIn) {
int count = context.countLiterals();
Expression expr = assignmentExpression(allowIn, count);
if (count < context.countLiterals()) {
objectLiteral_StaticSemantics(count);
}
return expr;
}
private Expression assignmentExpressionNoValidation(boolean allowIn) {
return assignmentExpression(allowIn, context.countLiterals());
}
private Expression assignmentExpression(boolean allowIn, int oldCount) {
// TODO: this may need to be changed...
if (token() == Token.YIELD) {
return yieldExpression();
}
long marker = ts.marker();
Expression left = binaryExpression(allowIn);
Token tok = token();
if (tok == Token.HOOK) {
consume(Token.HOOK);
Expression then = assignmentExpression(true);
consume(Token.COLON);
Expression otherwise = assignmentExpression(allowIn);
return new ConditionalExpression(left, then, otherwise);
} else if (tok == Token.ARROW) {
// discard parsed object literals
if (oldCount < context.countLiterals()) {
ArrayDeque<ObjectLiteral> literals = context.objectLiterals;
for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) {
literals.pop();
}
}
ts.reset(marker);
return arrowFunction();
} else if (tok == Token.ASSIGN) {
LeftHandSideExpression lhs = validateAssignment(left);
if (lhs == null) {
reportReferenceError(Messages.Key.InvalidAssignmentTarget);
}
consume(Token.ASSIGN);
Expression right = assignmentExpression(allowIn);
return new AssignmentExpression(assignmentOp(tok), lhs, right);
} else if (isAssignmentOperator(tok)) {
LeftHandSideExpression lhs = validateSimpleAssignment(left);
if (lhs == null) {
reportReferenceError(Messages.Key.InvalidAssignmentTarget);
}
consume(tok);
Expression right = assignmentExpression(allowIn);
return new AssignmentExpression(assignmentOp(tok), lhs, right);
} else {
return left;
}
}
private static AssignmentExpression.Operator assignmentOp(Token token) {
switch (token) {
case ASSIGN:
return AssignmentExpression.Operator.ASSIGN;
case ASSIGN_ADD:
return AssignmentExpression.Operator.ASSIGN_ADD;
case ASSIGN_SUB:
return AssignmentExpression.Operator.ASSIGN_SUB;
case ASSIGN_MUL:
return AssignmentExpression.Operator.ASSIGN_MUL;
case ASSIGN_DIV:
return AssignmentExpression.Operator.ASSIGN_DIV;
case ASSIGN_MOD:
return AssignmentExpression.Operator.ASSIGN_MOD;
case ASSIGN_SHL:
return AssignmentExpression.Operator.ASSIGN_SHL;
case ASSIGN_SHR:
return AssignmentExpression.Operator.ASSIGN_SHR;
case ASSIGN_USHR:
return AssignmentExpression.Operator.ASSIGN_USHR;
case ASSIGN_BITAND:
return AssignmentExpression.Operator.ASSIGN_BITAND;
case ASSIGN_BITOR:
return AssignmentExpression.Operator.ASSIGN_BITOR;
case ASSIGN_BITXOR:
return AssignmentExpression.Operator.ASSIGN_BITXOR;
default:
return null;
}
}
/**
* <strong>[11.13] Assignment Operators</strong>
*
* <pre>
* AssignmentOperator : <b>one of</b>
* *= /= %= += -= <<= >>= >>>= &= ^= |=
* </pre>
*/
private boolean isAssignmentOperator(Token tok) {
switch (tok) {
case ASSIGN_ADD:
case ASSIGN_BITAND:
case ASSIGN_BITOR:
case ASSIGN_BITXOR:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_MUL:
case ASSIGN_SHL:
case ASSIGN_SHR:
case ASSIGN_SUB:
case ASSIGN_USHR:
return true;
default:
return false;
}
}
/**
* <strong>[11.14] Comma Operator</strong>
*
* <pre>
* Expression :
* AssignmentExpression
* Expression , AssignmentExpression
* ExpressionNoIn :
* AssignmentExpressionNoIn
* ExpressionNoIn , AssignmentExpressionNoIn
* </pre>
*/
private Expression expression(boolean allowIn) {
Expression expr = assignmentExpression(allowIn);
if (token() == Token.COMMA) {
List<Expression> list = new ArrayList<>();
list.add(expr);
while (token() == Token.COMMA) {
consume(Token.COMMA);
expr = assignmentExpression(allowIn);
list.add(expr);
}
return new CommaExpression(list);
}
return expr;
}
/**
* <strong>[7.9] Automatic Semicolon Insertion</strong>
*
* <pre>
* </pre>
*/
private void semicolon() {
switch (token()) {
case SEMI:
consume(Token.SEMI);
case RC:
case EOF:
break;
default:
if (noLineTerminator()) {
reportSyntaxError(Messages.Key.MissingSemicolon);
}
}
}
/**
* Peek next token and check for line-terminator
*/
private boolean noLineTerminator() {
return !ts.hasCurrentLineTerminator();
}
/**
* Return token name
*/
private String getName(Token tok) {
if (tok == Token.NAME) {
return ts.getString();
}
return tok.getName();
}
/**
* <strong>[7.6] Identifier Names and Identifiers</strong>
*
* <pre>
* Identifier ::
* IdentifierName but not ReservedWord
* ReservedWord ::
* Keyword
* FutureReservedWord
* NullLiteral
* BooleanLiteral
* </pre>
*/
private String identifier() {
Token tok = token();
if (!isIdentifier(tok)) {
reportTokenMismatch("<identifier>", tok);
}
String name = getName(tok);
consume(tok);
return name;
}
/**
* <strong>[7.6] Identifier Names and Identifiers</strong>
*/
private boolean isIdentifier(Token tok) {
return isIdentifier(tok, context.strictMode);
}
/**
* <strong>[7.6] Identifier Names and Identifiers</strong>
*/
private boolean isIdentifier(Token tok, StrictMode strictMode) {
switch (tok) {
case NAME:
return true;
case IMPLEMENTS:
case INTERFACE:
case PACKAGE:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case STATIC:
// TODO: otherwise cannot parse YieldExpression, context dependent syntax restriction?
// case YIELD:
if (strictMode != StrictMode.NonStrict) {
reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok));
}
return (strictMode != StrictMode.Strict);
default:
return false;
}
}
/**
* <strong>[7.6] Identifier Names and Identifiers</strong>
*/
private String identifierName() {
Token tok = token();
if (!isIdentifierName(tok)) {
reportTokenMismatch("<identifier-name>", tok);
}
String name = getName(tok);
consume(tok);
return name;
}
/**
* <strong>[7.6] Identifier Names and Identifiers</strong>
*/
private static boolean isIdentifierName(Token tok) {
switch (tok) {
case BREAK:
case CASE:
case CATCH:
case CLASS:
case CONST:
case CONTINUE:
case DEBUGGER:
case DEFAULT:
case DELETE:
case DO:
case ELSE:
case ENUM:
case EXPORT:
case EXTENDS:
case FALSE:
case FINALLY:
case FOR:
case FUNCTION:
case IF:
case IMPLEMENTS:
case IMPORT:
case IN:
case INSTANCEOF:
case INTERFACE:
case LET:
case NAME:
case NEW:
case NULL:
case PACKAGE:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case RETURN:
case STATIC:
case SUPER:
case SWITCH:
case THIS:
case THROW:
case TRUE:
case TRY:
case TYPEOF:
case VAR:
case VOID:
case WHILE:
case WITH:
case YIELD:
return true;
default:
return false;
}
}
}
|
package org.hackreduce.examples.ngram.two_gram;
import java.io.IOException;
import java.util.Arrays;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.ToolRunner;
import org.hackreduce.mappers.ModelMapper;
import org.hackreduce.mappers.ngram.TwoGramMapper;
import org.hackreduce.models.ngram.TwoGram;
/**
* This MapReduce job will count the total number of {@link TwoGram} records in the data dump.
*
*/
public class HackRecordCounter extends org.hackreduce.examples.RecordCounter {
public enum Count {
TOTAL_RECORDS
}
public static class HackRecordCounterMapper extends TwoGramMapper<Text, LongWritable> {
// Our own made up key to send all counts to a single Reducer, so we can
// aggregate a total value.
public static final Text TOTAL_COUNT = new Text("total");
// Just to save on object instantiation
public static final LongWritable ONE_COUNT = new LongWritable(1);
@Override
protected void map(TwoGram record, Context context) throws IOException, InterruptedException {
// Count only anagrams by returning early if not an anagram
// Simple length check should usually suffice
//if (record.getGram1().length() != record.getGram2().length()) return;
// Same length, so sort lowercase characters to compare
//char[] g1 = record.getGram1().toLowerCase().toCharArray();
//char[] g2 = record.getGram2().toLowerCase().toCharArray();
//Arrays.sort(g1);
//Arrays.sort(g2);
//if (!Arrays.equals(g1, g2)) return;
// Write out count of one, keyed by the canonicalized gram
//context.write(new Text(new String(g1)), new LongWritable(record.getMatchCount()));
//context.getCounter(Count.TOTAL_RECORDS).increment(1);
//context.write(TOTAL_COUNT, ONE_COUNT);
// Count alliteration by returning early if not matching first letter
String g1 = record.getGram1();
String g2 = record.getGram2();
if (g2 == null || g1.length() < 3 || g2.length() < 3) return;
if (!g1.matches("[a-zA-Z]+") || !g2.matches("[a-zA-Z]+")) return;
char c1 = g1.charAt(0);
char c2 = g2.charAt(0);
if (!Character.isLetter(c1) || !Character.isLetter(c2)) return;
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) return;
// Write alliteration by year, letter, count
context.write(
new Text("" + c1 + " " + Integer.toString(record.getYear())),
new LongWritable(record.getMatchCount()));
}
}
@Override
public void configureJob(Job job) {
// The flight data dumps comes in as a CSV file (text input), so we configure
// the job to use this format.
TwoGramMapper.configureJob(job);
}
@Override
public Class<? extends ModelMapper<?, ?, ?, ?, ?>> getMapper() {
return HackRecordCounterMapper.class;
}
public static void main(String[] args) throws Exception {
int result = ToolRunner.run(new Configuration(), new HackRecordCounter(), args);
System.exit(result);
}
}
|
package com.github.bot.curiosone.core.nlp;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Handles a Word.
* A Word is like a Token, but with a restricted Set of Meanings.
* Provides methods to create a new Word and retrieve its information.
* @see com.github.bot.curiosone.core.nlp.Token The Token Class
*
*/
public class Word {
/**
* Stores the textual representation of this Word.
*/
String text;
/**
* Stores the base form of this Word.
*/
String lemma;
/**
* Stores all the possible meanings of this Word.
* @see com.github.bot.curiosone.core.nlp.Meaning The Meaning Class
*/
Set<Meaning> means;
/**
* Constructs a Word starting from a text, a lemma and a Set of meanings.
* @param text
* a textual representation of this Word
* @param lemma
* the lemma for this Word
* @param means
* Set containing all the possible meanings for this Word
*/
public Word(String text, String lemma, Set<Meaning> means) {
this.text = text;
this.lemma = lemma;
this.means = means;
}
/**
* Constructs a Word starting from a text, a lemma and a single meaning.
* @param text
* textual representation of this Word
* @param lemma
* the lemma for this Word
* @param mean
* meaning of this Word
*/
public Word(String text, String lemma, Meaning mean) {
this.text = text;
this.lemma = lemma;
this.means = new HashSet<>();
means.add(mean);
}
/**
* @return the textual representation of this Word.
*/
public String getText() {
return text;
}
/**
* @return the lemma of this Word.
*/
public String getLemma() {
return lemma;
}
/**
* @return the Set of the meanings of this Word.
* @see com.github.bot.curiosone.core.nlp.Meaning The Meaning Class
*/
public Set<Meaning> getMeanings() {
return means;
}
/**
* Checks whether this Word has the given meaning or not.
* @param mean
* the Meaning that this Word is supposed to have
* @return {@code true} if the given Meaning is associated with this Word;
* {@code false} otherwise
*/
public boolean itMeans(Meaning mean) {
return means.contains(mean);
}
/**
* Checks whether this Word is the given Part of Speech Type or not.
* @param pos
* the POS to be checked
* @return {@code true} if this Word is the given POS;
* {@code false} otherwise
*/
public boolean itMeans(POS pos) {
return means.stream()
.map(Meaning::getPOS)
.collect(Collectors.toList())
.contains(pos);
}
/**
* Checks whether this Word is the given Lexical Type or not.
* @param lex
* the LEX to be checked
* @return {@code true} if this Word is the given LEX;
* {@code false} otherwise
*/
public boolean itMeans(LEX lex) {
return means.stream()
.map(Meaning::getLEX)
.collect(Collectors.toList())
.contains(lex);
}
/**
* @return a String representation of this Word in the form [text, word, meanings].
*/
@Override
public String toString() {
return "[" + text + " (" + lemma + ")" + ", " + means + "]";
}
/**
* Checks whether this Word equals to the given Object.
* @param other
* the other Word to be compared against
* @return {@code true} if this Word equals the other Word;
* {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other == null || other.getClass() != this.getClass()) {
return false;
}
Word that = (Word) other;
return this.text.equals(that.text);
}
/**
* Calculates the HashCode of this Word.
* The HashCode is based on the HashCode of the textual representation of this Word.
* @return the HashCode of this Word
*/
@Override
public int hashCode() {
return text.hashCode();
}
}
|
package com.github.davidcarboni.restolino;
import javax.servlet.Servlet;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.BaseHolder.Source;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import com.github.davidcarboni.restolino.handlers.MainHandler;
/**
*
* This class launches the web application in an embedded Jetty container. This
* is the entry point to your application. The Java command that is used for
* launching should fire this main method.
*
*/
public class Main {
public static void main(String[] args) throws Exception {
String port = System.getenv("PORT");
if (StringUtils.isBlank(port))
port = "8080";
System.out.println("Using port " + port);
Server server = new Server(Integer.parseInt(port));
Handler mainHandler = new MainHandler();
server.setHandler(mainHandler);
server.start();
// server.dumpStdErr();
server.join();
}
// public static void main(String[] args) throws Exception {
// Server server = new Server(8080);
// // Web app:
// // WebAppContext webApp = new WebAppContext();
// ServletContextHandler webApp = new ServletContextHandler();
// // ContextHandler webApp = new ContextHandler();
// webApp.setContextPath("/");
// webApp.setResourceBase("src/main/webapp");
// // Filter: (Default: EnumSet.of(DispatcherType.REQUEST))
// /**
// * @param args
// */
// public static void main(String[] args) throws Exception {
// String webappDirLocation = "src/main/webapp/";
// // The port that we should run on can be set into an environment
// // variable
// // Look for that variable and default to 8080 if it isn't there.
// String webPort = System.getenv("PORT");
// if (StringUtils.isBlank(webPort)) {
// webPort = "8080";
// Server server = new Server(Integer.parseInt(webPort));
// ServletHandler handler = new ServletHandler();
// // Filter:
/**
* Adds a servlet that will get initialised on startup.
*
* @param root
* @param servletClass
* @param pathSpec
*/
static void addServlet(WebAppContext root,
Class<? extends Servlet> servletClass, String pathSpec) {
ServletHolder holder = new ServletHolder(Source.EMBEDDED);
holder.setClassName(servletClass.getName());
holder.setInitOrder(++order);
root.addServlet(holder, pathSpec);
}
/**
* Adds a servlet that will get initialised on startup.
*
* @param root
* @param servletClass
* @param pathSpec
*/
static void addServlet(ServletHandler root,
Class<? extends Servlet> servletClass, String pathSpec) {
ServletHolder holder = new ServletHolder(Source.EMBEDDED);
holder.setClassName(servletClass.getName());
holder.setInitOrder(++order);
root.addServletWithMapping(holder, pathSpec);
}
/**
* Adds a servlet that will get initialised on startup.
*
* @param root
* @param servletClass
* @param pathSpec
*/
static void addServlet(ServletContextHandler root,
Class<? extends Servlet> servletClass, String pathSpec) {
ServletHolder holder = new ServletHolder(Source.EMBEDDED);
holder.setClassName(servletClass.getName());
holder.setInitOrder(++order);
root.addServlet(holder, pathSpec);
}
}
|
package com.github.msemys.esjc.http;
import com.github.msemys.esjc.UserCredentials;
import com.github.msemys.esjc.http.handler.HttpResponseHandler;
import com.github.msemys.esjc.util.concurrent.ResettableLatch;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.Base64;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.github.msemys.esjc.util.Numbers.isPositive;
import static com.github.msemys.esjc.util.Preconditions.*;
import static com.github.msemys.esjc.util.Strings.*;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* HTTP client without pipelining support
*/
public class HttpClient implements AutoCloseable {
private final EventLoopGroup group = new NioEventLoopGroup(0, new DefaultThreadFactory("es-http"));
private final Bootstrap bootstrap;
private final String host;
private final boolean acceptGzip;
private final long operationTimeoutMillis;
private final ExecutorService queueExecutor = newSingleThreadExecutor(new DefaultThreadFactory("es-http-queue"));
private final Queue<HttpOperation> queue = new ConcurrentLinkedQueue<>();
private final AtomicBoolean isProcessing = new AtomicBoolean();
private final ResettableLatch received = new ResettableLatch(false);
private volatile Channel channel;
private HttpClient(Builder builder) {
host = builder.address.getHostString();
acceptGzip = builder.acceptGzip;
operationTimeoutMillis = builder.operationTimeout.toMillis();
bootstrap = new Bootstrap()
.remoteAddress(builder.address)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_REUSEADDR, false)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) builder.connectTimeout.toMillis())
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("http-codec", new HttpClientCodec());
if (acceptGzip) {
pipeline.addLast("content-decompressor", new HttpContentDecompressor());
}
pipeline.addLast("object-aggregator", new HttpObjectAggregator(builder.maxContentLength));
pipeline.addLast("logger", new LoggingHandler(HttpClient.class, LogLevel.TRACE));
pipeline.addLast("response-handler", new HttpResponseHandler());
}
});
}
public CompletableFuture<FullHttpResponse> send(HttpRequest request) {
checkNotNull(request, "request is null");
checkState(isRunning(), "HTTP client is closed");
request.headers().set(HttpHeaders.Names.HOST, host);
if (acceptGzip) {
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
CompletableFuture<FullHttpResponse> response = new CompletableFuture<>();
enqueue(new HttpOperation(request, response));
return response;
}
private void enqueue(HttpOperation operation) {
checkNotNull(operation, "operation is null");
queue.offer(operation);
if (isProcessing.compareAndSet(false, true)) {
queueExecutor.execute(this::processQueue);
}
}
private void processQueue() {
do {
HttpOperation operation;
while ((operation = queue.poll()) != null) {
if (channel == null || !channel.isActive()) {
try {
channel = bootstrap.connect().syncUninterruptibly().channel();
} catch (Exception e) {
operation.response.completeExceptionally(e);
if (isRunning()) {
continue;
} else {
break;
}
}
}
write(operation);
}
isProcessing.set(false);
} while (isRunning() && !queue.isEmpty() && isProcessing.compareAndSet(false, true));
}
private void write(HttpOperation operation) {
received.reset();
operation.response.whenComplete((r, t) -> received.release());
HttpResponseHandler responseHandler = channel.pipeline().get(HttpResponseHandler.class);
responseHandler.pendingResponse = operation.response;
try {
channel.writeAndFlush(operation.request).sync();
if (!received.await(operationTimeoutMillis, MILLISECONDS)) {
channel.close().awaitUninterruptibly();
String message = String.format("%s %s request never got response from server.",
operation.request.getMethod().name(),
operation.request.getUri());
operation.response.completeExceptionally(new TimeoutException(message));
}
} catch (Exception e) {
operation.response.completeExceptionally(e);
} finally {
responseHandler.pendingResponse = null;
}
}
private boolean isRunning() {
return !group.isShuttingDown();
}
@Override
public void close() {
Future shutdownFuture = group.shutdownGracefully(0, 15, SECONDS);
queueExecutor.shutdown();
HttpOperation operation;
while ((operation = queue.poll()) != null) {
operation.response.completeExceptionally(new HttpClientException("Client closed"));
}
shutdownFuture.awaitUninterruptibly();
try {
queueExecutor.awaitTermination(5, SECONDS);
} catch (InterruptedException e) {
// ignore
}
}
private static void addAuthorizationHeader(FullHttpRequest request, UserCredentials userCredentials) {
checkNotNull(request, "request is null");
checkNotNull(userCredentials, "userCredentials is null");
byte[] encodedCredentials = Base64.getEncoder().encode(toBytes(userCredentials.username + ":" + userCredentials.password));
request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + newString(encodedCredentials));
}
public static FullHttpRequest newRequest(HttpMethod method, String uri, UserCredentials userCredentials) {
checkNotNull(method, "method is null");
checkArgument(!isNullOrEmpty(uri), "uri is null or empty");
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri);
if (userCredentials != null) {
addAuthorizationHeader(request, userCredentials);
}
return request;
}
public static FullHttpRequest newRequest(HttpMethod method, String uri, String body, String contentType, UserCredentials userCredentials) {
checkNotNull(method, "method is null");
checkArgument(!isNullOrEmpty(uri), "uri is null or empty");
checkNotNull(body, "body is null");
checkArgument(!isNullOrEmpty(contentType), "contentType is null or empty");
ByteBuf data = copiedBuffer(body, UTF_8);
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri, data);
request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, data.readableBytes());
if (userCredentials != null) {
addAuthorizationHeader(request, userCredentials);
}
return request;
}
/**
* Creates a new HTTP client builder.
*
* @return HTTP client builder
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* HTTP client builder.
*/
public static class Builder {
private InetSocketAddress address;
private Duration connectTimeout;
private Duration operationTimeout;
private Boolean acceptGzip;
private Integer maxContentLength;
/**
* Sets server address.
*
* @param host the host name.
* @param port the port number.
* @return the builder reference
*/
public Builder address(String host, int port) {
return address(new InetSocketAddress(host, port));
}
/**
* Sets server address.
*
* @param address the server address.
* @return the builder reference
*/
public Builder address(InetSocketAddress address) {
this.address = address;
return this;
}
/**
* Sets connection establishment timeout (by default, 10 seconds).
*
* @param connectTimeout connection establishment timeout.
* @return the builder reference
*/
public Builder connectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Sets the amount of time before an operation is considered to have timed out (by default, 7 seconds).
*
* @param operationTimeout the amount of time before an operation is considered to have timed out.
* @return the builder reference
*/
public Builder operationTimeout(Duration operationTimeout) {
this.operationTimeout = operationTimeout;
return this;
}
/**
* Specifies whether or not the client accepts compressed content (by default, does not accept compressed content).
*
* @param acceptGzip {@code true} to accept.
* @return the builder reference
*/
public Builder acceptGzip(boolean acceptGzip) {
this.acceptGzip = acceptGzip;
return this;
}
/**
* Sets the maximum length of the response content in bytes (by default, 128 megabytes).
*
* @param maxContentLength the maximum length of the response content in bytes.
* @return the builder reference
*/
public Builder maxContentLength(int maxContentLength) {
this.maxContentLength = maxContentLength;
return this;
}
/**
* Builds a HTTP client.
*
* @return HTTP client
*/
public HttpClient build() {
checkNotNull(address, "address is null");
if (connectTimeout == null) {
connectTimeout = Duration.ofSeconds(10);
}
if (operationTimeout == null) {
operationTimeout = Duration.ofSeconds(7);
}
if (acceptGzip == null) {
acceptGzip = false;
}
if (maxContentLength == null) {
maxContentLength = 128 * 1024 * 1024;
} else {
checkArgument(isPositive(maxContentLength), "maxContentLength should be positive");
}
return new HttpClient(this);
}
}
private static class HttpOperation {
final HttpRequest request;
final CompletableFuture<FullHttpResponse> response;
HttpOperation(HttpRequest request, CompletableFuture<FullHttpResponse> response) {
checkNotNull(request, "request is null");
checkNotNull(response, "response is null");
this.request = request;
this.response = response;
}
}
}
|
package org.suren.autotest.web.framework.selenium;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_CHROME;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_FIREFOX;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_IE;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_OPERA;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_SAFARI;
import static org.suren.autotest.web.framework.settings.DriverConstants.ENGINE_CONFIG_FILE_NAME;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.suren.autotest.web.framework.core.AutoTestException;
import org.suren.autotest.web.framework.util.BrowserUtil;
import org.suren.autotest.web.framework.util.PathUtil;
/**
*
* @author suren
* @since jdk1.6 2016629
*/
@Component
public class SeleniumEngine
{
private static final Logger logger = LoggerFactory.getLogger(SeleniumEngine.class);
private Properties enginePro = new Properties();
private Map<String, DesiredCapabilities> engineCapMap = new HashMap<String, DesiredCapabilities>();
private WebDriver driver;
private String driverStr;
private String remoteStr;
private long timeout;
private boolean fullScreen;
private boolean maximize;
private int width;
private int height;
private int toolbarHeight;
public void init()
{
InputStream inputStream = null;
try
{
ClassLoader classLoader = this.getClass().getClassLoader();
loadDefaultEnginePath(classLoader, enginePro);
System.getProperties().putAll(enginePro);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
initCapMap();
String curDriverStr = getDriverStr();
DesiredCapabilities capability = engineCapMap.get(curDriverStr);
if(capability == null)
{
throw new RuntimeException(String.format("Unknow type driver [%s].", curDriverStr));
}
if(getRemoteStr() != null)
{
try
{
driver = new RemoteWebDriver(new URL(getRemoteStr()), capability);
}
catch (MalformedURLException e)
{
throw new AutoTestException();
}
}
else if(DRIVER_CHROME.equals(curDriverStr))
{
driver = new ChromeDriver(capability);
}
else if(DRIVER_IE.equals(curDriverStr))
{
driver = new InternetExplorerDriver(capability);
}
else if(DRIVER_FIREFOX.equals(curDriverStr))
{
String proFile = System.getProperty("firefox.profile", null);
FirefoxProfile profile = new FirefoxProfile(proFile != null ? new File(proFile) : null);
fireFoxPreSet(profile);
driver = new FirefoxDriver(null, profile, capability);
}
else if(DRIVER_SAFARI.equals(curDriverStr))
{
driver = new SafariDriver(capability);
}
else if(DRIVER_OPERA.equals(curDriverStr))
{
driver = new OperaDriver(capability);
}
if(timeout > 0)
{
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
Window window = driver.manage().window();
if(fullScreen)
{
try
{
// window.fullscreen();
}
catch(UnsupportedCommandException e)
{
logger.error("Unsupported fullScreen command.", e);
}
}
if(maximize)
{
window.maximize();
}
if(getWidth() > 0)
{
window.setSize(new Dimension(getWidth(), window.getSize().getHeight()));
}
if(getHeight() > 0)
{
window.setSize(new Dimension(window.getSize().getWidth(), getHeight()));
}
}
/**
* @return
*/
public final Map<Object, Object> getEngineConfig()
{
return Collections.unmodifiableMap(enginePro);
}
private void initCapMap()
{
{
DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setCapability("marionette", true);
engineCapMap.put(DRIVER_FIREFOX, capability);
}
//chrome://version/
{
DesiredCapabilities capability = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
Iterator<Object> chromeKeys = enginePro.keySet().iterator();
while(chromeKeys.hasNext())
{
String key = chromeKeys.next().toString();
if(!key.startsWith("chrome"))
{
continue;
}
if(key.startsWith("chrome.args"))
{
String arg = key.replace("chrome.args.", "") + "=" + enginePro.getProperty(key);
if(arg.endsWith("="))
{
arg = arg.substring(0, arg.length() - 1);
}
options.addArguments(arg);
logger.info(String.format("chrome arguments : [%s]", arg));
}
else if(key.startsWith("chrome.cap.proxy.http"))
{
String val = enginePro.getProperty(key);
Proxy proxy = new Proxy();
proxy.setHttpProxy(val);
capability.setCapability("proxy", proxy);
}
else if(key.startsWith("chrome.binary"))
{
options.setBinary(enginePro.getProperty(key));
}
}
capability.setCapability(ChromeOptions.CAPABILITY, options);
engineCapMap.put(DRIVER_CHROME, capability);
}
{
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
capability.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capability.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "http://surenpi.com");
capability.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false);
engineCapMap.put(DRIVER_IE, capability);
}
{
String proFile = System.getProperty("firefox.profile", null);
FirefoxProfile profile = new FirefoxProfile(proFile != null ? new File(proFile) : null);
fireFoxPreSet(profile);
}
{
DesiredCapabilities capability = DesiredCapabilities.safari();
engineCapMap.put(DRIVER_SAFARI, capability);
}
{
DesiredCapabilities capability = DesiredCapabilities.operaBlink();
engineCapMap.put(DRIVER_OPERA, capability);
}
}
/**
* firefox
* @param profile
*/
private void fireFoxPreSet(FirefoxProfile profile)
{
BrowserUtil browserUtil = new BrowserUtil();
Map<String, Boolean> boolMap = browserUtil.getFirefoxPreBoolMap();
Iterator<String> boolIt = boolMap.keySet().iterator();
while(boolIt.hasNext())
{
String key = boolIt.next();
profile.setPreference(key, boolMap.get(key));
}
Map<String, Integer> intMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> intIt = intMap.keySet().iterator();
while(intIt.hasNext())
{
String key = intIt.next();
profile.setPreference(key, intMap.get(key));
}
Map<String, Integer> strMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> strIt = intMap.keySet().iterator();
while(strIt.hasNext())
{
String key = strIt.next();
profile.setPreference(key, strMap.get(key));
}
}
/**
* engine
* @param enginePro
*/
private void loadDefaultEnginePath(ClassLoader classLoader, Properties enginePro)
{
URL ieDriverURL = classLoader.getResource("IEDriverServer.exe");
URL chromeDrvierURL = classLoader.getResource("chromedriver.exe");
enginePro.put("webdriver.ie.driver", getLocalFilePath(ieDriverURL));
enginePro.put("webdriver.chrome.driver", getLocalFilePath(chromeDrvierURL));
Enumeration<URL> resurceUrls = null;
URL defaultResourceUrl = null;
try
{
resurceUrls = classLoader.getResources(ENGINE_CONFIG_FILE_NAME);
defaultResourceUrl = classLoader.getResource(ENGINE_CONFIG_FILE_NAME);
}
catch (IOException e)
{
logger.error("Engine properties loading error.", e);
}
if(resurceUrls == null)
{
return;
}
try
{
loadFromURL(enginePro, defaultResourceUrl);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
while(resurceUrls.hasMoreElements())
{
URL url = resurceUrls.nextElement();
if(url.equals(defaultResourceUrl))
{
continue;
}
try
{
loadFromURL(enginePro, url);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
}
// TODO
String os = System.getProperty("os.name");
if(!"Linux".equals(os))
{
}
else
{
}
}
private void loadFromURL(Properties enginePro, URL url) throws IOException
{
try(InputStream inputStream = url.openStream())
{
enginePro.load(inputStream);
}
}
private String getLocalFilePath(URL url)
{
if(url == null)
{
return "";
}
File driverFile = null;
String protocol = url.getProtocol();
if("jar".equals(protocol) || "http".equals(protocol))
{
String driverFileName = ("surenpi.com." + new File(url.getFile()).getName());
try(InputStream inputStream = url.openStream())
{
driverFile = PathUtil.copyFileToRoot(inputStream, driverFileName);
}
catch (IOException e)
{
logger.error("Driver file copy error.", e);
}
}
else
{
try
{
driverFile = new File(URLDecoder.decode(url.getFile(), "utf-8"));
}
catch (UnsupportedEncodingException e)
{
logger.error(e.getMessage(), e);
}
}
if(driverFile != null)
{
return driverFile.getAbsolutePath();
}
else
{
return "";
}
}
/**
*
* @param driver
* @return
*/
public WebDriver turnToRootDriver(WebDriver driver)
{
return driver.switchTo().defaultContent();
}
/**
*
* @param url
*/
public void openUrl(String url)
{
driver.get(url);
}
public void close()
{
if(driver != null)
{
driver.quit();
}
}
/**
* @return
*/
public WebDriver getDriver()
{
return driver;
}
/**
* @return
*/
public String getDriverStr()
{
return driverStr;
}
/**
*
* @param driverStr
*/
public void setDriverStr(String driverStr)
{
this.driverStr = driverStr;
}
public String getRemoteStr()
{
return remoteStr;
}
public void setRemoteStr(String remoteStr)
{
this.remoteStr = remoteStr;
}
/**
* @return
*/
public long getTimeout()
{
return timeout;
}
/**
*
* @param timeout
*/
public void setTimeout(long timeout)
{
this.timeout = timeout;
}
/**
* @return truefalse
*/
public boolean isFullScreen()
{
return fullScreen;
}
/**
*
* @param fullScreen
*/
public void setFullScreen(boolean fullScreen)
{
this.fullScreen = fullScreen;
}
/**
* @return
*/
public int getWidth()
{
return width;
}
/**
*
* @param width
*/
public void setWidth(int width)
{
this.width = width;
}
/**
* @return
*/
public int getHeight()
{
return height;
}
/**
*
* @param height
*/
public void setHeight(int height)
{
this.height = height;
}
/**
* @return the maximize
*/
public boolean isMaximize()
{
return maximize;
}
/**
* @param maximize the maximize to set
*/
public void setMaximize(boolean maximize)
{
this.maximize = maximize;
}
/**
*
* @return
*/
public int computeToolbarHeight()
{
JavascriptExecutor jsExe = (JavascriptExecutor) driver;
Object objectHeight = jsExe.executeScript("return window.outerHeight - window.innerHeight;");
if(objectHeight instanceof Long)
{
toolbarHeight = ((Long) objectHeight).intValue();
}
return toolbarHeight;
}
/**
* @return the toolbarHeight
*/
public int getToolbarHeight()
{
return toolbarHeight;
}
}
|
package com.hpe.caf.api.worker;
import com.hpe.caf.api.Codec;
import com.hpe.caf.api.CodecException;
import com.hpe.caf.api.QuietResource;
import com.hpe.caf.util.ref.DataSource;
import com.hpe.caf.util.ref.DataSourceException;
import com.hpe.caf.util.ref.SourceNotFoundException;
import java.io.InputStream;
import java.util.Objects;
/**
* An implementation of a DataSource that uses a Worker DataStore and a CAF Codec.
* @since 9.0
*/
public class DataStoreSource extends DataSource
{
private final DataStore store;
private final Codec codec;
/**
* Create a new DataStoreSource.
* @param dataStore the store of remote data
* @param codec the method to decode remote data into returned objects
*/
public DataStoreSource(final DataStore dataStore, final Codec codec)
{
this.store = Objects.requireNonNull(dataStore);
this.codec = Objects.requireNonNull(codec);
}
@Override
public <T> T getObject(final String ref, final Class<T> clazz)
throws DataSourceException
{
try ( QuietResource<InputStream> qr = new QuietResource<>(getStream(ref))) {
try {
return codec.deserialise(qr.get(), clazz);
} catch (CodecException e) {
throw new DataSourceException("Could not deserialise stream", e);
}
}
}
@Override
public InputStream getStream(final String ref)
throws DataSourceException
{
try {
return store.getInputStream(ref);
} catch (ReferenceNotFoundException e) {
throw new SourceNotFoundException("Reference not found: " + ref, e);
} catch (DataStoreException e) {
throw new DataSourceException("Failed to get data stream", e);
}
}
}
|
package com.inter6.mail.gui.action;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.annotation.PostConstruct;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.inter6.mail.gui.data.DataPanel;
import com.inter6.mail.job.smtp.AbstractSmtpSendJob;
import com.inter6.mail.job.smtp.SmtpSendJobObserver;
@Component
public class ActionPanel extends JPanel implements SmtpSendJobObserver {
private static final long serialVersionUID = -1786161460680791823L;
@Autowired
private DataPanel dataPanel;
@Autowired
private LogPanel logPanel;
private final JButton startButton = new JButton("Start");
private final JButton stopButton = new JButton("Stop");
private final JCheckBox useMultiThreadCheckBox = new JCheckBox("Multi-Thread");
private final JTextField maxThreadCountFiled = new JTextField(2);
private final JProgressBar progressBar = new JProgressBar();
private final JLabel progressLabel = new JLabel("
private AbstractSmtpSendJob currentJob;
@PostConstruct
private void init() { // NOPMD
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel sendPanel = new JPanel(new FlowLayout());
{
this.startButton.addActionListener(this.startEvent);
sendPanel.add(this.startButton);
sendPanel.add(this.stopButton);
sendPanel.add(this.useMultiThreadCheckBox);
sendPanel.add(new JLabel("Max:"));
sendPanel.add(this.maxThreadCountFiled);
// XXX
this.useMultiThreadCheckBox.setSelected(true);
this.useMultiThreadCheckBox.setEnabled(false);
this.maxThreadCountFiled.setText("8");
this.maxThreadCountFiled.setEnabled(false);
this.stopButton.setEnabled(false);
}
this.add(sendPanel);
JPanel progressPanel = new JPanel(new BorderLayout());
{
progressPanel.add(new JLabel("--:--:--"), BorderLayout.WEST);
this.progressBar.setBorder(new EmptyBorder(0, 10, 0, 10));
this.progressBar.setMaximum(100);
progressPanel.add(this.progressBar, BorderLayout.CENTER);
progressPanel.add(this.progressLabel, BorderLayout.EAST);
}
this.add(progressPanel);
this.add(this.logPanel);
}
private final ActionListener startEvent = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
try {
ActionPanel.this.currentJob = ActionPanel.this.dataPanel.getSendJob();
new Thread(ActionPanel.this.currentJob).start();
} catch (Throwable e) {
ActionPanel.this.logPanel.error("job build fail !", e);
}
}
};
@Override
public void onStart(long startTime) {
// TODO
ActionPanel.this.startButton.setEnabled(false);
ActionPanel.this.stopButton.setEnabled(true);
}
@Override
public void onSuccess() {
// TODO Auto-generated method stub
}
@Override
public void onError(Throwable e) {
// TODO Auto-generated method stub
}
@Override
public void onDone(long startTime, long elapsedTime) {
ActionPanel.this.startButton.setEnabled(true);
ActionPanel.this.stopButton.setEnabled(false);
}
@Override
public void onProgress(float progressRate) {
this.progressBar.setValue((int) progressRate);
this.progressLabel.setText(String.format("%.2f", progressRate) + "%");
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.Repair;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
/**
* An EnsEMBL Healthcheck test case which checks that the protein_feature table agrees with the translation table.
*/
public class ProteinFeatureTranslation extends SingleDatabaseTestCase implements Repair {
// hash of lists of protein features to delete
// key - database name
private Map featuresToDelete;
private static int THRESHOLD = 1000; // don't report a problem if there are less results than this
private static int OUTPUT_LIMIT = 20; // only complain about this many missing translations or long translations
/**
* Create an ProteinFeatureTranslationTestCase that applies to a specific set of databases.
*/
public ProteinFeatureTranslation() {
addToGroup("post_genebuild");
addToGroup("release");
addToGroup("pre-compara-handover");
addToGroup("post-compara-handover");
featuresToDelete = new HashMap();
setFailureText("Large numbers of features longer than the translation indicate something is wrong. A few is probably OK");
setHintLongRunning(true);
setTeamResponsible(Team.GENEBUILD);
}
/**
* This test only applies to core and Vega databases.
*/
public void types() {
removeAppliesToType(DatabaseType.OTHERFEATURES);
removeAppliesToType(DatabaseType.ESTGENE);
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.RNASEQ);
}
/**
* Builds a cache of the translation lengths, then compares them with the values in the protein_features table.
*
* @param dbre
* The database to use.
* @return Result.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
int problems = 0;
// get list of transcripts
String sql = "SELECT t.transcript_id, e.exon_id, tl.start_exon_id, " + " tl.translation_id, tl.end_exon_id, tl.seq_start, " + " tl.seq_end, e.seq_region_start, e.seq_region_end "
+ "FROM transcript t, exon_transcript et, exon e, translation tl " + "WHERE t.transcript_id = et.transcript_id " + "AND et.exon_id = e.exon_id "
+ "AND t.transcript_id = tl.transcript_id " + "ORDER BY t.transcript_id, et.rank";
try {
Connection con = dbre.getConnection();
// check that the protein feature table actually has some rows - if
// not there's
// no point working out the translation lengths
if (!tableHasRows(con, "protein_feature")) {
ReportManager.problem(this, con, "protein_feature table is empty");
return false; // shoud we return true or false in this case?
}
// NOTE: By default the MM MySQL JDBC driver reads and stores *all*
// rows in the
// ResultSet.
// Since this TestCase is likely to produce lots of output, we must
// use the
// "streaming"
// mode where only one row of the ResultSet is stored at a time.
// To do this, the following two lines are both necessary.
// See the README file for the mm MySQL driver.
Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(1000);
Map translationLengths = new HashMap();
// now calculate and store the translation lengths
ResultSet rs = stmt.executeQuery(sql);
rs.setFetchDirection(ResultSet.FETCH_FORWARD);
boolean inCodingRegion = false;
while (rs.next()) {
int currentTranslationID = rs.getInt("translation_id");
Integer id = new Integer(currentTranslationID);
// initialise if necessary
if (translationLengths.get(id) == null) {
translationLengths.put(id, new Integer(0));
}
if (!inCodingRegion) {
if (rs.getInt("start_exon_id") == rs.getInt("exon_id")) {
// single-exon-translations
if (rs.getInt("start_exon_id") == rs.getInt("end_exon_id")) {
int length = (rs.getInt("seq_end") - rs.getInt("seq_start")) + 1;
translationLengths.put(id, new Integer(length));
continue;
}
inCodingRegion = true;
// subtract seq_start
int currentLength = ((Integer) translationLengths.get(id)).intValue();
currentLength -= (rs.getInt("seq_start") - 1);
translationLengths.put(id, new Integer(currentLength));
}
} // if !inCoding
if (inCodingRegion) {
if (rs.getInt("exon_id") == rs.getInt("end_exon_id")) {
// add seq_end
int currentLength = ((Integer) translationLengths.get(id)).intValue();
currentLength += rs.getInt("seq_end");
translationLengths.put(id, new Integer(currentLength));
inCodingRegion = false;
} else {
int currentLength = ((Integer) translationLengths.get(id)).intValue();
currentLength += (rs.getInt("seq_region_end") - rs.getInt("seq_region_start")) + 1;
translationLengths.put(id, new Integer(currentLength));
// inCodingRegion = false;
}
} // if inCoding
} // while rs
rs.close();
stmt.close();
stmt = null;
// Re-open the statement to make sure it's GC'd
stmt = con.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
// stmt.setFetchSize(1000);
stmt.setFetchSize(Integer.MIN_VALUE);
logger.fine("Built translation length cache, about to look at protein features");
// dumpTranslationLengths(con, translationLengths, 100);
// find protein features where seq_end is > than the length of the
// translation
List thisDBFeatures = new ArrayList();
rs = stmt.executeQuery("SELECT protein_feature_id, translation_id, seq_end FROM protein_feature");
while (rs.next()) {
Integer translationID = new Integer(rs.getInt("translation_id"));
Integer proteinFeatureID = new Integer(rs.getInt("protein_feature_id"));
if (translationLengths.get(translationID) != null) {
// some codons can only be 2 bp
int minTranslationLength = (((Integer) translationLengths.get(translationID)).intValue() + 2) / 3;
// int minTranslationLength = ((Integer)
// translationLengths.get(translationID)).intValue();
if (rs.getInt("seq_end") > minTranslationLength) {
thisDBFeatures.add(proteinFeatureID);
// System.out.println("proteinFeatureID: " + proteinFeatureID);
}
} else {
if (problems++ < OUTPUT_LIMIT) {
ReportManager.problem(this, con, "Protein feature " + proteinFeatureID + " refers to non-existent translation " + translationID);
}
}
}
featuresToDelete.put(DBUtils.getShortDatabaseName(con), thisDBFeatures);
if (thisDBFeatures.size() > THRESHOLD) {
ReportManager.problem(this, con, "protein_feature table has " + thisDBFeatures.size() + " features that are longer than the translation");
result = false;
} else if (thisDBFeatures.size() == 0) {
ReportManager.correct(this, con, "protein_feature table has no features that are longer than the translation");
} else {
ReportManager.correct(this, con, "protein_feature table has " + thisDBFeatures.size() + " features that are longer than the translation; this is less than the threshold of " + THRESHOLD);
}
rs.close();
stmt.close();
if (problems >= OUTPUT_LIMIT) {
ReportManager.problem(this, con, "Note that only " + OUTPUT_LIMIT + " missing translation IDs were notified, there may be more");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// Implementation of Repair interface.
/**
* Delete any protein features that run past the end of the translation. <strong>CAUTION! </strong>Actually deletes the features
* from the protein_feature table.
*
* @param dbre
* The database to use.
*/
public void repair(DatabaseRegistryEntry dbre) {
Connection con = dbre.getConnection();
String sql = setupRepairSQL(con);
if (sql.length() == 0) {
System.out.println("No invalid protein features were found in " + DBUtils.getShortDatabaseName(con));
} else {
try {
Statement stmt = con.createStatement();
System.out.println(DBUtils.getShortDatabaseName(con));
System.out.println(sql);
// stmt.execute(sql);
stmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
/**
* Show which protein features would be deleted by the repair method.
*
* @param dbre
* The database to use.
*/
public void show(DatabaseRegistryEntry dbre) {
System.out.println("Candidate for repair:");
Connection con = dbre.getConnection();
String sql = setupRepairSQL(con);
if (sql.length() == 0) {
System.out.println("No invalid protein features were found in " + DBUtils.getShortDatabaseName(con));
} else {
System.out.println(DBUtils.getShortDatabaseName(con) + ": " + sql);
}
}
/**
* Set up the SQL to delete the offending protein features.
*
* @param con
* The database connection to use.
* @return The SQL to delete the incorrect protein features, or "" if there are no problems.
*/
private String setupRepairSQL(Connection con) {
StringBuffer sql = new StringBuffer("DELETE FROM protein_feature WHERE protein_feature_id IN (");
List thisDBFeatures = (List) featuresToDelete.get(DBUtils.getShortDatabaseName(con));
if (thisDBFeatures == null || thisDBFeatures.size() == 0) {
return "";
}
Iterator featureIterator = thisDBFeatures.iterator();
while (featureIterator.hasNext()) {
sql.append(((Integer) featureIterator.next()).intValue());
if (featureIterator.hasNext()) {
sql.append(",");
}
}
sql.append(")");
return sql.toString();
}
// private void dumpTranslationLengths(Connection con, Map lengths, int maxID) {
// System.out.println("Translation lengths for " + DBUtils.getShortDatabaseName(con));
// Set keySet = lengths.keySet();
// List keyList = new ArrayList(keySet);
// Collections.sort(keyList, new IntegerComparator());
// Iterator it = keyList.iterator();
// while (it.hasNext()) {
// Integer iid = (Integer) it.next();
// int id = iid.intValue();
// if (id > maxID) {
// break;
// Integer iLength = (Integer) lengths.get(iid);
// int length = iLength.intValue();
// System.out.println("ID: " + id + "\tLength: " + length);
} // ProteinFeatureTranslationTestCase
|
package com.laytonsmith.core.events;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.annotations.event;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.events.BoundEvent.Priority;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.EventException;
import com.laytonsmith.core.exceptions.FunctionReturnException;
import com.laytonsmith.core.exceptions.PrefilterNonMatchException;
import com.laytonsmith.core.functions.Exceptions;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author layton
*/
public final class EventUtils {
private EventUtils() {
}
private static final Map<Driver, SortedSet<BoundEvent>> event_handles
= new EnumMap<Driver, SortedSet<BoundEvent>>(Driver.class);
/**
* Registers a BoundEvent.
*
* @param b
* @throws EventException
*/
public static void RegisterEvent(BoundEvent b) throws EventException {
Event event = EventList.getEvent(b.getEventName());
if (event == null) {
throw new EventException("The event type \"" + b.getEventName() + "\" could not be found.");
}
if (!event_handles.containsKey(event.driver())) {
event_handles.put(event.driver(), new TreeSet<BoundEvent>());
}
//Check for duplicate IDs
for (Set<BoundEvent> s : event_handles.values()) {
for (BoundEvent bb : s) {
if (bb.getId().equals(b.getId())) {
throw new ConfigRuntimeException("Cannot have duplicate IDs defined."
+ " (Tried to define an event handler with id \"" + b.getId() + "\" at " + b.getTarget() + ","
+ " but it has already been defined at " + bb.getTarget() + ")",
Exceptions.ExceptionType.BindException, b.getTarget());
}
}
}
SortedSet<BoundEvent> set = event_handles.get(event.driver());
set.add(b);
try {
event.bind(b);
} catch (UnsupportedOperationException e) {
}
}
/**
* Looks through all the events for an event with id <code>id</code>. Once
* found, removes it. If no event with that id is registered, nothing
* happens.
*
* @param id
*/
public static void UnregisterEvent(String id) {
for (Driver type : event_handles.keySet()) {
SortedSet<BoundEvent> set = event_handles.get(type);
Iterator<BoundEvent> i = set.iterator();
while (i.hasNext()) {
BoundEvent b = i.next();
if (b.getId().equals(id)) {
i.remove();
return;
}
}
}
}
/**
* Unregisters all event handlers. Runs in O(n)
*/
public static void UnregisterAll(String name) {
for (Driver type : event_handles.keySet()) {
SortedSet<BoundEvent> set = event_handles.get(type);
Iterator<BoundEvent> i = set.iterator();
while (i.hasNext()) {
BoundEvent b = i.next();
if (b.getEventObjName().equals(name)) {
i.remove();
return;
}
}
}
}
/**
* This should be used in the case the plugin is disabled, or /reloadalises
* is run.
*/
public static void UnregisterAll() {
event_handles.clear();
}
/**
* Returns all events driven by type. O(1).
*
* @param type
* @return
*/
public static SortedSet<BoundEvent> GetEvents(Driver type) {
return event_handles.get(type);
}
public static void ManualTrigger(String eventName, CArray object, boolean serverWide) {
for (Driver type : event_handles.keySet()) {
SortedSet<BoundEvent> toRun = new TreeSet<BoundEvent>();
SortedSet<BoundEvent> bounded = GetEvents(type);
Event driver = EventList.getEvent(type, eventName);
if (bounded != null) {
for (BoundEvent b : bounded) {
if (b.getEventName().equalsIgnoreCase(eventName)) {
try {
BindableEvent convertedEvent;
try {
convertedEvent = driver.convert(object);
} catch (ConfigRuntimeException e) {
ConfigRuntimeException.React(e, b.getEnvironment());
continue;
}
if (driver.matches(b.getPrefilter(), convertedEvent)) {
toRun.add(b);
}
} catch (PrefilterNonMatchException ex) {
//Not running this one
}
}
}
}
//If it's not a serverwide event, or this event doesn't support external events.
if (!toRun.isEmpty()) {
if (!serverWide || !driver.supportsExternal()) {
FireListeners(toRun, driver, driver.convert(object));
} else {
//It's serverwide, so we can just trigger it normally with the driver, and it should trickle back down to us
driver.manualTrigger(driver.convert(object));
}
} else {
//They have fired a non existant event
ConfigRuntimeException.DoWarning(ConfigRuntimeException.CreateUncatchableException("Non existant event is being triggered: " + eventName, object.getTarget()));
}
}
}
/**
* Returns a set of events that should be triggered by this event.
*
* @param type
* @param eventName
* @param e
* @return
*/
public static SortedSet<BoundEvent> GetMatchingEvents(Driver type, String eventName, BindableEvent e, Event driver) {
SortedSet<BoundEvent> toRun = new TreeSet<BoundEvent>();
//This is the set of bounded events of this driver type.
//We must now look through the bound events to see if they are
//the eventName, and if so, we will also run the prefilter.
SortedSet<BoundEvent> bounded = GetEvents(type);
if (bounded != null) {
for (BoundEvent b : bounded) {
try {
boolean matches = false;
try {
matches = driver.matches(b.getPrefilter(), e);
} catch (ConfigRuntimeException ex) {
//This can happen in limited cases, but still needs to be
//handled properly. This would happen if, for instance, a
//prefilter was configured improperly with bad runtime data.
//We use the environment from the bound event.
ConfigRuntimeException.React(ex, b.getEnvironment());
}
if (b.getEventName().equals(eventName) && matches) {
toRun.add(b);
}
} catch (PrefilterNonMatchException ex) {
//Not running this one
}
}
}
return toRun;
}
/**
* Triggers an event by name. The event name is the primary filter for this
* event, but to increase event lookup efficiency, the driver is required.
* This will run in O(n), where n is the number of bound events driven by
* type <code>type</code>.
*
* @param type
* @param eventName
* @param e
*/
public static void TriggerListener(Driver type, String eventName, BindableEvent e) {
Event driver = EventList.getEvent(type, eventName);
if (driver == null) {
throw ConfigRuntimeException.CreateUncatchableException("Tried to fire an unknown event: " + eventName, Target.UNKNOWN);
} else {
FireListeners(GetMatchingEvents(type, eventName, e, driver), driver, e);
}
}
public static void FireListeners(SortedSet<BoundEvent> toRun, Event driver, BindableEvent e) {
//Sort our event handlers by priorities
BoundEvent.ActiveEvent activeEvent = new BoundEvent.ActiveEvent(e);
for (BoundEvent b : toRun) {
if (activeEvent.canReceive() || b.getPriority().equals(Priority.MONITOR)) {
try {
//We must re-set the active event's bound event and parsed event
activeEvent.setBoundEvent(b);
activeEvent.setParsedEvent(driver.evaluate(e));
b.trigger(activeEvent);
} catch (FunctionReturnException ex) {
//We also know how to deal with this
} catch (EventException ex) {
throw new ConfigRuntimeException(ex.getMessage(), null, Target.UNKNOWN);
} catch (ConfigRuntimeException ex) {
//An exception has bubbled all the way up
ConfigRuntimeException.React(ex, b.getEnvironment());
}
}
}
for (BoundEvent b : toRun) {
activeEvent.setBoundEvent(b);
if (activeEvent.isCancelled()) {
activeEvent.executeCancelled();
} else {
activeEvent.executeTriggered();
}
}
}
public static Construct DumpEvents() {
CArray ca = new CArray(Target.UNKNOWN);
for (Driver type : event_handles.keySet()) {
SortedSet<BoundEvent> set = event_handles.get(type);
Iterator<BoundEvent> i = set.iterator();
while (i.hasNext()) {
BoundEvent b = i.next();
ca.push(new CString(b.toString() + ":" + b.getFile() + ":" + b.getLineNum(), Target.UNKNOWN));
}
}
return ca;
}
public static void TriggerExternal(BindableEvent mce) {
for (Method m : ClassDiscovery.getDefaultInstance().loadMethodsWithAnnotation(event.class)) {
Class<?>[] params = m.getParameterTypes();
if (params.length != 1 || !BindableEvent.class.isAssignableFrom(params[0])) {
Logger.getLogger(EventUtils.class.getName()).log(Level.SEVERE, "An event handler annotated with @"
+ event.class.getSimpleName() + " may only contain one parameter, which extends "
+ BindableEvent.class.getName());
} else {
try {
Object instance = null;
if ((m.getModifiers() & Modifier.STATIC) == 0) {
//It's not static, so we need an instance. Ideally we could skip
//this step, but it's harder to enforce that across jars.
//We could emit a warning, but the end user wouldn't know what
//to do with that. However, if this step fails (no no-arg constructors
//exist) we will be forced to fail.
// TODO: We could preprocess, as we are for lifecycles, and emit errors.
try {
instance = m.getDeclaringClass().newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate the superclass " + m.getDeclaringClass().getName()
+ ". There is no no-arg constructor present. Ideally however, the method " + m.getName()
+ " would simply be static, which would decrease overhead in general. "
+ " Note to the end user: This error is not a CommandHelper error,"
+ " it is an error in the extension that provides the event handler for"
+ " " + mce.getClass().getName() + ", and should be reported to the extension"
+ " author.", e);
}
}
m.invoke(instance, mce);
} catch (IllegalAccessException ex) {
Logger.getLogger(EventUtils.class.getName()).log(Level.SEVERE,
"Illegal Access Exception while triggering"
+ " an external event:", ex.getCause());
} catch (IllegalArgumentException ex) {
// If we do this, console gets spammed for hooks that don't apply for
// the event being fired. Need to check if mce is instance of params[0].
//Logger.getLogger(EventUtils.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(EventUtils.class.getName()).log(Level.SEVERE,
"Invocation Target Exception while triggering"
+ " an external event:", ex.getCause());
}
}
}
}
}
|
package ch.zhaw.dna.ssh.mapreduce.model;
import static org.junit.Assert.assertEquals;
import ch.zhaw.dna.ssh.mapreduce.model.framework.*;
import org.junit.Before;
import org.junit.Test;
public class WordFrequencyMapTaskTest {
/** jmock context */
/** instance under test */
@Before
public void setUp() {
String testString = "hallo welt ich teste dich hallo";
}
@Test
public void shouldMapInput(){
/*
MapRunner runner = new MapRunner();
*/
WordFrequencyMapTask test = new WordFrequencyMapTask();
//test.map(runner, testString);
//assertEquals("Ergibt Ausgabe", 'hallo, "1"', );
}
}
|
package com.macilias.games.controller;
import com.macilias.games.model.Field;
import java.util.Random;
public class GameImpl implements Game {
private static GameImpl instance;
private Field field;
private boolean isOver = false;
private Random random = new Random(467462421234L);
private long score = 0L;
private GameImpl() {
try {
field = new Field();
} catch (Exception e) {
// should never ever happen
e.printStackTrace();
}
}
private GameImpl(int size) throws Exception {
field = new Field(size);
}
public static GameImpl getInstance() {
if (instance == null) {
instance = new GameImpl();
}
return instance;
}
public static GameImpl getInstance(int size) throws Exception {
if (instance == null) {
instance = new GameImpl(size);
}
return instance;
}
@Override
public Field moveLeft() {
resetField();
for (int i = 0; i < field.field.length; i++) {
field.field[i] = reverse(manipulateRow(reverse(field.field[i])));
}
return returnField();
}
@Override
public Field moveRight() {
resetField();
for (int i = 0; i < field.field.length; i++) {
field.field[i] = manipulateRow(field.field[i]);
}
return returnField();
}
@Override
public Field moveUp() {
resetField();
int[][] temp = transpose(field.field);
for (int i = 0; i < temp.length; i++) {
temp[i] = reverse(manipulateRow(reverse(temp[i])));
}
field.field = transpose(temp);
return returnField();
}
@Override
public Field moveDown() {
resetField();
int[][] temp = transpose(field.field);
for (int i = 0; i < temp.length; i++) {
temp[i] = manipulateRow(temp[i]);
}
field.field = transpose(temp);
return returnField();
}
private void resetField() {
field.setChanged(false);
}
private Field returnField() {
if (field.isChanged() && slotsOpen()) {
addRandom();
}
return field;
}
@Override
public Field getField() {
addRandom();
return field;
}
@Override
public boolean isOver() {
return isOver;
}
@Override
public long getScore() {
return score;
}
@VisibleForTesting
public int[] manipulateRow(int[] row) {
int collisionAt = 0;
for (int i = row.length - 2; i >= 0; i
boolean collated = false;
boolean stopped = false;
int current = row[i];
if (current != 0) {
for (int j = i; j < row.length - 1 && !collated && !stopped; j++) {
int next = row[j + 1];
if (current == next && collisionAt != j + 1) {
collated = true;
collisionAt = j + 1;
int tile = current * 2;
row[j + 1] = tile;
row[j] = 0;
score += tile;
field.setChanged(true);
} else if (next != 0) {
stopped = true;
} else {
row[j + 1] = current;
row[j] = 0;
field.setChanged(true);
}
}
}
}
return row;
}
private int[] reverse(int[] row) {
for (int i = 0; i < row.length / 2; i++) {
int temp = row[i];
row[i] = row[row.length - i - 1];
row[row.length - i - 1] = temp;
}
return row;
}
private int[][] transpose(int[][] field) {
int[][] result = new int[field.length][field[0].length];
for (int i = 0; i < field[0].length; i++) {
for (int j = 0; j < field.length; j++) {
result[i][j] = field[j][i];
}
}
return result;
}
private void addRandom() {
boolean inserted = false;
while (!inserted) {
int rx = random.nextInt(field.field.length);
int ry = random.nextInt(field.field.length);
if (field.field[rx][ry] == 0) {
int rv = random.nextInt(9) == 0 ? 4 : 2;
field.field[rx][ry] = rv;
inserted = true;
}
}
}
private boolean slotsOpen() {
for (int i = 0; i < field.field.length; i++) {
for (int j = 0; j < field.field.length; j++) {
if (field.field[i][j] == 0) {
return true;
}
}
}
isOver = true;
return false;
}
}
|
package com.celements.navigation.filter;
import static com.celements.common.test.CelementsTestUtils.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.xwiki.model.reference.DocumentReference;
import com.celements.common.test.AbstractComponentTest;
import com.celements.navigation.TreeNode;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.user.api.XWikiRightService;
public class InternalRightsFilterTest extends AbstractComponentTest {
private InternalRightsFilter filter;
private XWikiContext context;
private XWiki wiki;
private XWikiRightService rightsService;
@Before
public void setUp_InternalRightsFilterTest() throws Exception {
filter = new InternalRightsFilter();
context = getContext();
wiki = getWikiMock();
rightsService = createMockAndAddToDefault(XWikiRightService.class);
expect(wiki.getRightService()).andReturn(rightsService);
}
@Test
public void testGetMenuPart_NotNull() {
filter = new InternalRightsFilter();
assertNotNull("Must not be null (leads to NPE in checkMenuPart!).", filter.getMenuPart());
}
@Test
public void testSetMenuPart() {
String expectedMenuPart = "mainPart";
filter.setMenuPart(expectedMenuPart);
assertNotNull(filter.getMenuPart());
assertEquals(expectedMenuPart, filter.getMenuPart());
}
@Test
public void testSetMenuPart_null() {
String expectedMenuPart = "";
filter.setMenuPart(null);
assertNotNull(filter.getMenuPart());
assertEquals(expectedMenuPart, filter.getMenuPart());
}
@Test
public void testConvertObject() {
BaseObject baseObj = new BaseObject();
assertSame(baseObj, filter.convertObject(baseObj, context));
}
@Test
@Deprecated
public void testIncludeMenuItem_noViewRights() throws Exception {
String docFullName = "MySpace.MyDoc";
DocumentReference docRef = new DocumentReference(context.getDatabase(), "MySpace", "MyDoc");
BaseObject baseObj = new BaseObject();
baseObj.setDocumentReference(docRef);
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(false);
replayDefault();
assertFalse(filter.includeMenuItem(baseObj, context));
verifyDefault();
}
@Test
@Deprecated
public void testIncludeMenuItem_hasViewRights_noMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
DocumentReference docRef = new DocumentReference(context.getDatabase(), "MySpace", "MyDoc");
BaseObject baseObj = new BaseObject();
baseObj.setDocumentReference(docRef);
filter.setMenuPart("");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertTrue(filter.includeMenuItem(baseObj, context));
verifyDefault();
}
@Test
@Deprecated
public void testIncludeMenuItem_hasViewRights_wrongMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
DocumentReference docRef = new DocumentReference(context.getDatabase(), "MySpace", "MyDoc");
BaseObject baseObj = new BaseObject();
baseObj.setDocumentReference(docRef);
baseObj.setStringValue("part_name", "anotherPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertFalse(filter.includeMenuItem(baseObj, context));
verifyDefault();
}
@Test
@Deprecated
public void testIncludeMenuItem_hasViewRights_matchingMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
DocumentReference docRef = new DocumentReference(context.getDatabase(), "MySpace", "MyDoc");
BaseObject baseObj = new BaseObject();
baseObj.setDocumentReference(docRef);
baseObj.setStringValue("part_name", "mainPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertTrue(filter.includeMenuItem(baseObj, context));
verifyDefault();
}
@Test
@Deprecated
public void testIncludeMenuItem_Exception() throws Exception {
String docFullName = "MySpace.MyDoc";
DocumentReference docRef = new DocumentReference(context.getDatabase(), "MySpace", "MyDoc");
BaseObject baseObj = new BaseObject();
baseObj.setDocumentReference(docRef);
baseObj.setStringValue("part_name", "mainPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andThrow(new XWikiException());
replayDefault();
assertFalse(filter.includeMenuItem(baseObj, context));
verifyDefault();
}
@Test
public void testIncludeTreeNode_noViewRights() throws Exception {
String docFullName = "MySpace.MyDoc";
TreeNode node = new TreeNode(new DocumentReference(context.getDatabase(), "MySpace", "MyDoc"),
null, 0);
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(false);
replayDefault();
assertFalse(filter.includeTreeNode(node, context));
verifyDefault();
}
@Test
public void testIncludeTreeNode_hasViewRights_noMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
TreeNode node = new TreeNode(new DocumentReference(context.getDatabase(), "MySpace", "MyDoc"),
null, 0);
filter.setMenuPart("");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertTrue(filter.includeTreeNode(node, context));
verifyDefault();
}
@Test
public void testIncludeTreeNode_hasViewRights_wrongMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
TreeNode node = new TreeNode(new DocumentReference(context.getDatabase(), "MySpace", "MyDoc"),
null, 0, "anotherPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertFalse(filter.includeTreeNode(node, context));
verifyDefault();
}
@Test
public void testIncludeTreeNode_hasViewRights_matchingMenuPart() throws Exception {
String docFullName = "MySpace.MyDoc";
TreeNode node = new TreeNode(new DocumentReference(context.getDatabase(), "MySpace", "MyDoc"),
null, 0, "mainPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andReturn(true);
replayDefault();
assertTrue(filter.includeTreeNode(node, context));
verifyDefault();
}
@Test
public void testIncludeTreeNode_Exception() throws Exception {
String docFullName = "MySpace.MyDoc";
TreeNode node = new TreeNode(new DocumentReference(context.getDatabase(), "MySpace", "MyDoc"),
null, 0, "mainPart");
filter.setMenuPart("mainPart");
expect(rightsService.hasAccessLevel(eq("view"), eq(context.getUser()), eq(context.getDatabase()
+ ":" + docFullName), same(context))).andThrow(new XWikiException());
replayDefault();
assertFalse(filter.includeTreeNode(node, context));
verifyDefault();
}
}
|
package com.metacodestudio.hotsuploader;
import com.metacodestudio.hotsuploader.controllers.HomeController;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowHandler;
import io.datafx.controller.flow.container.DefaultFlowContainer;
import io.datafx.controller.flow.context.ViewFlowContext;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.io.File;
public class Client extends Application {
private static File hotsRoot;
public static File getHotsRoot() {
return hotsRoot;
}
public static void main(String[] args) {
hotsRoot = getRootDirectory();
Application.launch(Client.class, args);
}
private static File getRootDirectory() {
StringBuilder builder = new StringBuilder(System.getProperty("user.home"));
if (isWindows()) {
builder.append("\\Documents\\Heroes of the Storm\\Accounts\\");
} else if (isMacintosh()) {
builder.append("/Library/Application Support/Blizzard/Heroes of the Storm/Accounts/");
} else {
throw new UnsupportedOperationException("This application requires Windows or Macintosh OSX to run");
}
return new File(builder.toString());
}
private static boolean isMacintosh() {
// TODO DETERMINE MACINTOSH PROPERTIES
throw new UnsupportedOperationException("Macintosh check not yet implemented");
}
private static boolean isWindows() {
String osName = System.getProperty("os.name");
return osName.contains("Windows");
}
@Override
public void start(final Stage primaryStage) throws Exception {
Flow flow = new Flow(HomeController.class);
FlowHandler flowHandler = flow.createHandler(new ViewFlowContext());
DefaultFlowContainer container = new DefaultFlowContainer();
StackPane pane = flowHandler.start(container);
primaryStage.setScene(new Scene(pane));
primaryStage.setOnCloseRequest(event -> System.exit(0));
primaryStage.show();
}
}
|
package com.mikesamuel.cil.ast.meta;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.mikesamuel.cil.ast.AssignmentNode;
import com.mikesamuel.cil.ast.AssignmentOperatorNode;
import com.mikesamuel.cil.ast.FloatingPointTypeNode;
import com.mikesamuel.cil.ast.IntegralTypeNode;
import com.mikesamuel.cil.ast.NumericTypeNode;
import com.mikesamuel.cil.ast.PrimitiveTypeNode;
import com.mikesamuel.cil.ast.meta.TypeSpecification.TypeBinding;
import com.mikesamuel.cil.ast.meta.TypeSpecification.Variance;
import com.mikesamuel.cil.parser.SourcePosition;
/**
* Represents a Java type.
*/
@SuppressWarnings("synthetic-access")
public abstract class StaticType {
/** The specification for this type. */
public final TypeSpecification typeSpecification;
private StaticType(TypeSpecification spec) {
this.typeSpecification = spec;
}
@Override
public abstract String toString();
public abstract String toDescriptor();
/**
* A type that does not use any generic elements.
*/
public abstract StaticType toErasedType();
@Override
public abstract boolean equals(Object o);
@Override
public abstract int hashCode();
/**
* The operation needed to convert from an output of type t to an input of
* this type.
*/
public abstract Cast assignableFrom(StaticType t);
/**
* Extracts a primitive type from a node.
*/
public static PrimitiveType fromParseTree(PrimitiveTypeNode pt) {
switch (pt.getVariant()) {
case AnnotationBoolean:
return T_BOOLEAN;
case AnnotationNumericType:
NumericTypeNode ntn = pt.firstChildWithType(NumericTypeNode.class);
if (ntn == null) {
throw new IllegalArgumentException("Missing numeric type");
}
switch (ntn.getVariant()) {
case FloatingPointType:
FloatingPointTypeNode ftn = ntn.firstChildWithType(
FloatingPointTypeNode.class);
if (ftn == null) {
throw new IllegalArgumentException("Missing float type");
}
switch (ftn.getVariant()) {
case Double:
return T_DOUBLE;
case Float:
return T_FLOAT;
}
throw new AssertionError(ftn.getVariant());
case IntegralType:
IntegralTypeNode itn = pt.firstChildWithType(
IntegralTypeNode.class);
switch (itn.getVariant()) {
case Byte:
return T_BYTE;
case Char:
return T_CHAR;
case Int:
return T_INT;
case Long:
return T_LONG;
case Short:
return T_SHORT;
}
throw new AssertionError(itn.getVariant());
}
throw new AssertionError(ntn.getValue());
}
throw new AssertionError(pt.getValue());
}
/**
* Type relationships.
*/
public enum Cast {
/** Types are incompatible. */
DISJOINT,
/** Types are equivalent. */
SAME,
/**
* For example, a cast from {@code int} to {@code short} that can lead to
* loss of precision.
* Conversions between {@code short} and {@code char} are considered lossy
* because of reinterpetation of the MSB.
*/
CONVERTING_LOSSY(true),
/** For example, a cast from {@code short} to {@code int}. */
CONVERTING_LOSSLESS,
/** For example, a cast from {@code String} to {@code Object}. */
CONFIRM_SAFE,
/**
* For example, a cast from {@code Object} to {@code String}
* that can fail at runtime.
*/
CONFIRM_CHECKED(true),
/**
* For example, a cast from {@code List} to {@code List<String>}
* that is generic-type unsound.
*/
CONFIRM_UNCHECKED,
/**
* For example, a conversion from {@code int} to {@code /java/lang/Integer}.
*/
BOX,
/**
* For example, a conversion from {@code /java/lang/Integer} to {@code int}.
*/
UNBOX,
;
/**
* Whether the type conversion can be done implicitly.
* There are some wrinkles to this.
* Specifically in an {@link AssignmentNode} where the
* {@link AssignmentOperatorNode} is not {@code =},
* {@link #CONVERTING_LOSSY} operations can occur implicitly.
*/
public final boolean explicit;
Cast() {
this(false);
}
Cast(boolean explicit) {
this.explicit = explicit;
}
}
/** Base type for primitive types. */
public static abstract class PrimitiveType extends StaticType {
/** Keyword that specifies this type. */
public final String name;
/** The wrapper class. */
public final @Nullable Name wrapperType;
final String descriptorFragment;
private PrimitiveType(
String name, @Nullable Name wrapperType, @Nullable Name specType,
String descriptorFragment) {
super(new TypeSpecification(
specType != null
? specType
: wrapperType.child("TYPE", Name.Type.FIELD)));
this.name = name;
this.wrapperType = wrapperType;
this.descriptorFragment = descriptorFragment;
}
@Override
public PrimitiveType toErasedType() {
return this;
}
@Override
public String toDescriptor() {
return descriptorFragment;
}
}
/**
* A numeric primitive type.
*/
public static final class NumericType extends PrimitiveType {
/** True iff a floating point type. */
public final boolean isFloaty;
/** sizeof this type. */
public final int byteWidth;
/** True iff the type is signed. */
public final boolean isSigned;
private NumericType(
String name, boolean isFloaty, int byteWidth,
boolean isSigned, Name wrapperType,
String descriptorFragment) {
super(name, wrapperType, null, descriptorFragment);
this.isFloaty = isFloaty;
this.byteWidth = byteWidth;
this.isSigned = isSigned;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
return o instanceof NumericType && name.equals(((NumericType) o).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public Cast assignableFrom(StaticType t) {
if (t == ERROR_TYPE) {
return Cast.UNBOX;
}
if (t instanceof NumericType) {
NumericType nt = (NumericType) t;
if (this.name.equals(nt.name)) {
return Cast.SAME;
}
if (this.isFloaty == nt.isFloaty) {
return this.byteWidth < nt.byteWidth
|| (this.byteWidth == nt.byteWidth
&& this.isSigned != nt.isSigned)
? Cast.CONVERTING_LOSSY // double -> float, long -> int
: Cast.CONVERTING_LOSSLESS; // float -> double, int -> long
} else {
return this.isFloaty
? Cast.CONVERTING_LOSSLESS
: Cast.CONVERTING_LOSSY;
}
}
if (t instanceof TypePool.ClassOrInterfaceType
&& ((TypePool.ClassOrInterfaceType) t)
.getBaseTypeName().equals(wrapperType)) {
return Cast.UNBOX;
}
return Cast.DISJOINT;
}
}
private static final Name JAVA =
Name.DEFAULT_PACKAGE.child("java", Name.Type.PACKAGE);
private static final Name JAVA_LANG =
JAVA.child("lang", Name.Type.PACKAGE);
static final Name JAVA_LANG_OBJECT =
JAVA_LANG.child("Object", Name.Type.CLASS);
private static final Name JAVA_LANG_CLONEABLE =
JAVA_LANG.child("Cloneable", Name.Type.CLASS);
/** A type returned when a type is malformed. */
public static StaticType ERROR_TYPE = new StaticType(
new TypeSpecification(
Name.DEFAULT_PACKAGE
.child("error", Name.Type.PACKAGE)
.child("ErrorType", Name.Type.CLASS)
.child("TYPE", Name.Type.FIELD))) {
@Override
public String toString() {
return ERROR_TYPE.typeSpecification.toString();
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public Cast assignableFrom(StaticType t) {
if (t == this) { return Cast.SAME; }
if (t == T_VOID) { return Cast.DISJOINT; }
if (t instanceof PrimitiveType) {
return Cast.BOX;
}
if (t instanceof TypePool.ReferenceType) {
return Cast.CONFIRM_UNCHECKED;
}
throw new AssertionError(t);
}
@Override
public String toDescriptor() {
return "X";
}
@Override
public StaticType toErasedType() {
return this;
}
};
private static final class OneOffType extends PrimitiveType {
private OneOffType(
String name, @Nullable Name wrapperType, @Nullable Name specTypeName,
String descriptorFragment) {
super(name, wrapperType, specTypeName, descriptorFragment);
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
return o instanceof OneOffType && name.equals(((OneOffType) o).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public Cast assignableFrom(StaticType t) {
if (this.equals(t)) {
return Cast.SAME;
}
if (t == ERROR_TYPE && !"void".equals(name)) {
return Cast.UNBOX;
}
if (wrapperType != null && t instanceof TypePool.ClassOrInterfaceType
&& ((TypePool.ClassOrInterfaceType) t).getBaseTypeName()
.equals(wrapperType)) {
return Cast.UNBOX;
}
return Cast.DISJOINT;
}
}
/** Type {@code byte} */
public static final PrimitiveType T_VOID = new OneOffType(
"void", null,
JAVA_LANG.child("Void", Name.Type.CLASS).child("TYPE", Name.Type.FIELD),
"V");
/** Type {@code byte} */
public static final PrimitiveType T_BOOLEAN = new OneOffType(
"boolean", JAVA_LANG.child("Boolean", Name.Type.CLASS), null,
"Z");
/** Type {@code byte} */
public static final NumericType T_BYTE = new NumericType(
"byte", false, 1, true,
JAVA_LANG.child("Byte", Name.Type.CLASS), "B");
/** Type {@code short} */
public static final NumericType T_SHORT = new NumericType(
"short", false, 2, true,
JAVA_LANG.child("Short", Name.Type.CLASS), "S");
/** Type {@code char} */
public static final NumericType T_CHAR = new NumericType(
"char", false, 2, false,
JAVA_LANG.child("Character", Name.Type.CLASS), "C");
/** Type {@code int} */
public static final NumericType T_INT = new NumericType(
"int", false, 4, true,
JAVA_LANG.child("Integer", Name.Type.CLASS), "I");
/** Type {@code long} */
public static final NumericType T_LONG = new NumericType(
"long", false, 8, true,
JAVA_LANG.child("Long", Name.Type.CLASS), "J");
/** Type {@code float} */
public static final NumericType T_FLOAT = new NumericType(
"float", true, 4, true,
JAVA_LANG.child("Float", Name.Type.CLASS), "F");
/** Type {@code double} */
public static final NumericType T_DOUBLE = new NumericType(
"double", true, 8, true,
JAVA_LANG.child("Double", Name.Type.CLASS), "D");
private static final Set<Name> ARRAY_SUPER_TYPES = ImmutableSet.of(
JAVA_LANG_OBJECT,
JAVA_LANG_CLONEABLE,
JAVA.child("io", Name.Type.PACKAGE).child("Serializable", Name.Type.CLASS)
);
/**
* All the primitive types.
*/
public static final ImmutableList<PrimitiveType> PRIMITIVE_TYPES =
ImmutableList.of(
T_BOOLEAN,
T_BYTE,
T_CHAR,
T_SHORT,
T_INT,
T_FLOAT,
T_LONG,
T_DOUBLE);
/**
* Maintains a mapping of names to class or interface types so that we can
* memoize sub-type checks.
* <p>
* This is roughly analogous to a class loader but we need not handle
* parent loaders since {@code javac} assumes (until {@code -source 9}) that
* all classes compiled together can address one another modulo visibility.
*/
public static final class TypePool {
/** Used to resolve names to type info. */
public final TypeInfoResolver r;
public TypePool(TypeInfoResolver r) {
this.r = r;
}
/**
* Special type for the {@code null} value which is a reference bottom type.
*/
public final ReferenceType T_NULL = new NullType();
private final Map<TypeSpecification, StaticType> pool =
Maps.newHashMap();
{
// Seed the pool so that type(spec) works.
pool.put(T_VOID.typeSpecification, T_VOID);
pool.put(T_BOOLEAN.typeSpecification, T_BOOLEAN);
pool.put(T_BYTE.typeSpecification, T_BYTE);
pool.put(T_SHORT.typeSpecification, T_SHORT);
pool.put(T_CHAR.typeSpecification, T_CHAR);
pool.put(T_INT.typeSpecification, T_INT);
pool.put(T_LONG.typeSpecification, T_LONG);
pool.put(T_FLOAT.typeSpecification, T_FLOAT);
pool.put(T_DOUBLE.typeSpecification, T_DOUBLE);
pool.put(ERROR_TYPE.typeSpecification, ERROR_TYPE);
pool.put(T_NULL.typeSpecification, T_NULL);
}
/**
* @param tspec specifices the type to return.
* @param pos to use with any log messages.
* @param logger receives error messages related to
*/
public StaticType type(
TypeSpecification tspec,
@Nullable SourcePosition pos, @Nullable Logger logger) {
return pool.computeIfAbsent(
tspec.canon(r),
new Function<TypeSpecification, StaticType>() {
@Override
public StaticType apply(TypeSpecification ts) {
if (ts.nDims > 0) {
TypeSpecification elementSpec = new TypeSpecification(
ts.typeName, ts.bindings, ts.nDims - 1);
return new ArrayType(ts, type(elementSpec, pos, logger));
}
// Check that the type exists.
if (!ts.typeName.type.isType) {
// Primitive types should not reach here due to cache seeding
// above, but malformed types like int<String> might.
logger.severe(
(pos != null ? pos + ": " : "")
+ " type name " + ts.typeName + " does not specify a type");
if (!ts.bindings.isEmpty()) {
TypeSpecification withoutBindings = new TypeSpecification(
ts.typeName);
if (pool.containsKey(withoutBindings)) {
return pool.get(withoutBindings);
}
}
return ERROR_TYPE;
}
Optional<TypeInfo> tiOpt = r.resolve(ts.typeName);
if (!tiOpt.isPresent()) {
Thread.dumpStack();
logger.severe(
(pos != null ? pos + ": " : "")
+ " type name " + ts.typeName + " does not specify a type");
return ERROR_TYPE;
}
TypeInfo ti = tiOpt.get();
// Check type parameter count and bounds.
boolean bindingsOk = true;
if (!ts.bindings.isEmpty()) {
// Not a raw type
if (ts.bindings.size() != ti.parameters.size()) {
logger.severe(
(pos != null ? pos + ": " : "")
+ " type " + ts
+ " has the wrong number of type parameters");
bindingsOk = false;
} else {
// TODO: figure out how to check type bounds
// We may not actually need to do this since we allow
// common passes latitude on inputs that are not compiling
// java programs.
// This is also complicated by recursive type specifications.
}
}
if (!bindingsOk) {
TypeSpecification rawSpec = new TypeSpecification(ts.typeName);
return type(rawSpec, pos, logger);
}
return new ClassOrInterfaceType(ts, ti);
}
});
}
/** Base type for primitive types. */
public abstract class ReferenceType extends StaticType {
private ReferenceType(TypeSpecification spec) {
super(spec);
}
/**
* The type pool associated with this.
*/
public TypePool getPool() {
return TypePool.this;
}
}
private final class NullType extends ReferenceType {
private NullType() {
super(new TypeSpecification(
// Outside normal type namespace since null is a keyword.
Name.DEFAULT_PACKAGE.child("null", Name.Type.CLASS)));
}
@Override
public String toString() {
return "<null>";
}
@Override
public String toDescriptor() {
return ERROR_TYPE.toDescriptor();
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public Cast assignableFrom(StaticType t) {
if (t == this) {
return Cast.SAME;
}
if (ERROR_TYPE.equals(t)) {
return Cast.CONFIRM_UNCHECKED;
}
if (t instanceof ReferenceType) {
return Cast.CONFIRM_CHECKED;
}
// The <null> type may be assignable to Integer but it does not
// participate in unboxing.
return Cast.DISJOINT;
}
@Override
public StaticType toErasedType() {
return this;
}
}
/**
* A class or interface type.
*/
public final class ClassOrInterfaceType extends ReferenceType {
/**
* The type info for the type.
*/
public final TypeInfo info;
/**
* Any type parameter bindings that correspond to info.parameters.
*/
public final ImmutableList<TypeBinding> typeParameterBindings;
private ImmutableMap<Name, ClassOrInterfaceType> superTypesTransitive;
private ClassOrInterfaceType(
TypeSpecification spec,
TypeInfo info) {
super(spec);
this.info = info;
this.typeParameterBindings = spec.bindings;
}
/** The name of the raw type. */
public Name getBaseTypeName() {
return info.canonName;
}
@Override
public StaticType toErasedType() {
TypeSpecification erasedSpec;
if (info.canonName.type == Name.Type.CLASS) {
if (this.typeParameterBindings.isEmpty()) {
return this;
} else {
erasedSpec = typeSpecification.withBindings(ImmutableList.of());
}
} else {
Preconditions.checkState(
Name.Type.TYPE_PARAMETER == info.canonName.type);
erasedSpec = info.superType.or(TypeSpecification.JAVA_LANG_OBJECT)
.withBindings(ImmutableList.of());
}
return type(erasedSpec, null, null).toErasedType();
}
@Override
public String toString() {
if (typeParameterBindings.isEmpty()) {
return info.canonName.toString();
}
StringBuilder sb = new StringBuilder();
sb.append(info.canonName);
sb.append('<');
for (int i = 0, n = typeParameterBindings.size(); i < n; ++i) {
if (i != 0) {
sb.append(',');
}
sb.append(typeParameterBindings.get(i));
}
sb.append('>');
return sb.toString();
}
Map<Name, ClassOrInterfaceType> getSuperTypesTransitive() {
if (this.superTypesTransitive == null) {
Map<Name, ClassOrInterfaceType> m = new LinkedHashMap<>();
m.put(info.canonName, this);
for (TypeSpecification ts : r.superTypesOf(this.typeSpecification)) {
if (!m.containsKey(ts.typeName)) {
StaticType superType = TypePool.this.type(ts, null, null);
if (superType instanceof ClassOrInterfaceType) { // Not error
ClassOrInterfaceType superCT = (ClassOrInterfaceType) superType;
m.put(ts.typeName, superCT);
// TODO: Fails to halt if dep cycles.
for (Map.Entry<Name, ClassOrInterfaceType> e :
superCT.getSuperTypesTransitive().entrySet()) {
m.putIfAbsent(e.getKey(), e.getValue());
}
}
}
}
this.superTypesTransitive = ImmutableMap.copyOf(m);
}
return this.superTypesTransitive;
}
@Override
public Cast assignableFrom(StaticType t) {
if (ERROR_TYPE.equals(t)) {
return Cast.CONFIRM_UNCHECKED;
}
if (t instanceof NullType) {
return Cast.CONFIRM_SAFE;
}
if (t instanceof ClassOrInterfaceType) {
ClassOrInterfaceType ct = (ClassOrInterfaceType) t;
if (info.canonName.equals(ct.info.canonName)) {
// This single-class-loader-esque assumption is valid for all code
// compiled together.
if (this.typeParameterBindings.equals(ct.typeParameterBindings)) {
return Cast.SAME;
} else if (this.typeParameterBindings.isEmpty()) {
// Optimistic raw type assumptions.
return Cast.CONFIRM_SAFE;
} else if (ct.typeParameterBindings.isEmpty()) {
return Cast.CONFIRM_UNCHECKED;
} else {
int n = typeParameterBindings.size();
Preconditions.checkState(n == ct.typeParameterBindings.size());
// Optimistically assume this, and look for reasons to downgrade
// to disjoint or unchecked.
Cast result = Cast.CONFIRM_SAFE;
// Check parameters pairwise taking variance into account.
for (int i = 0; i < n; ++i) {
TypeBinding left = typeParameterBindings.get(i);
TypeBinding right = ct.typeParameterBindings.get(i);
if (left.variance == Variance.INVARIANT
&& right.variance == Variance.INVARIANT) {
if (!left.equals(right)) {
return Cast.DISJOINT;
}
continue;
}
StaticType leftType = type(left.typeSpec, null, null);
StaticType rightType = type(right.typeSpec, null, null);
Cast pc = leftType.assignableFrom(rightType);
switch (pc) {
case DISJOINT:
return Cast.DISJOINT;
case SAME:
if (left.variance != right.variance
&& right.variance != Variance.INVARIANT) {
result = Cast.CONFIRM_UNCHECKED;
}
continue;
case CONFIRM_SAFE:
if (right.variance == Variance.SUPER
// Special case
// X<? super Foo> y = ...;
// X<? extends Object> x = y;
// which is safe because all parameter bindings are
// reference types and Object is a top for reference
// types.
&& (left.variance != Variance.EXTENDS
|| !JAVA_LANG_OBJECT.equals(
left.typeSpec.typeName))) {
result = Cast.CONFIRM_UNCHECKED;
} else if (left.variance != Variance.EXTENDS) {
return Cast.DISJOINT;
}
break;
case CONFIRM_CHECKED:
if (right.variance == Variance.EXTENDS) {
result = Cast.CONFIRM_UNCHECKED;
} else if (left.variance != Variance.SUPER) {
return Cast.DISJOINT;
}
break;
case CONFIRM_UNCHECKED:
result = Cast.CONFIRM_UNCHECKED;
break;
case BOX:
case CONVERTING_LOSSLESS:
case CONVERTING_LOSSY:
case UNBOX:
throw new AssertionError(
left + " =~= " + right + " => " + pc);
}
}
return result;
}
}
Map<Name, ClassOrInterfaceType> ctSuperTypes =
ct.getSuperTypesTransitive();
ClassOrInterfaceType ctCommonSuperType = ctSuperTypes.get(
info.canonName);
if (ctCommonSuperType != null) {
Cast castToCtCommonSuper = this.assignableFrom(ctCommonSuperType);
switch (castToCtCommonSuper) {
case SAME:
return Cast.CONFIRM_SAFE;
case CONFIRM_SAFE:
case CONFIRM_CHECKED: // Is this right?
case CONFIRM_UNCHECKED:
return castToCtCommonSuper;
case CONVERTING_LOSSLESS:
case CONVERTING_LOSSY:
case DISJOINT:
case BOX:
case UNBOX:
throw new AssertionError(castToCtCommonSuper);
}
}
Map<Name, ClassOrInterfaceType> superTypes =
getSuperTypesTransitive();
ClassOrInterfaceType commonSuperType = superTypes.get(
ct.info.canonName);
if (commonSuperType != null) {
Cast castToCommonSuper = commonSuperType.assignableFrom(ct);
switch (castToCommonSuper) {
case SAME:
return Cast.CONFIRM_CHECKED;
case CONFIRM_SAFE:
case CONFIRM_CHECKED: // Is this right?
case CONFIRM_UNCHECKED:
return castToCommonSuper;
case CONVERTING_LOSSLESS:
case CONVERTING_LOSSY:
case DISJOINT:
case BOX:
case UNBOX:
throw new AssertionError(castToCommonSuper);
}
}
// TODO: Do we need to work on the case where this is a type parameter
// and use its upper bound above?
return Cast.DISJOINT;
}
if (t instanceof PrimitiveType) {
PrimitiveType pt = (PrimitiveType) t;
if (pt.wrapperType == null) {
return Cast.DISJOINT;
}
if (this.info.canonName.equals(pt.wrapperType)) {
return Cast.BOX;
}
StaticType wrapperType = type(
new TypeSpecification(pt.wrapperType), null, null);
Cast c = assignableFrom(wrapperType);
switch (c) {
case BOX:
case UNBOX:
case CONVERTING_LOSSLESS:
case CONVERTING_LOSSY:
throw new AssertionError();
case CONFIRM_CHECKED:
case CONFIRM_UNCHECKED:
return Cast.DISJOINT;
case CONFIRM_SAFE:
// E.g. Number n = intExpression;
return Cast.BOX;
case DISJOINT:
return Cast.DISJOINT;
case SAME:
return Cast.BOX;
}
throw new AssertionError(c);
}
if (t instanceof ArrayType) {
if (ARRAY_SUPER_TYPES.contains(info.canonName)) {
return Cast.CONFIRM_SAFE;
}
return Cast.DISJOINT;
}
throw new IllegalArgumentException(t.getClass().getName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + info.canonName.hashCode();
result = prime * result + r.hashCode();
result = prime * result + typeParameterBindings.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ClassOrInterfaceType other = (ClassOrInterfaceType) obj;
if (info == null) {
if (other.info != null) {
return false;
}
} else if (!info.canonName.equals(other.info.canonName)) {
return false;
}
if (getPool() != other.getPool()) {
return false;
}
if (typeParameterBindings == null) {
if (other.typeParameterBindings != null) {
return false;
}
} else if (!typeParameterBindings.equals(other.typeParameterBindings)) {
return false;
}
return true;
}
@Override
public String toDescriptor() {
if (info.canonName.type == Name.Type.TYPE_PARAMETER) {
Preconditions.checkState(info.superType.isPresent());
// Mimic type-erasure by using the upper-type bound.
return type(info.superType.get(), null, null).toDescriptor();
}
StringBuilder sb = new StringBuilder();
sb.append('L');
toDescriptor(this.info.canonName, sb);
return sb.append(';').toString();
}
private Name.Type toDescriptor(Name nm, StringBuilder sb) {
if (nm == Name.DEFAULT_PACKAGE) {
return null;
}
Name.Type parentType = toDescriptor(nm.parent, sb);
switch (nm.type) {
case CLASS:
if (parentType == Name.Type.CLASS) {
sb.append('$');
} else if (parentType == Name.Type.PACKAGE) {
sb.append('/');
}
sb.append(nm.identifier);
return Name.Type.CLASS;
case PACKAGE:
if (parentType != null) {
sb.append('/');
}
sb.append(nm.identifier);
return Name.Type.PACKAGE;
default:
return parentType;
}
}
}
/**
* Type for an array type.
*/
public final class ArrayType extends ReferenceType {
/** The type of the elements of arrays with this static type. */
public final StaticType elementType;
/**
* The type of the elements of the innermost array.
* This will never be itself an array type.
*/
public final StaticType baseElementType;
/**
* One greater than the dimensionality of the element type or 1 if the
* element type is not itself an array type.
*/
public final int dimensionality;
private ArrayType(TypeSpecification spec, StaticType elementType) {
super(spec);
this.elementType = elementType;
if (elementType instanceof ArrayType) {
ArrayType at = (ArrayType) elementType;
this.dimensionality = at.dimensionality + 1;
this.baseElementType = at.baseElementType;
} else {
this.dimensionality = 1;
this.baseElementType = elementType;
}
}
@Override
public StaticType toErasedType() {
StaticType erasedBaseType = baseElementType.toErasedType();
int nDims = this.typeSpecification.nDims
- baseElementType.typeSpecification.nDims
+ erasedBaseType.typeSpecification.nDims;
return type(new TypeSpecification(
erasedBaseType.typeSpecification.typeName, nDims), null, null);
}
@Override
public String toDescriptor() {
return "[" + elementType.toDescriptor();
}
@Override
public String toString() {
return elementType + "[]";
}
@Override
public boolean equals(Object o) {
return (o instanceof ArrayType)
&& elementType.equals(((ArrayType) o).elementType);
}
@Override
public int hashCode() {
return elementType.hashCode() ^ 0xe20d66a3;
}
@Override
public Cast assignableFrom(StaticType t) {
if (ERROR_TYPE.equals(t)) {
return Cast.CONFIRM_UNCHECKED;
}
if (t instanceof NullType) {
return Cast.CONFIRM_SAFE;
}
if (t instanceof PrimitiveType) {
return Cast.DISJOINT;
}
if (t instanceof ClassOrInterfaceType) {
ClassOrInterfaceType cit = (ClassOrInterfaceType) t;
if (ARRAY_SUPER_TYPES.contains(cit.info.canonName)) {
return Cast.CONFIRM_CHECKED;
}
return Cast.DISJOINT;
}
Preconditions.checkArgument(t instanceof ArrayType);
ArrayType at = (ArrayType) t;
int dimDelta = this.dimensionality - at.dimensionality;
if (dimDelta == 0) {
Cast ec = elementType.assignableFrom(at.elementType);
switch (ec) {
case SAME:
case DISJOINT:
case CONFIRM_CHECKED:
case CONFIRM_SAFE:
case CONFIRM_UNCHECKED:
return ec;
case BOX:
case UNBOX:
case CONVERTING_LOSSLESS:
case CONVERTING_LOSSY:
return Cast.DISJOINT;
}
throw new AssertionError(ec);
} else {
StaticType a = this;
StaticType b = at;
while (a instanceof ArrayType && b instanceof ArrayType) {
a = ((ArrayType) a).elementType;
b = ((ArrayType) b).elementType;
}
return a.assignableFrom(b);
}
}
}
}
}
|
package com.nhn.pinpoint.web.vo;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nhn.pinpoint.common.HistogramSlot;
import com.nhn.pinpoint.web.util.TimeWindowUtils;
/**
*
* @author netspider
*
*/
public class LinkStatistics {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final short SLOT_SLOW = Short.MAX_VALUE - 1;
private static final short SLOT_ERROR = Short.MAX_VALUE;
// /**
// * <pre>
// * key = responseTimeslot
// * value = count
// * </pre>
// */
// private final SortedMap<Integer, Long> histogramSummary = new TreeMap<Integer, Long>();;
/**
* <pre>
* index = responseTimeslot index,
* value = key=timestamp, value=value
* </pre>
*/
private final List<SortedMap<Long, Long>> timeseriesValueList = new ArrayList<SortedMap<Long, Long>>();
private final SortedMap<Short, Integer> timeseriesSlotIndex = new TreeMap<Short, Integer>();
private final long from;
private final long to;
private long successCount = 0;
private long failedCount = 0;
public LinkStatistics(long from, long to) {
this.from = from;
this.to = to;
}
/**
* timeseries . . ..
*
* @return
*/
private SortedMap<Long, Long> makeEmptyTimeseriesValueMap() {
SortedMap<Long, Long> map = new TreeMap<Long, Long>();
long windowSize = TimeWindowUtils.getWindowSize(from, to);
for (long time = from; time <= to; time += windowSize) {
map.put(time, 0L);
}
return map;
}
/**
* histogram slot view slot 0 . key
* . .
*
* @param slotList
*/
public void setDefaultHistogramSlotList(List<HistogramSlot> slotList) {
if (successCount > 0 || failedCount > 0) {
throw new IllegalStateException("Can't set slot list while containing the data.");
}
// histogramSummary.clear();
timeseriesSlotIndex.clear();
timeseriesValueList.clear();
// histogramSummary.put(SLOT_SLOW, 0L);
// histogramSummary.put(SLOT_ERROR, 0L);
for (HistogramSlot slot : slotList) {
// histogramSummary.put(slot.getSlotTime(), 0L);
timeseriesSlotIndex.put(slot.getSlotTime(), timeseriesSlotIndex.size());
timeseriesValueList.add(makeEmptyTimeseriesValueMap());
}
timeseriesSlotIndex.put(SLOT_SLOW, timeseriesSlotIndex.size());
timeseriesSlotIndex.put(SLOT_ERROR, timeseriesSlotIndex.size());
timeseriesValueList.add(makeEmptyTimeseriesValueMap());
timeseriesValueList.add(makeEmptyTimeseriesValueMap());
}
public void addSample(long timestamp, int responseTimeslot, long callCount, boolean isFailed) {
logger.debug("Add sample. timeslot=" + timestamp + ", responseTimeslot=" + responseTimeslot + ", callCount=" + callCount + ", failed=" + isFailed);
timestamp = TimeWindowUtils.refineTimestamp(from, to, timestamp);
if (isFailed) {
failedCount += callCount;
} else {
successCount += callCount;
}
// TODO .
if (responseTimeslot == -1) {
responseTimeslot = SLOT_ERROR;
} else if (responseTimeslot == 0) {
responseTimeslot = SLOT_SLOW;
}
// add summary
// long value = histogramSummary.containsKey(responseTimeslot) ? histogramSummary.get(responseTimeslot) + callCount : callCount;
// histogramSummary.put(responseTimeslot, value);
/**
* <pre>
* timeseriesValueList ..
* list[respoinse_slot_no + 0] = value<timestamp, call count>
* list[respoinse_slot_no + 1] = value<timestamp, call count>
* list[respoinse_slot_no + N] = value<timestamp, call count>
* </pre>
*/
for (int i = 0; i < timeseriesValueList.size(); i++) {
SortedMap<Long, Long> map = timeseriesValueList.get(i);
// slot .
if (i == timeseriesSlotIndex.get(responseTimeslot)) {
long v = map.containsKey(timestamp) ? map.get(timestamp) + callCount : callCount;
map.put(timestamp, v);
} else {
if (!map.containsKey(timestamp)) {
map.put(timestamp, 0L);
}
}
}
}
// public Map<Integer, Long> getHistogramSummary() {
// return histogramSummary;
public long getSuccessCount() {
return successCount;
}
public long getFailedCount() {
return failedCount;
}
public SortedMap<Short, Integer> getTimeseriesSlotIndex() {
return timeseriesSlotIndex;
}
public List<SortedMap<Long, Long>> getTimeseriesValue() {
return timeseriesValueList;
}
public int getSlow() {
return SLOT_SLOW;
}
public int getError() {
return SLOT_ERROR;
}
@Override
public String toString() {
return "LinkStatistics [timeseriesValue=" + timeseriesValueList + ", timeseriesSlotIndex=" + timeseriesSlotIndex + ", from=" + from + ", to=" + to + ", successCount=" + successCount + ", failedCount=" + failedCount + "]";
}
}
|
package uk.org.ownage.dmdirc.ui.dialogs.channelsetting;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Properties;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import uk.org.ownage.dmdirc.Channel;
import uk.org.ownage.dmdirc.Config;
import uk.org.ownage.dmdirc.identities.Identity;
import uk.org.ownage.dmdirc.identities.IdentityManager;
import static uk.org.ownage.dmdirc.ui.UIUtilities.LARGE_BORDER;
import static uk.org.ownage.dmdirc.ui.UIUtilities.SMALL_BORDER;
import static uk.org.ownage.dmdirc.ui.UIUtilities.layoutGrid;
/**
* Channel settings panel.
*/
public final class ChannelSettingsPane extends JPanel implements ActionListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** Parent channel. */
private final Channel channel;
/** Parent container panel. */
private final JPanel parent;
/** Current settings panel. */
private JPanel settingsPanel;
/** Information label. */
private final JLabel infoLabel;
/** No settings warning label. */
private final JLabel noCurrentSettingsLabel;
/** splut user modes checkbox. */
private final JCheckBox splitUserModes;
/** cycle text text field. */
private final JTextField cycleText;
/** kick text text field. */
private final JTextField kickText;
/** part text text field. */
private final JTextField partText;
/** background colour text field. */
private final JTextField backColour;
/** fore ground colour text field. */
private final JTextField foreColour;
/** frame buffer text field. */
private final JTextField frameBuffer;
/** input buffer text field. */
private final JTextField inputBuffer;
/** new setting value text field. */
private final JTextField newSettingField;
/** new setting combo box. */
private final JComboBox newSettingComboBox;
/** add new settinb button. */
private final JButton newSettingButton;
/** channel settings . */
private Properties settings;
/** number of current settings. */
private int numCurrentSettings;
/** number of addable settings. */
private int numAddableSettings;
/** hashmap, config option -> name */
private HashMap<String, String> optionMap;
/** Channel identity file. */
private Identity identity;
/** Valid option types */
private enum OPTION_TYPE { TEXTFIELD, CHECKBOX, }
/** text fields */
private HashMap<String, JTextField> textFields;
/** checkboxes */
private HashMap<String, JCheckBox> checkBoxes;
/**
* Creates a new instance of ChannelSettingsPane.
* @param newParent parent panel
* @param newChannel parent Channel
*/
public ChannelSettingsPane(final JPanel newParent, final Channel newChannel) {
parent = newParent;
channel = newChannel;
identity = IdentityManager.getChannelConfig(channel.getServer().getNetwork(),
channel.getChannelInfo().getName());
infoLabel = new JLabel();
noCurrentSettingsLabel = new JLabel();
splitUserModes = new JCheckBox();
cycleText = new JTextField();
kickText = new JTextField();
partText = new JTextField();
backColour = new JTextField();
foreColour = new JTextField();
frameBuffer = new JTextField();
inputBuffer = new JTextField();
newSettingField = new JTextField();
newSettingComboBox = new JComboBox(new DefaultComboBoxModel());
newSettingButton = new JButton();
textFields = new HashMap<String, JTextField>();
checkBoxes = new HashMap<String, JCheckBox>();
optionMap = new LinkedHashMap<String, String>();
initSettingsPanel();
}
/**
* Initialises the settings panel.
*/
private void initSettingsPanel() {
this.setVisible(false);
this.removeAll();
final GridBagConstraints constraints = new GridBagConstraints();
final JPanel addPanel = new JPanel();
settingsPanel = new JPanel();
JLabel label;
JButton button;
numCurrentSettings = 0;
numAddableSettings = 0;
optionMap.clear();
textFields.clear();
checkBoxes.clear();
settingsPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
new EtchedBorder(), "Current settings"),
new EmptyBorder(LARGE_BORDER, LARGE_BORDER, LARGE_BORDER,
LARGE_BORDER)));
settingsPanel.setLayout(new SpringLayout());
addPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
new EtchedBorder(), "Add new setting"),
new EmptyBorder(LARGE_BORDER, LARGE_BORDER, LARGE_BORDER,
LARGE_BORDER)));
addPanel.setLayout(new SpringLayout());
infoLabel.setText("<html>These settings are specific to this channel on this network,<br>"
+ "any settings specified here will overwrite global settings</html>");
infoLabel.setBorder(new EmptyBorder(0, 0, LARGE_BORDER, 0));
if (identity == null) {
settings = new Properties();
} else {
settings = identity.getProperties();
}
addOption("channel.splitusermodes", "Split user modes", OPTION_TYPE.CHECKBOX);
addOption("general.cyclemessage", "Cycle message", OPTION_TYPE.TEXTFIELD);
addOption("general.kickmessage", "Kick message", OPTION_TYPE.TEXTFIELD);
addOption("general.partmessage", "Part message", OPTION_TYPE.TEXTFIELD);
addOption("ui.backgroundcolour", "Background colour", OPTION_TYPE.TEXTFIELD);
addOption("ui.foregroundcolour", "Foreground colour", OPTION_TYPE.TEXTFIELD);
addOption("ui.frameBufferSize", "Frame buffer size", OPTION_TYPE.TEXTFIELD);
addOption("ui.inputbuffersize", "Input buffer size", OPTION_TYPE.TEXTFIELD);
if (numCurrentSettings == 0) {
noCurrentSettingsLabel.setText("No channel specific settings.");
noCurrentSettingsLabel.setBorder(new EmptyBorder(0, 0, 0, 0));
settingsPanel.add(noCurrentSettingsLabel);
layoutGrid(settingsPanel, 1,
1, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
} else {
layoutGrid(settingsPanel, numCurrentSettings,
3, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER);
}
newSettingComboBox.setPreferredSize(new Dimension(150,
newSettingComboBox.getFont().getSize()));
newSettingField.setText("");
newSettingField.setPreferredSize(new Dimension(150,
newSettingField.getFont().getSize()));
newSettingButton.setText("Add");
newSettingButton.setMargin(new Insets(0, 0, 0, 0));
newSettingButton.setPreferredSize(new Dimension(45, 0));
newSettingButton.addActionListener(this);
addPanel.add(newSettingComboBox);
addPanel.add(newSettingField);
addPanel.add(newSettingButton);
layoutGrid(addPanel, 1, 3, SMALL_BORDER, SMALL_BORDER,
SMALL_BORDER, SMALL_BORDER);
this.setLayout(new GridBagLayout());
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weighty = 0.0;
constraints.weightx = 0.0;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
this.add(infoLabel, constraints);
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.gridy = 1;
this.add(settingsPanel, constraints);
constraints.weighty = 0.0;
constraints.gridy = 2;
this.add(addPanel, constraints);
this.setVisible(true);
parent.add(this, BorderLayout.CENTER);
}
/**
* Adds an option to the panel
* @param configName config option name
* @param type config option type
*/
private void addOption(final String configName, final String displayName,
final OPTION_TYPE type) {
String optionValue;
optionMap.put(displayName, configName);
if ((optionValue = settings.getProperty(configName)) != null) {
addCurrentOption(configName, displayName, settingsPanel, type, optionValue);
} else {
addAddableOption(displayName);
}
}
/**
* Adds an option to the current options pane.
*/
private void addCurrentOption(final String configName, final String displayName,
final JPanel panel,
final OPTION_TYPE type, final String optionValue) {
JComponent component;
numCurrentSettings++;
switch (type) {
case CHECKBOX:
component = new JCheckBox();
((JCheckBox) component).setSelected(Boolean.parseBoolean(optionValue));
checkBoxes.put(configName, (JCheckBox) component);
break;
case TEXTFIELD:
component = new JTextField();
((JTextField) component).setText(optionValue);
break;
default:
throw new IllegalArgumentException("Unrecognised option type");
}
component.setPreferredSize(new Dimension(150,
splitUserModes.getFont().getSize()));
JLabel label = new JLabel();
label.setText(displayName + ": ");
label.setPreferredSize(new Dimension(150,
label.getFont().getSize()));
label.setLabelFor(component);
JButton button = new JButton();
button.setIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource("uk/org/ownage/dmdirc/res/close-inactive.png")));
button.setRolloverIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource("uk/org/ownage/dmdirc/res/close-active.png")));
button.setPressedIcon(new ImageIcon(this.getClass()
.getClassLoader().getResource("uk/org/ownage/dmdirc/res/close-active.png")));
button.setContentAreaFilled(false);
button.setBorder(new EmptyBorder(0, 0, 0, 0));
button.setMargin(new Insets(0, 0, 0, 0));
button.setPreferredSize(new Dimension(16, 0));
button.setActionCommand(configName);
button.addActionListener(this);
panel.add(label);
panel.add(component);
panel.add(button);
}
/**
* Adds an option to the addable options combo box.
*/
public void addAddableOption(final String displayName) {
numAddableSettings++;
((DefaultComboBoxModel) newSettingComboBox.getModel()).addElement(displayName);
}
/**
* Adds an addable option to the current options.
* @param name option name
* @param value option value
*/
private void addNewCurrentOption(final String name, final String value) {
if (identity != null && value != null) {
String[] optionValues = optionMap.get(name).split("\\.");
identity.setOption(optionValues[0], optionValues[1], value);
initSettingsPanel();
}
}
/** {@inheritDoc}. */
public void actionPerformed(final ActionEvent event) {
String option;
if (event.getSource() == newSettingButton) {
addNewCurrentOption((String) newSettingComboBox.getSelectedItem(),
newSettingField.getText());
} else {
String[] optionValues = event.getActionCommand().split("\\.");
identity.removeOption(optionValues[0], optionValues[1]);
initSettingsPanel();
}
}
/** Saves teh current options */
public void saveSettings() {
Config.save();
}
}
|
package com.novoda.notils.logger.toast;
import android.content.Context;
/**
* A Toast helper giving a short hand to show toasts.
* Also checks for the validity of your context and Log's if it cannot toast.
*
* @deprecated StackingToastDisplayer subsumes the functionality of this Toaster
*/
@Deprecated
public class Toaster implements ToastDisplayer {
private final StackingToastDisplayer toastDisplayer;
/**
* A helper in Toasting messages to the screen
*
* @param context
* @deprecated use Toaster.newInstance(Context) instead
*/
@Deprecated
public Toaster(Context context) {
this(StackingToastDisplayer.newInstance(context));
}
private Toaster(StackingToastDisplayer toastDisplayer) {
this.toastDisplayer = toastDisplayer;
}
public static Toaster newInstance(Context context) {
return new Toaster(StackingToastDisplayer.newInstance(context));
}
/**
* Toast.LENGTH_SHORT
*
* @param resId
* @deprecated use display(int) instead
*/
@Deprecated
public void popToast(int resId) {
display(resId);
}
/**
* Toast.LENGTH_SHORT
*
* @param message
* @deprecated use display(String)
*/
@Deprecated
public void popToast(String message) {
display(message);
}
/**
* Toast.LENGTH_LONG
*
* @param resId
* @deprecated use displayLong(int) instead
*/
@Deprecated
public void popBurntToast(int resId) {
displayLong(resId);
}
/**
* Toast.LENGTH_LONG
*
* @param message
* @deprecated use displayLong(String) instead
*/
@Deprecated
public void popBurntToast(String message) {
displayLong(message);
}
@Override
public void display(String message) {
toastDisplayer.display(message);
}
@Override
public void display(int resId) {
toastDisplayer.display(resId);
}
@Override
public void displayLong(String message) {
toastDisplayer.displayLong(message);
}
@Override
public void displayLong(int resId) {
toastDisplayer.displayLong(resId);
}
@Override
public void cancelAll() {
toastDisplayer.cancelAll();
}
}
|
package com.pyx4me.maven.proguard;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.codehaus.plexus.archiver.jar.JarArchiver;
/**
*
* <p>
* The Obfuscate task provides a stand-alone obfuscation task
* </p>
*
* @goal proguard
* @phase package
* @description Create small jar files using ProGuard
* @requiresDependencyResolution compile
*/
public class ProGuardMojo extends AbstractMojo {
/**
* Recursively reads configuration options from the given file filename
*
* @parameter default-value="${basedir}/proguard.conf"
*/
private File proguardInclude;
/**
* ProGuard configuration options
*
* @parameter
*/
private String[] options;
/**
* Specifies not to obfuscate the input class files.
*
* @parameter default-value="true"
*/
private boolean obfuscate;
/**
* Specifies that project compile dependencies be added as -libraryjars to
* proguard arguments. Dependency itself is not included in resulting jar
*
* @parameter default-value="true"
*/
private boolean includeDependency;
/**
* Bundle project dependency to resulting jar. Specifies list of artifact
* inclusions
*
* @parameter
*/
private Assembly assembly;
/**
* Additional -libraryjars e.g. ${java.home}/lib/rt.jar Project compile
* dependency are added automaticaly. See exclusions
*
* @parameter
*/
private List libs;
/**
* List of dependency exclusions
*
* @parameter
*/
private List exclusions;
/**
* Specifies the input jar name (or wars, ears, zips) of the application to
* be processed.
*
* @parameter expression="${project.build.finalName}.jar"
* @required
*/
protected String injar;
/**
* Apply ProGuard classpathentry Filters to input jar. e.g.
* <code>!**.gif,!**/tests/**'</code>
*
* @parameter
*/
protected String inFilter;
/**
* Specifies the names of the output jars. If attach=true the value ignored
* and name constructed base on classifier If empty input jar would be
* overdriven.
*
* @parameter
*/
protected String outjar;
/**
* Specifies whether or not to attach the created artifact to the project
*
* @parameter default-value="false"
*/
private boolean attach = false;
/**
* Specifies attach artifact type
*
* @parameter default-value="jar"
*/
private String attachArtifactType;
/**
* Specifies attach artifact Classifier, Ignored if attach=false
*
* @parameter default-value="small"
*/
private String attachArtifactClassifier;
/**
* Set to false to exclude the attachArtifactClassifier from the Artifact
* final name. Default value is true.
*
* @parameter default-value="true"
*/
private boolean appendClassifier;
* Set to true to include META-INF/maven/** maven descriptord
*
* @parameter default-value="false"
*/
private boolean addMavenDescriptor;
/**
* Directory containing the input and generated JAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
protected File outputDirectory;
/**
* The Maven project reference where the plugin is currently being executed.
* The default value is populated from maven.
*
* @parameter expression="${project}"
* @readonly
* @required
*/
protected MavenProject mavenProject;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List pluginArtifacts;
/**
* @component
*/
private MavenProjectHelper projectHelper;
/**
* The Jar archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#jar}"
* @required
*/
private JarArchiver jarArchiver;
/**
* The maven archive configuration to use. only if assembly is used.
*
* @parameter
*/
protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
/**
* The max memory the forked java process should use, e.g. 256m
*
* @parameter
*/
protected String maxMemory;
private Log log;
static final String proguardMainClass = "proguard.ProGuard";
/**
* ProGuard docs: Names with special characters like spaces and parentheses
* must be quoted with single or double quotes.
*/
private static String fileNameToString(String fileName) {
return "'" + fileName + "'";
}
private static String fileToString(File file) {
return fileNameToString(file.toString());
}
private boolean useArtifactClassifier() {
return appendClassifier && ((attachArtifactClassifier != null) && (attachArtifactClassifier.length() > 0));
}
public void execute() throws MojoExecutionException, MojoFailureException {
log = getLog();
boolean mainIsJar = mavenProject.getPackaging().equals("jar");
boolean mainIsPom = mavenProject.getPackaging().equals("pom");
File inJarFile = new File(outputDirectory, injar);
if (mainIsJar && (!inJarFile.exists())) {
throw new MojoFailureException("Can't find file " + inJarFile);
}
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
throw new MojoFailureException("Can't create " + outputDirectory);
}
}
File outJarFile;
boolean sameArtifact;
if (attach) {
outjar = nameNoType(injar);
if (useArtifactClassifier()) {
outjar += "-" + attachArtifactClassifier;
}
outjar += "." + attachArtifactType;
}
if ((outjar != null) && (!outjar.equals(injar))) {
sameArtifact = false;
outJarFile = (new File(outputDirectory, outjar)).getAbsoluteFile();
} else {
sameArtifact = true;
outJarFile = inJarFile.getAbsoluteFile();
File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_base.jar");
if (baseFile.exists()) {
if (!baseFile.delete()) {
throw new MojoFailureException("Can't delete " + baseFile);
}
}
if (inJarFile.exists()) {
if (!inJarFile.renameTo(baseFile)) {
throw new MojoFailureException("Can't rename " + inJarFile);
}
}
inJarFile = baseFile;
}
ArrayList args = new ArrayList();
if (log.isDebugEnabled()) {
List dependancy = mavenProject.getCompileArtifacts();
for (Iterator i = dependancy.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- compile artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getArtifacts().iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getDependencies().iterator(); i.hasNext();) {
Dependency artifact = (Dependency) i.next();
log.debug("--- dependency " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
}
Set inPath = new HashSet();
boolean hasInclusionLibrary = false;
if (assembly != null) {
for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
Inclusion inc = (Inclusion) iter.next();
if (!inc.library) {
File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
inPath.add(file.toString());
log.debug("--- ADD injars:" + inc.artifactId);
StringBuffer filter = new StringBuffer(fileToString(file));
filter.append("(!META-INF/MANIFEST.MF");
if (!addMavenDescriptor) {
filter.append(",");
|
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.compiler.js.util.JsIdentifierNames;
import com.redhat.ceylon.compiler.js.util.JsJULLogger;
import com.redhat.ceylon.compiler.js.util.JsOutput;
import com.redhat.ceylon.compiler.js.util.Options;
import com.redhat.ceylon.compiler.loader.MetamodelVisitor;
import com.redhat.ceylon.compiler.loader.ModelEncoder;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.model.typechecker.model.Module;
/** A simple program that takes the main JS module file and replaces #include markers with the contents of other files.
*
* @author Enrique Zamudio
*/
public class Stitcher {
private static TypeCheckerBuilder langmodtc;
private static Path tmpDir;
public static final File clSrcDir = new File("../ceylon.language/src/ceylon/language/");
public static final File LANGMOD_JS_SRC = new File("../ceylon.language/runtime-js");
public static final File LANGMOD_JS_SRC2 = new File("../ceylon.language/runtime-js/ceylon/language");
private static JsIdentifierNames names;
private static Module mod;
private static int compileLanguageModule(final String line, final Writer writer)
throws IOException {
File clsrcTmpDir = Files.createTempDirectory(tmpDir, "clsrc").toFile();
final File tmpout = new File(clsrcTmpDir, Constants.DEFAULT_MODULE_DIR);
tmpout.mkdir();
final Options opts = new Options().addRepo("build/runtime").comment(false).optimize(true)
.outRepo(tmpout.getAbsolutePath()).modulify(false).minify(true);
//Typecheck the whole language module
if (langmodtc == null) {
langmodtc = new TypeCheckerBuilder().addSrcDirectory(clSrcDir.getParentFile().getParentFile())
.addSrcDirectory(LANGMOD_JS_SRC)
.encoding("UTF-8");
langmodtc.setRepositoryManager(CeylonUtils.repoManager().systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos()).outRepo(opts.getOutRepo()).buildManager());
}
final File mod2 = new File(LANGMOD_JS_SRC2, "module.ceylon");
if (!mod2.exists()) {
try (FileWriter w2 = new FileWriter(mod2);
FileReader r2 = new FileReader(new File(clSrcDir, "module.ceylon"))) {
char[] c = new char[512];
int r = r2.read(c);
while (r != -1) {
w2.write(c, 0, r);
r = r2.read(c);
}
mod2.deleteOnExit();
} finally {
}
}
final TypeChecker tc = langmodtc.getTypeChecker();
tc.process();
if (tc.getErrors() > 0) {
return 1;
}
//Compile these files
final List<File> includes = new ArrayList<File>();
for (String filename : line.split(",")) {
filename = filename.trim();
final boolean isJsSrc = filename.endsWith(".js");
final boolean isDir = filename.endsWith("/");
final File src = new File(isJsSrc ? LANGMOD_JS_SRC : clSrcDir,
isJsSrc || isDir ? filename :
String.format("%s.ceylon", filename));
if (src.exists() && src.isFile() && src.canRead()) {
includes.add(src);
} else if (src.exists() && src.isDirectory()) {
includes.addAll(Arrays.asList(src.listFiles()));
} else {
final File src2 = new File(LANGMOD_JS_SRC2, isDir ? filename : String.format("%s.ceylon", filename));
if (src2.exists() && src2.isFile() && src2.canRead()) {
includes.add(src2);
} else if (src2.exists() && src2.isDirectory()) {
includes.addAll(Arrays.asList(src2.listFiles()));
} else {
throw new IllegalArgumentException("Invalid Ceylon language module source " + src + " or " + src2);
}
}
}
//Compile only the files specified in the line
//Set this before typechecking to share some decls that otherwise would be private
JsCompiler.compilingLanguageModule=true;
JsCompiler jsc = new JsCompiler(tc, opts).stopOnErrors(false);
jsc.setSourceFiles(includes);
jsc.generate();
if (names == null) {
names = jsc.getNames();
mod = tc.getPhasedUnits().getPhasedUnits().get(0).getPackage().getModule();
}
JsCompiler.compilingLanguageModule=false;
File compsrc = new File(tmpout, "delete/me/delete-me.js");
if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) {
try (BufferedReader jsr = new BufferedReader(new FileReader(compsrc))) {
String jsline = null;
while ((jsline = jsr.readLine()) != null) {
if (!jsline.contains("=require('")) {
writer.write(jsline);
writer.write("\n");
}
}
} finally {
compsrc.delete();
}
} else {
System.out.println("Can't find generated js for language module in " + compsrc.getAbsolutePath());
return 1;
}
return 0;
}
private static int encodeModel(final File moduleFile) throws IOException {
final String name = moduleFile.getName();
final File file = new File(moduleFile.getParentFile(),
name.substring(0,name.length()-3)+ArtifactContext.JS_MODEL);
System.out.println("Generating language module compile-time model in JSON...");
TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false);
tcb.addSrcDirectory(clSrcDir.getParentFile().getParentFile());
TypeChecker tc = tcb.getTypeChecker();
tc.process();
MetamodelVisitor mmg = null;
for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
if (!pu.getCompilationUnit().getErrors().isEmpty()) {
System.out.println("whoa, errors in the language module "
+ pu.getCompilationUnit().getLocation());
for (Message err : pu.getCompilationUnit().getErrors()) {
System.out.println(err.getMessage());
}
}
if (mmg == null) {
mmg = new MetamodelVisitor(pu.getPackage().getModule());
}
pu.getCompilationUnit().visit(mmg);
}
try (FileWriter writer = new FileWriter(file)) {
JsCompiler.beginWrapper(writer);
writer.write("ex$.$CCMM$=");
ModelEncoder.encodeModel(mmg.getModel(), writer);
writer.write(";\n");
int exitCode = compileLanguageModule("MODEL.js", writer);
if (exitCode != 0) {
return exitCode;
}
JsCompiler.endWrapper(writer);
} finally {
ShaSigner.sign(file, new JsJULLogger(), true);
}
return 0;
}
private static int stitch(File infile, final Writer writer, String version) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8"));
try {
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0) {
if (line.equals("//#METAMODEL")) {
writer.write("var _CTM$;function $CCMM$(){if (_CTM$===undefined)_CTM$=require('");
writer.write("ceylon/language/");
writer.write(version);
writer.write("/ceylon.language-");
writer.write(version);
writer.write("-model");
writer.write("').$CCMM$;return _CTM$;}\n");
writer.write("ex$.$CCMM$=$CCMM$;");
} else if (line.startsWith("//#COMPILE ")) {
final String sourceFiles = line.substring(11);
System.out.println("Compiling language module sources: " + sourceFiles);
int exitCode = compileLanguageModule(sourceFiles, writer);
if (exitCode != 0) {
return exitCode;
}
} else if (line.startsWith("//#UNSHARED")) {
new JsOutput(mod, "UTF-8") {
@Override
public Writer getWriter() throws IOException {
return writer;
}
}.publishUnsharedDeclarations(names);
} else if (!line.endsWith("//IGNORE")) {
writer.write(line);
writer.write("\n");
}
}
}
} finally {
if (reader != null) reader.close();
}
return 0;
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("This program requires 3 arguments to run:");
System.err.println("1. The path to the main JS file");
System.err.println("2. The path of the resulting JS file");
System.exit(1);
return;
}
int exitCode = 0;
tmpDir = Files.createTempDirectory("ceylon-jsstitcher-");
try {
File infile = new File(args[0]);
if (infile.exists() && infile.isFile() && infile.canRead()) {
File outfile = new File(args[1]);
if (!outfile.getParentFile().exists()) {
outfile.getParentFile().mkdirs();
}
exitCode = encodeModel(outfile);
if (exitCode == 0) {
final int p0 = args[1].indexOf(".language-");
final String version = args[1].substring(p0+10,args[1].length()-3);
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8")) {
exitCode = stitch(infile, writer, version);
} finally {
ShaSigner.sign(outfile, new JsJULLogger(), true);
}
}
} else {
System.err.println("Input file is invalid: " + infile);
exitCode = 2;
}
} finally {
FileUtil.deleteQuietly(tmpDir.toFile());
}
if (exitCode != 0) {
System.exit(exitCode);
}
}
}
|
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.compiler.js.util.JsIdentifierNames;
import com.redhat.ceylon.compiler.js.util.JsJULLogger;
import com.redhat.ceylon.compiler.js.util.JsOutput;
import com.redhat.ceylon.compiler.js.util.Options;
import com.redhat.ceylon.compiler.loader.MetamodelVisitor;
import com.redhat.ceylon.compiler.loader.ModelEncoder;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.model.typechecker.model.Module;
/** A simple program that takes the main JS module file and replaces #include markers with the contents of other files.
*
* @author Enrique Zamudio
*/
public class Stitcher {
private static TypeCheckerBuilder langmodtc;
private static Path tmpDir;
public static final File clSrcDir = new File("../ceylon.language/src/ceylon/language/");
public static final File LANGMOD_JS_SRC = new File("../ceylon.language/runtime-js");
public static final File LANGMOD_JS_SRC2 = new File("../ceylon.language/runtime-js/ceylon/language");
private static JsIdentifierNames names;
private static Module mod;
private static int compileLanguageModule(final String line, final Writer writer)
throws IOException {
File clsrcTmpDir = Files.createTempDirectory(tmpDir, "clsrc").toFile();
final File tmpout = new File(clsrcTmpDir, Constants.DEFAULT_MODULE_DIR);
tmpout.mkdir();
final Options opts = new Options().addRepo("build/runtime").comment(false).optimize(true)
.outRepo(tmpout.getAbsolutePath()).modulify(false).minify(true);
//Typecheck the whole language module
if (langmodtc == null) {
langmodtc = new TypeCheckerBuilder().addSrcDirectory(clSrcDir.getParentFile().getParentFile())
.addSrcDirectory(LANGMOD_JS_SRC)
.encoding("UTF-8");
langmodtc.setRepositoryManager(CeylonUtils.repoManager().systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos()).outRepo(opts.getOutRepo()).buildManager());
}
final File mod2 = new File(LANGMOD_JS_SRC2, "module.ceylon");
if (!mod2.exists()) {
try (FileWriter w2 = new FileWriter(mod2);
FileReader r2 = new FileReader(new File(clSrcDir, "module.ceylon"))) {
char[] c = new char[512];
int r = r2.read(c);
while (r != -1) {
w2.write(c, 0, r);
r = r2.read(c);
}
mod2.deleteOnExit();
} finally {
}
}
final TypeChecker tc = langmodtc.getTypeChecker();
tc.process();
if (tc.getErrors() > 0) {
return 1;
}
//Compile these files
final List<File> includes = new ArrayList<File>();
for (String filename : line.split(",")) {
filename = filename.trim();
final boolean isJsSrc = filename.endsWith(".js");
final boolean isDir = filename.endsWith("/");
final File src = new File(isJsSrc ? LANGMOD_JS_SRC : clSrcDir,
isJsSrc || isDir ? filename :
String.format("%s.ceylon", filename));
if (src.exists() && src.isFile() && src.canRead()) {
includes.add(src);
} else if (src.exists() && src.isDirectory()) {
includes.addAll(Arrays.asList(src.listFiles()));
} else {
final File src2 = new File(LANGMOD_JS_SRC2, isDir ? filename : String.format("%s.ceylon", filename));
if (src2.exists() && src2.isFile() && src2.canRead()) {
includes.add(src2);
} else if (src2.exists() && src2.isDirectory()) {
includes.addAll(Arrays.asList(src2.listFiles()));
} else {
throw new IllegalArgumentException("Invalid Ceylon language module source " + src + " or " + src2);
}
}
}
//Compile only the files specified in the line
//Set this before typechecking to share some decls that otherwise would be private
JsCompiler.compilingLanguageModule=true;
JsCompiler jsc = new JsCompiler(tc, opts).stopOnErrors(false);
jsc.setSourceFiles(includes);
jsc.generate();
if (names == null) {
names = jsc.getNames();
mod = tc.getPhasedUnits().getPhasedUnits().get(0).getPackage().getModule();
}
JsCompiler.compilingLanguageModule=false;
File compsrc = new File(tmpout, "delete/me/delete-me.js");
if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) {
try (BufferedReader jsr = new BufferedReader(new FileReader(compsrc))) {
String jsline = null;
while ((jsline = jsr.readLine()) != null) {
if (!jsline.contains("=require('")) {
writer.write(jsline);
writer.write("\n");
}
}
} finally {
compsrc.delete();
}
} else {
System.out.println("Can't find generated js for language module in " + compsrc.getAbsolutePath());
return 1;
}
return 0;
}
private static int encodeModel(final File moduleFile) throws IOException {
final String name = moduleFile.getName();
final File file = new File(moduleFile.getParentFile(),
name.substring(0,name.length()-3)+ArtifactContext.JS_MODEL);
System.out.println("Generating language module compile-time model in JSON...");
TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false);
tcb.addSrcDirectory(clSrcDir.getParentFile().getParentFile());
TypeChecker tc = tcb.getTypeChecker();
tc.process();
MetamodelVisitor mmg = null;
for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
if (!pu.getCompilationUnit().getErrors().isEmpty()) {
System.out.println("whoa, errors in the language module "
+ pu.getCompilationUnit().getLocation());
for (Message err : pu.getCompilationUnit().getErrors()) {
System.out.println(err.getMessage());
}
}
if (mmg == null) {
mmg = new MetamodelVisitor(pu.getPackage().getModule());
}
pu.getCompilationUnit().visit(mmg);
}
try (FileWriter writer = new FileWriter(file)) {
JsCompiler.beginWrapper(writer);
writer.write("ex$.$CCMM$=");
ModelEncoder.encodeModel(mmg.getModel(), writer);
writer.write(";\n");
int exitCode = compileLanguageModule("MODEL.js", writer);
if (exitCode != 0) {
return exitCode;
}
JsCompiler.endWrapper(writer);
} finally {
ShaSigner.sign(file, new JsJULLogger(), true);
}
return 0;
}
private static int stitch(File infile, final Writer writer) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8"));
try {
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0) {
if (line.startsWith("COMPILE ")) {
final String sourceFiles = line.substring(8);
System.out.println("Compiling language module sources: " + sourceFiles);
int exitCode = compileLanguageModule(sourceFiles, writer);
if (exitCode != 0) {
return exitCode;
}
}
}
}
} finally {
if (reader != null) reader.close();
}
return 0;
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("This program requires 2 arguments to run:");
System.err.println("1. The path to the master file (the one with the list of files to compile)");
System.err.println("2. The path of the resulting JS file");
System.exit(1);
return;
}
int exitCode = 0;
tmpDir = Files.createTempDirectory("ceylon-jsstitcher-");
try {
File infile = new File(args[0]);
if (infile.exists() && infile.isFile() && infile.canRead()) {
File outfile = new File(args[1]);
if (!outfile.getParentFile().exists()) {
outfile.getParentFile().mkdirs();
}
exitCode = encodeModel(outfile);
if (exitCode == 0) {
final int p0 = args[1].indexOf(".language-");
final String version = args[1].substring(p0+10,args[1].length()-3);
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8")) {
final JsOutput jsout = new JsOutput(mod, "UTF-8") {
@Override
public Writer getWriter() throws IOException {
return writer;
}
};
//CommonJS wrapper
JsCompiler.beginWrapper(writer);
//Model
jsout.out("var _CTM$;function $CCMM$(){if (_CTM$===undefined)_CTM$=require('",
"ceylon/language/", version, "/ceylon.language-", version, "-model",
"').$CCMM$;return _CTM$;}\nex$.$CCMM$=$CCMM$;");
//Compile all the listed files
exitCode = stitch(infile, writer);
//Unshared declarations
jsout.publishUnsharedDeclarations(names);
//Close the commonJS wrapper
JsCompiler.endWrapper(writer);
} finally {
ShaSigner.sign(outfile, new JsJULLogger(), true);
}
}
} else {
System.err.println("Input file is invalid: " + infile);
exitCode = 2;
}
} finally {
FileUtil.deleteQuietly(tmpDir.toFile());
}
if (exitCode != 0) {
System.exit(exitCode);
}
}
}
|
package com.sri.ai.praise.sgsolver.demo;
import com.google.common.annotations.Beta;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import de.jensd.fx.glyphs.GlyphIcons;
import de.jensd.fx.glyphs.GlyphsBuilder;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.GlyphsStack;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcons;
@Beta
public class FXUtil {
public static final String _iconSmallSize = "17px";
public static final String _iconMediumSize = "18px";
public static final String _buttonDefaultIconSize = "24px";
public static final String _buttonPaginationIconSize = "20px";
public static void anchor(Node node) {
AnchorPane.setTopAnchor(node, 0.0);
AnchorPane.setLeftAnchor(node, 0.0);
AnchorPane.setRightAnchor(node, 0.0);
AnchorPane.setBottomAnchor(node, 0.0);
}
public static void setDefaultButtonIcon(Button button, GlyphIcons icon) {
GlyphsDude.setIcon(button, icon, _buttonDefaultIconSize, ContentDisplay.GRAPHIC_ONLY);
}
public static void setPaginationButtonIcon(Button button, GlyphIcons icon) {
GlyphsDude.setIcon(button, icon, _buttonPaginationIconSize, ContentDisplay.GRAPHIC_ONLY);
}
public static void setMediumButtonIcon(Button button, GlyphIcons icon) {
GlyphsDude.setIcon(button, icon, _buttonDefaultIconSize, ContentDisplay.GRAPHIC_ONLY);
}
public static void setButtonStackedIcons(Button button, GlyphIcons icon1, GlyphIcons icon2) {
Region saveAsImg = GlyphsStack.create()
.add(GlyphsBuilder.create(FontAwesomeIcon.class).glyph(icon1).size(_buttonDefaultIconSize).build())
.add(GlyphsBuilder.create(FontAwesomeIcon.class).glyph(icon2).size(_iconSmallSize).build());
button.setGraphic(saveAsImg);
button.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
public static Node configMenuIcon() {
HBox node = new HBox();
node.getChildren().add(GlyphsBuilder.create(FontAwesomeIcon.class).glyph(FontAwesomeIcons.COG).size("12px").build());
node.getChildren().add(GlyphsBuilder.create(FontAwesomeIcon.class).glyph(FontAwesomeIcons.CARET_DOWN).size("10px").build());
return node;
}
}
|
package com.toutiao.controller;
import com.toutiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/* Spring MVC Controller */
@Controller
@RequestMapping(value = "/user")
public class LoginController{
@Autowired
private UserService userService;
@RequestMapping(value = "/main")
public String loginPage(){
return "login";
}
@RequestMapping(value = "/login")
public ModelAndView loginCheck(HttpServletRequest request, HttpServletResponse response){
return new ModelAndView();
}
}
|
package jenkins.formelementpath;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.PageDecorator;
import jenkins.util.SystemProperties;
@Extension
public class FormElementPathPageDecorator extends PageDecorator {
@SuppressFBWarnings("MS_SHOULD_BE_FINAL")
private static /*almost final */ boolean ENABLED =
SystemProperties.getBoolean(FormElementPathPageDecorator.class.getName() + ".enabled");
public boolean isEnabled() {
return ENABLED;
}
}
|
package com.ukefu.webim.service.task;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.client.NettyClients;
import com.ukefu.webim.service.acd.ServiceQuene;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.AgentUserTaskRepository;
import com.ukefu.webim.service.repository.ChatMessageRepository;
import com.ukefu.webim.service.repository.OnlineUserRepository;
import com.ukefu.webim.util.OnlineUserUtils;
import com.ukefu.webim.util.router.OutMessageRouter;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.model.AgentStatus;
import com.ukefu.webim.web.model.AgentUser;
import com.ukefu.webim.web.model.AgentUserTask;
import com.ukefu.webim.web.model.MessageOutContent;
import com.ukefu.webim.web.model.OnlineUser;
import com.ukefu.webim.web.model.SessionConfig;
@Configuration
@EnableScheduling
public class WebIMTask {
@Autowired
private AgentUserTaskRepository agentUserTaskRes ;
@Autowired
private OnlineUserRepository onlineUserRes ;
@Scheduled(fixedDelay= 5000)
public void task() {
SessionConfig sessionConfig = ServiceQuene.initSessionConfig(UKDataContext.SYSTEM_ORGI) ;
if(sessionConfig!=null && UKDataContext.getContext() != null){
if(sessionConfig.isSessiontimeout()){
List<AgentUserTask> agentUserTask = agentUserTaskRes.findByLastmessageLessThanAndStatusAndOrgi(UKTools.getLastTime(sessionConfig.getTimeout()) , UKDataContext.AgentUserStatusEnum.INSERVICE.toString() , sessionConfig.getOrgi()) ;
for(AgentUserTask task : agentUserTask){
AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean().getCacheObject(task.getUserid(), UKDataContext.SYSTEM_ORGI);
if(agentUser!=null && agentUser.getAgentno()!=null){
AgentStatus agentStatus = (AgentStatus) CacheHelper.getAgentStatusCacheBean().getCacheObject(agentUser.getAgentno(), task.getOrgi()) ;
if(agentStatus!=null && (task.getWarnings()==null || task.getWarnings().equals("0"))){
task.setWarnings("1");
task.setWarningtime(new Date());
processMessage(sessionConfig, sessionConfig.getTimeoutmsg() ,agentUser , agentStatus , task);
agentUserTaskRes.save(task) ;
}else if(sessionConfig.isResessiontimeout() && agentStatus!=null && task.getWarningtime()!=null && UKTools.getLastTime(sessionConfig.getRetimeout()).after(task.getWarningtime())){
processMessage(sessionConfig, sessionConfig.getRetimeoutmsg() , agentUser , agentStatus , task);
try {
ServiceQuene.serviceFinish(agentUser, task.getOrgi());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}else if(sessionConfig.isResessiontimeout()){
List<AgentUserTask> agentUserTask = agentUserTaskRes.findByLastmessageLessThanAndStatusAndOrgi(UKTools.getLastTime(sessionConfig.getRetimeout()) , UKDataContext.AgentUserStatusEnum.INSERVICE.toString() , sessionConfig.getOrgi()) ;
for(AgentUserTask task : agentUserTask){
AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean().getCacheObject(task.getUserid(), UKDataContext.SYSTEM_ORGI);
if(agentUser!=null){
AgentStatus agentStatus = (AgentStatus) CacheHelper.getAgentStatusCacheBean().getCacheObject(agentUser.getAgentno(), task.getOrgi()) ;
if(agentStatus!=null && task.getWarningtime()!=null && UKTools.getLastTime(sessionConfig.getRetimeout()).after(task.getWarningtime())){
processMessage(sessionConfig, sessionConfig.getRetimeoutmsg() , agentUser , agentStatus , task);
try {
ServiceQuene.serviceFinish(agentUser, task.getOrgi());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
@Scheduled(fixedDelay= 5000)
public void agent() {
SessionConfig sessionConfig = ServiceQuene.initSessionConfig(UKDataContext.SYSTEM_ORGI) ;
if(sessionConfig!=null && UKDataContext.getContext() != null && sessionConfig.isAgentreplaytimeout()){
List<AgentUserTask> agentUserTask = agentUserTaskRes.findByLastgetmessageLessThanAndStatusAndOrgi(UKTools.getLastTime(sessionConfig.getAgenttimeout()) , UKDataContext.AgentUserStatusEnum.INSERVICE.toString() , sessionConfig.getOrgi()) ;
for(AgentUserTask task : agentUserTask){
AgentUser agentUser = (AgentUser) CacheHelper.getAgentUserCacheBean().getCacheObject(task.getUserid(), UKDataContext.SYSTEM_ORGI);
if(agentUser!=null){
AgentStatus agentStatus = (AgentStatus) CacheHelper.getAgentStatusCacheBean().getCacheObject(agentUser.getAgentno(), task.getOrgi()) ;
if(agentStatus!=null && task.getReptimes()!=null && task.getReptimes().equals("0")){
task.setReptimes("1");
task.setReptime(new Date());
processMessage(sessionConfig, sessionConfig.getAgenttimeoutmsg() ,agentUser , agentStatus , task);
agentUserTaskRes.save(task) ;
}
}
}
}
}
@Scheduled(fixedDelay= 60000)
public void onlineuser() {
Page<OnlineUser> pages = onlineUserRes.findByOrgiAndStatusAndCreatetimeLessThan(UKDataContext.SYSTEM_ORGI, UKDataContext.OnlineUserOperatorStatus.ONLINE.toString(), UKTools.getLastTime(300), new PageRequest(0, 100)) ;
if(pages.getContent().size()>0){
for(OnlineUser onlineUser : pages.getContent()){
try {
OnlineUserUtils.offline(onlineUser.getUserid(), onlineUser.getOrgi());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* appid : appid ,
userid:userid,
sign:session,
touser:touser,
session: session ,
orgi:orgi,
username:agentstatus,
nickname:agentstatus,
message : message
* @param sessionConfig
* @param agentUser
* @param task
*/
private void processMessage(SessionConfig sessionConfig , String message, AgentUser agentUser , AgentStatus agentStatus , AgentUserTask task){
MessageOutContent outMessage = new MessageOutContent() ;
if(!StringUtils.isBlank(message)){
outMessage.setMessage(message);
outMessage.setMessageType(UKDataContext.MediaTypeEnum.TEXT.toString());
outMessage.setCalltype(UKDataContext.CallTypeEnum.OUT.toString());
outMessage.setAgentUser(agentUser);
outMessage.setSnsAccount(null);
ChatMessage data = new ChatMessage();
if(agentUser!=null && agentStatus!=null){
data.setAppid(agentUser.getAppid());
data.setUserid(agentStatus.getAgentno());
data.setUsession(agentUser.getUserid());
data.setTouser(agentUser.getUserid());
data.setOrgi(agentUser.getOrgi());
data.setUsername(agentStatus.getUsername());
data.setMessage(message);
data.setId(UKTools.getUUID());
data.setContextid(agentUser.getContextid());
data.setAgentserviceid(agentUser.getAgentserviceid());
data.setCalltype(UKDataContext.CallTypeEnum.OUT.toString());
if(!StringUtils.isBlank(agentUser.getAgentno())){
data.setTouser(agentUser.getUserid());
}
data.setChannel(agentUser.getChannel());
data.setUsession(agentUser.getUserid());
outMessage.setContextid(agentUser.getContextid());
outMessage.setFromUser(data.getUserid());
outMessage.setToUser(data.getTouser());
outMessage.setChannelMessage(data);
if(agentStatus!=null){
data.setUsername(agentStatus.getUsername());
outMessage.setNickName(agentStatus.getUsername());
}
outMessage.setCreatetime(data.getCreatetime());
UKDataContext.getContext().getBean(ChatMessageRepository.class).save(data) ;
if(agentUser!=null && !StringUtils.isBlank(agentUser.getAgentno())){
NettyClients.getInstance().sendAgentEventMessage(agentUser.getAgentno(), UKDataContext.MessageTypeEnum.MESSAGE.toString(), data);
}
if(!StringUtils.isBlank(data.getTouser())){
if(!StringUtils.isBlank(data.getTouser())){
OutMessageRouter router = null ;
router = (OutMessageRouter) UKDataContext.getContext().getBean(agentUser.getChannel()) ;
if(router!=null){
router.handler(data.getTouser(), UKDataContext.MessageTypeEnum.MESSAGE.toString(), agentUser.getAppid(), outMessage);
}
}
}
}
}
}
}
|
package etomica.nbr.cell;
import etomica.atom.IAtom;
import etomica.atom.IAtomList;
import etomica.box.Box;
import etomica.integrator.IntegratorEvent;
import etomica.integrator.IntegratorListener;
import etomica.potential.BondingInfo;
import etomica.potential.compute.NeighborIterator;
import etomica.potential.compute.NeighborManager;
import etomica.simulation.Simulation;
import etomica.space.Vector;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class NeighborCellManagerFasterer implements NeighborManager {
protected final Box box;
private final boolean isPureAtoms;
private final BondingInfo bondingInfo;
protected int cellRange;
protected Vector[] boxOffsets;
protected final Vector boxHalf;
protected final int[] numCells, jump;
protected double range;
protected int[] wrapMap, cellLastAtom;
protected int[] cellOffsets;
protected int numCellOffsets;
protected Vector[] rawBoxOffsets = new Vector[0];
protected int[] cellNextAtom;
protected int[] atomCell;
public int[] allCellOffsets;
public NeighborCellManagerFasterer(Simulation sim, Box box, int cellRange, BondingInfo bondingInfo) {
this.box = box;
this.cellRange = cellRange;
boxHalf = box.getSpace().makeVector();
numCells = new int[3];
jump = new int[3];
cellNextAtom = atomCell = cellOffsets = wrapMap = cellLastAtom = new int[0];
this.isPureAtoms = sim.getSpeciesList().stream().allMatch(s -> s.getLeafAtomCount() == 1);
this.bondingInfo = bondingInfo;
}
public int cellForCoord(Vector r) {
int cellNum = 0;
Vector bs = box.getBoundary().getBoxSize();
boolean[] periodic = box.getBoundary().getPeriodicity();
for (int i = 0; i < periodic.length; i++) {
double x = (r.getX(i) + boxHalf.getX(i)) / bs.getX(i);
if (periodic[i]) cellNum += ((int) (cellRange + x * (numCells[i] - 2 * cellRange))) * jump[i];
else cellNum += ((int) (x * numCells[i])) * jump[i];
}
return cellNum;
}
public void setCellRange(int newCellRange) {
cellRange = newCellRange;
}
public void setPotentialRange(double newRange) {
range = newRange;
}
@Override
public IntegratorListener makeIntegratorListener() {
return new IntegratorListener() {
@Override
public void integratorInitialized(IntegratorEvent e) {
init();
}
@Override
public void integratorStepStarted(IntegratorEvent e) {
}
@Override
public void integratorStepFinished(IntegratorEvent e) {
}
};
}
private int iCell(int ax, int ay, int az) {
return (az % numCells[2])
+ (ay % numCells[1]) * numCells[2]
+ (ax % numCells[0]) * numCells[1] * numCells[2];
}
protected int wrappedIndex(int i, int nc) {
int rv = i;
while (rv < cellRange) rv += nc - 2 * cellRange;
while (nc - rv <= cellRange) rv -= nc - 2 * cellRange;
return rv;
}
@Override
public NeighborIterator makeNeighborIterator() {
return new NeighborIteratorCellFasterer(this, bondingInfo, isPureAtoms, box);
}
public void init() {
double minCellSize = range / cellRange;
int totalCells = 1;
final Vector bs = box.getBoundary().getBoxSize();
final boolean[] periodic = box.getBoundary().getPeriodicity();
int D = periodic.length;
// numCells is 3D even if we aren't, has 1 for extra components
Arrays.fill(numCells, 1);
for (int i = 0; i < D; i++) {
// with cell lists, we can accommodate rc>L/2
// we need the box to be at least the size of a cell.
// when rc>L/2, we'll end up doing a lattice sum
if (bs.getX(i) < minCellSize) {
System.err.println("box not big enough to accomodate even 1 cell (" + bs.getX(i) + " < " + minCellSize + ")");
System.exit(1);
}
// include cellRange of padding on each side of the box
numCells[i] = ((int) Math.floor(bs.getX(i) / minCellSize));
if (periodic[i]) numCells[i] += cellRange * 2;
totalCells *= numCells[i];
}
if (totalCells > cellLastAtom.length) {
cellLastAtom = new int[totalCells];
wrapMap = new int[totalCells];
boxOffsets = new Vector[totalCells];
}
int lastCellCount = 0;
numCellOffsets = 0;
for (int icd = 1; icd <= cellRange + 5; icd++) {
// we want all cells whose squared (index) distance is not more than icd
// but exclude any cells handle in the previous passes
int icd2 = icd * icd;
int iz2;
int izMax2 = D == 3 ? icd2 : 0;
for (int iz = 0; (iz2 = iz * iz) <= izMax2; iz++) {
int izm1 = iz == 0 ? 0 : (Math.abs(iz) - 1);
int izm1Sq = izm1 * izm1;
int iy2Max = icd2 - iz2;
int iyMax = D > 1 ? ((int) Math.sqrt(iy2Max + 0.001)) : 0;
for (int iy = -iyMax; iy <= iyMax; iy++) {
int iym1 = iy == 0 ? 0 : (Math.abs(iy) - 1);
int iym1Sq = iym1 * iym1;
int iy2 = iy * iy;
int ix2Max = iy2Max - iy2;
int ixMax = (int) Math.sqrt(ix2Max + 0.001);
int ix2Min = (icd - 1) * (icd - 1) - iz2 - iy2;
int ixMin;
if (ix2Min < 0) {
ix2Min = 0;
ixMin = -1;
} else {
ixMin = (int) Math.sqrt(ix2Min + 0.001);
}
for (int ix = -ixMax; ix <= ixMax; ix++) {
if (ix >= -ixMin && ix <= ixMin) {
ix = ixMin + 1;
if (ix > ixMax) break;
}
if (iz == 0) {
if (iy < 1) {
if (ix < 1) continue;
} else if (ix < 0) continue;
}
int ixm1 = ix == 0 ? 0 : (Math.abs(ix) - 1);
int ixm1Sq = ixm1 * ixm1;
if (ixm1Sq + iym1Sq + izm1Sq >= cellRange * cellRange) continue;
int mv = ix;
if (D > 0) {
if (D == 2) {
mv += iy * numCells[0];
} else if (D > 1) {
mv += (iy + iz * numCells[1]) * numCells[0];
}
}
// terrible? yes.
if (cellOffsets.length <= numCellOffsets)
cellOffsets = Arrays.copyOf(cellOffsets, numCellOffsets + 1);
cellOffsets[numCellOffsets] = mv;
numCellOffsets++;
}
}
}
if (numCellOffsets == lastCellCount) break;
lastCellCount = numCellOffsets;
}
int xboRange = periodic[0] ? (numCells[0] - cellRange - 1) / (numCells[0] - 2 * cellRange) : 0;
int yboRange = D > 1 ? (periodic[1] ? (numCells[1] - cellRange - 1) / (numCells[1] - 2 * cellRange) : 0) : 0;
int zboRange = D > 2 ? (periodic[2] ? (numCells[2] - cellRange - 1) / (numCells[2] - 2 * cellRange) : 0) : 0;
int nx = (2 * xboRange + 1);
int ny = (2 * yboRange + 1);
int nz = (2 * zboRange + 1);
if (rawBoxOffsets.length < nx * ny * nz) {
rawBoxOffsets = new Vector[nx * ny * nz];
}
for (int ix = -xboRange; ix <= xboRange; ix++) {
for (int iy = -yboRange; iy <= yboRange; iy++) {
for (int iz = -zboRange; iz <= zboRange; iz++) {
int idx = (ix + xboRange) * ny * nz + (iy + yboRange) * nz + (iz + zboRange);
rawBoxOffsets[idx] = Vector.d(D);
rawBoxOffsets[idx].setX(0, ix * bs.getX(0));
if (ny > 1) {
rawBoxOffsets[idx].setX(1, iy * bs.getX(1));
if (nz > 1) {
rawBoxOffsets[idx].setX(2, iz * bs.getX(2));
}
}
}
}
}
for (int ix = 0; ix < numCells[0]; ix++) {
int x2 = periodic[0] ? wrappedIndex(ix, numCells[0]) : ix;
int xbo = periodic[0] ? (ix - x2) / (numCells[0] - 2 * cellRange) : 0;
for (int iy = 0; iy < numCells[1]; iy++) {
int y2 = (D > 1 && periodic[1]) ? wrappedIndex(iy, numCells[1]) : iy;
int ybo = (D > 1 && periodic[1]) ? (iy - y2) / (numCells[1] - 2 * cellRange) : 0;
for (int iz = 0; iz < numCells[2]; iz++) {
int z2 = (D > 2 && periodic[2]) ? wrappedIndex(iz, numCells[2]) : iz;
int zbo = (D > 2 && periodic[2]) ? (iz - z2) / (numCells[2] - 2 * cellRange) : 0;
int iMap = iCell(ix, iy, iz);
int dCell = iCell(x2, y2, z2);
wrapMap[iMap] = dCell;
boxOffsets[iMap] = rawBoxOffsets[(xbo + xboRange) * ny * nz + (ybo + yboRange) * nz + (zbo + zboRange)];
}
}
}
this.allCellOffsets = Stream.of(
// IntStream.of(0),
IntStream.of(cellOffsets),
IntStream.of(cellOffsets).map(offset -> offset * -1)
).flatMapToInt(s -> s).toArray();
assignCellAll();
}
public void assignCellAll() {
Vector bs = box.getBoundary().getBoxSize();
if (box.getBoundary().volume() == 0) {
System.err.println("box has 0 volume, can't assign cells");
return;
}
if (range == 0 || cellRange == 0) {
System.err.println("range and cell range need to be non-zero");
return;
}
final int numAtoms = box.getLeafList().size();
if (cellNextAtom.length < numAtoms) {
cellNextAtom = new int[numAtoms];
atomCell = new int[numAtoms];
}
boxHalf.Ea1Tv1(0.5, bs);
jump[0] = numCells[1] * numCells[2];
jump[1] = numCells[2];
jump[2] = 1;
for (int i = 0; i < cellLastAtom.length; i++) {
cellLastAtom[i] = -1;
}
IAtomList atoms = box.getLeafList();
for (int iAtom = 0; iAtom < numAtoms; iAtom++) {
int cellNum = 0;
IAtom atom = atoms.get(iAtom);
Vector r = atom.getPosition();
for (int i = 0; i < r.getD(); i++) {
double x = (r.getX(i) + boxHalf.getX(i)) / bs.getX(i);
int y = ((int) (cellRange + x * (numCells[i] - 2 * cellRange)));
if (y == numCells[i] - cellRange) y
else if (y == cellRange - 1) y++;
cellNum += y * jump[i];
}
atomCell[iAtom] = cellNum;
cellNextAtom[iAtom] = cellLastAtom[cellNum];
cellLastAtom[cellNum] = iAtom;
}
}
public void removeAtom(IAtom atom) {
int iAtom = atom.getLeafIndex();
int oldCell = atomCell[iAtom];
if (oldCell > -1) {
// delete from old cell
int j = cellLastAtom[oldCell];
if (j == iAtom) {
cellLastAtom[oldCell] = cellNextAtom[iAtom];
} else {
while (cellNextAtom[j] != iAtom) {
j = cellNextAtom[j];
}
cellNextAtom[j] = cellNextAtom[iAtom];
}
}
}
public void updateAtom(IAtom atom) {
int cellNum = 0;
final Vector bs = box.getBoundary().getBoxSize();
Vector r = atom.getPosition();
for (int i = 0; i < 3; i++) {
double x = (r.getX(i) + boxHalf.getX(i)) / bs.getX(i);
int y = ((int) (cellRange + x * (numCells[i] - 2 * cellRange)));
if (y == numCells[i] - cellRange) y
else if (y == cellRange - 1) y++;
cellNum += y * jump[i];
}
int iAtom = atom.getLeafIndex();
int oldCell = atomCell[iAtom];
// check if existing assignment is right
if (cellNum == oldCell) return;
if (oldCell > -1) {
// delete from old cell
int j = cellLastAtom[oldCell];
if (j == iAtom) {
cellLastAtom[oldCell] = cellNextAtom[iAtom];
} else {
while (cellNextAtom[j] != iAtom) {
j = cellNextAtom[j];
}
cellNextAtom[j] = cellNextAtom[iAtom];
}
}
atomCell[iAtom] = cellNum;
cellNextAtom[iAtom] = cellLastAtom[cellNum];
cellLastAtom[cellNum] = iAtom;
}
public void moveAtomIndex(int oldIndex, int newIndex) {
if (oldIndex == newIndex) return;
int cell = atomCell[oldIndex];
//printf("%d was in %d\n", oldIndex, cell);
atomCell[newIndex] = cell;
cellNextAtom[newIndex] = cellNextAtom[oldIndex];
//printf("%d now points to %d\n", newIndex, cellNextAtom[newIndex]);
if (cell == -1) return;
int j = cellLastAtom[cell];
if (j == oldIndex) {
cellLastAtom[cell] = newIndex;
return;
}
while (cellNextAtom[j] != oldIndex) j = cellNextAtom[j];
cellNextAtom[j] = newIndex;
}
public Vector[] getBoxOffsets() {
return boxOffsets;
}
public int[] getAtomCell() {
return atomCell;
}
public int[] getCellNextAtom() {
return cellNextAtom;
}
public int[] getCellOffsets() {
return cellOffsets;
}
public int[] getWrapMap() {
return wrapMap;
}
public int[] getCellLastAtom() {
return cellLastAtom;
}
}
|
package com.xmlcalabash.extensions;
import com.xmlcalabash.core.XMLCalabash;
import com.xmlcalabash.core.XProcConstants;
import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.core.XProcRuntime;
import com.xmlcalabash.io.ReadablePipe;
import com.xmlcalabash.io.WritablePipe;
import com.xmlcalabash.library.DefaultStep;
import com.xmlcalabash.runtime.XAtomicStep;
import com.xmlcalabash.util.Base64;
import com.xmlcalabash.util.S9apiUtils;
import com.xmlcalabash.util.XProcURIResolver;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import static org.asciidoctor.Asciidoctor.Factory.create;
import net.sf.saxon.s9api.XdmNode;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Attributes;
import org.asciidoctor.CompatMode;
import org.asciidoctor.Options;
import org.asciidoctor.Placement;
import org.asciidoctor.SafeMode;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.sax.SAXSource;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.URISyntaxException;
@XMLCalabash(
name = "cx:asciidoctor",
type = "{http://xmlcalabash.com/ns/extensions}asciidoctor")
public class AsciiDoctor extends DefaultStep {
/* Attributes */
private static final QName _allow_read_uri = new QName("", "allow-read-uri");
private static final QName _attribute_missing = new QName("", "attribute-missing");
private static final QName _attribute_undefined = new QName("", "attribute-undefined");
private static final QName _backend = new QName("", "backend");
private static final QName _title = new QName("", "title");
private static final QName _doctype = new QName("", "doctype");
private static final QName _imagesdir = new QName("", "imagesdir");
private static final QName _source_language = new QName("", "source-language");
private static final QName _source_highlighter = new QName("", "source-highlighter");
private static final QName _max_include_depth = new QName("", "max-include-depth");
private static final QName _sectnumlevels = new QName("", "sectnumlevels");
private static final QName _hardbreaks = new QName("", "hardbreaks");
private static final QName _cache_uri = new QName("", "cache-uri");
private static final QName _hide_uri_scheme = new QName("", "hide-uri-scheme");
private static final QName _appendix_caption = new QName("", "appendix-caption");
private static final QName _math = new QName("", "math");
private static final QName _skip_front_matter = new QName("", "skip-front-matter");
private static final QName _setanchors = new QName("", "setanchors");
private static final QName _untitled_label = new QName("", "untitled-label");
private static final QName _ignore_undefined = new QName("", "ignore-undefined");
private static final QName _toc_placement = new QName("", "toc-placement");
private static final QName _toc2_placement = new QName("", "toc2-placement");
private static final QName _showtitle = new QName("", "showtitle");
private static final QName _toc = new QName("", "toc");
private static final QName _localdate = new QName("", "localdate");
private static final QName _localtime = new QName("", "localtime");
private static final QName _docdate = new QName("", "docdate");
private static final QName _doctime = new QName("", "doctime");
private static final QName _stylesheet = new QName("", "stylesheet");
private static final QName _stylesdir = new QName("", "stylesdir");
private static final QName _linkcss = new QName("", "linkcss");
private static final QName _copycss = new QName("", "copycss");
private static final QName _icons = new QName("", "icons");
private static final QName _iconfont_remote = new QName("", "iconfont-remote");
private static final QName _iconfont_cdn = new QName("", "iconfont-cdn");
private static final QName _iconfont_name = new QName("", "iconfont-name");
private static final QName _data_uri = new QName("", "data-uri");
private static final QName _iconsdir = new QName("", "iconsdir");
private static final QName _numbered = new QName("", "numbered");
private static final QName _linkattrs = new QName("", "linkattrs");
private static final QName _experimental = new QName("", "experimental");
private static final QName _nofooter = new QName("", "nofooter");
private static final QName _compat_mode = new QName("", "compat-mode");
/* Options */
private static final QName _header_footer = new QName("", "header-footer");
private static final QName _template_dirs = new QName("", "template-dirs");
private static final QName _template_engine = new QName("", "template-engine");
private static final QName _safe = new QName("", "safe");
private static final QName _eruby = new QName("", "eruby");
private static final QName _compact = new QName("", "compact");
private static final QName _base_dir = new QName("", "base-dir");
private static final QName _template_cache = new QName("", "template-cache");
private static final QName _parse_header_only = new QName("", "parse-header-only");
private static final QName _content_type = new QName("content-type");
private ReadablePipe source = null;
private WritablePipe result = null;
public AsciiDoctor(XProcRuntime runtime, XAtomicStep step) {
super(runtime, step);
}
public void setInput(String port, ReadablePipe pipe) {
source = pipe;
}
public void setOutput(String port, WritablePipe pipe) {
result = pipe;
}
public void reset() {
source.resetReader();
result.resetWriter();
}
public void run() throws SaxonApiException {
super.run();
XdmNode doc = source.read();
XdmNode root = S9apiUtils.getDocumentElement(doc);
String asciiDoc = null;
if ((XProcConstants.c_data.equals(root.getNodeName())
&& "application/octet-stream".equals(root.getAttributeValue(_content_type)))
|| "base64".equals(root.getAttributeValue(_encoding))) {
byte[] decoded = Base64.decode(root.getStringValue());
asciiDoc = new String(decoded);
} else {
asciiDoc = root.getStringValue();
}
Attributes adAttr = attributes();
Options adOpts = options();
adOpts.setAttributes(adAttr);
Asciidoctor asciidoctor = create();
String doctored = asciidoctor.convert(asciiDoc, adOpts);
try {
ByteArrayInputStream doctoredBytes = new ByteArrayInputStream(doctored.getBytes("UTF-8"));
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setEntityResolver(runtime.getResolver());
SAXSource saxSource = new SAXSource(reader, new InputSource(doctoredBytes));
DocumentBuilder builder = runtime.getProcessor().newDocumentBuilder();
builder.setLineNumbering(true);
builder.setDTDValidation(false);
builder.setBaseURI(doc.getBaseURI());
result.write(builder.build(saxSource));
} catch (Exception e) {
throw new XProcException(e);
}
}
private Attributes attributes() {
Attributes adAttr = new Attributes();
String s = null;
s = getOption(_allow_read_uri, (String) null);
if (s != null) {
adAttr.setAllowUriRead(bool(s));
}
s = getOption(_attribute_missing, (String) null);
if (s != null) {
adAttr.setAttributeMissing(s);
}
s = getOption(_attribute_undefined, (String) null);
if (s != null) {
adAttr.setAttributeUndefined(s);
}
s = getOption(_backend, (String) null);
if (s != null) {
adAttr.setBackend(s);
}
s = getOption(_title, (String) null);
if (s != null) {
adAttr.setTitle(s);
}
s = getOption(_doctype, (String) null);
if (s != null) {
adAttr.setDocType(s);
}
s = getOption(_imagesdir, (String) null);
if (s != null) {
adAttr.setImagesDir(s);
}
s = getOption(_source_language, (String) null);
if (s != null) {
adAttr.setSourceLanguage(s);
}
s = getOption(_source_highlighter, (String) null);
if (s != null) {
adAttr.setSourceHighlighter(s);
}
s = getOption(_max_include_depth, (String) null);
if (s != null) {
adAttr.setMaxIncludeDepth(Integer.parseInt(s));
}
s = getOption(_sectnumlevels, (String) null);
if (s != null) {
adAttr.setSectNumLevels(Integer.parseInt(s));
}
s = getOption(_hardbreaks, (String) null);
if (s != null) {
adAttr.setHardbreaks(bool(s));
}
s = getOption(_cache_uri, (String) null);
if (s != null) {
adAttr.setCacheUri(bool(s));
}
s = getOption(_hide_uri_scheme, (String) null);
if (s != null) {
adAttr.setHideUriScheme(bool(s));
}
s = getOption(_appendix_caption, (String) null);
if (s != null) {
adAttr.setAppendixCaption(s);
}
s = getOption(_math, (String) null);
if (s != null) {
adAttr.setMath(s);
}
s = getOption(_skip_front_matter, (String) null);
if (s != null) {
adAttr.setSkipFrontMatter(bool(s));
}
s = getOption(_setanchors, (String) null);
if (s != null) {
adAttr.setAnchors(bool(s));
}
s = getOption(_untitled_label, (String) null);
if (s != null) {
adAttr.setUntitledLabel(s);
}
s = getOption(_ignore_undefined, (String) null);
if (s != null) {
adAttr.setIgnoreUndefinedAttributes(bool(s));
}
s = getOption(_toc_placement, (String) null);
if (s != null) {
if ("left".equals(s)) {
adAttr.setTableOfContents(Placement.LEFT);
} else if ("right".equals(s)) {
adAttr.setTableOfContents(Placement.RIGHT);
} else if ("top".equals(s)) {
adAttr.setTableOfContents(Placement.TOP);
} else if ("bottom".equals(s)) {
adAttr.setTableOfContents(Placement.BOTTOM);
} else {
throw new XProcException("Invalid TOC placement value: " + s);
}
}
s = getOption(_toc2_placement, (String) null);
if (s != null) {
if ("left".equals(s)) {
adAttr.setTableOfContents2(Placement.LEFT);
} else if ("right".equals(s)) {
adAttr.setTableOfContents2(Placement.RIGHT);
} else if ("top".equals(s)) {
adAttr.setTableOfContents2(Placement.TOP);
} else if ("bottom".equals(s)) {
adAttr.setTableOfContents2(Placement.BOTTOM);
} else {
throw new XProcException("Invalid TOC placement value: " + s);
}
}
s = getOption(_showtitle, (String) null);
if (s != null) {
adAttr.setShowTitle(bool(s));
}
s = getOption(_toc, (String) null);
if (s != null) {
adAttr.setTableOfContents(bool(s));
}
s = getOption(_localdate, (String) null);
if (s != null) {
DateTimeFormatter parser = ISODateTimeFormat.date();
adAttr.setLocalDate(parser.parseDateTime(s).toLocalDate().toDate());
}
s = getOption(_localtime, (String) null);
if (s != null) {
DateTimeFormatter parser = ISODateTimeFormat.timeNoMillis();
adAttr.setLocalTime(parser.parseDateTime(s).toLocalDate().toDate());
}
s = getOption(_docdate, (String) null);
if (s != null) {
DateTimeFormatter parser = ISODateTimeFormat.date();
adAttr.setDocDate(parser.parseDateTime(s).toLocalDate().toDate());
}
s = getOption(_doctime, (String) null);
if (s != null) {
DateTimeFormatter parser = ISODateTimeFormat.timeNoMillis();
adAttr.setDocTime(parser.parseDateTime(s).toLocalDate().toDate());
}
s = getOption(_stylesheet, (String) null);
if (s != null) {
adAttr.setStyleSheetName(s);
}
s = getOption(_stylesdir, (String) null);
if (s != null) {
adAttr.setStylesDir(s);
}
s = getOption(_linkcss, (String) null);
if (s != null) {
adAttr.setLinkCss(bool(s));
}
s = getOption(_copycss, (String) null);
if (s != null) {
adAttr.setCopyCss(bool(s));
}
s = getOption(_icons, (String) null);
if (s != null) {
adAttr.setIcons(s);
}
s = getOption(_iconfont_remote, (String) null);
if (s != null) {
adAttr.setIconFontRemote(bool(s));
}
s = getOption(_iconfont_cdn, (String) null);
if (s != null) {
try {
adAttr.setIconFontCdn(new URI(s));
} catch (URISyntaxException e) {
throw new XProcException(e);
}
}
s = getOption(_iconfont_name, (String) null);
if (s != null) {
adAttr.setIconFontName(s);
}
s = getOption(_data_uri, (String) null);
if (s != null) {
adAttr.setDataUri(bool(s));
}
s = getOption(_iconsdir, (String) null);
if (s != null) {
adAttr.setIconsDir(s);
}
s = getOption(_numbered, (String) null);
if (s != null) {
adAttr.setSectionNumbers(bool(s));
}
s = getOption(_linkattrs, (String) null);
if (s != null) {
adAttr.setLinkAttrs(bool(s));
}
s = getOption(_experimental, (String) null);
if (s != null) {
adAttr.setExperimental(bool(s));
}
s = getOption(_nofooter, (String) null);
if (s != null) {
adAttr.setNoFooter(bool(s));
}
s = getOption(_compat_mode, (String) null);
if (s != null) {
if ("default".equals(s)) {
adAttr.setCompatMode(CompatMode.DEFAULT);
} else if ("legacy".equals(s)) {
adAttr.setCompatMode(CompatMode.LEGACY);
} else {
throw new XProcException("Invalid compat-mode value: " + s);
}
}
return adAttr;
}
private Options options() {
Options adOpts = new Options();
String s = null;
Boolean b = null;
s = getOption(_header_footer, (String) null);
if (s != null) {
adOpts.setHeaderFooter(bool(s));
}
s = getOption(_template_dirs, (String) null);
if (s != null) {
String[] dirs = s.split("\\s+");
adOpts.setTemplateDirs(dirs);
}
s = getOption(_template_engine, (String) null);
if (s != null) {
adOpts.setTemplateEngine(s);
}
s = getOption(_safe, (String) null);
if (s != null) {
if ("safe".equals(s)) {
adOpts.setSafe(SafeMode.SAFE);
} else if ("unsafe".equals(s)) {
adOpts.setSafe(SafeMode.UNSAFE);
} else if ("server".equals(s)) {
adOpts.setSafe(SafeMode.SERVER);
} else if ("secure".equals(s)) {
adOpts.setSafe(SafeMode.SECURE);
} else {
throw new XProcException("Invalid safe value: " + s);
}
}
s = getOption(_eruby, (String) null);
if (s != null) {
adOpts.setEruby(s);
}
s = getOption(_compact, (String) null);
if (s != null) {
adOpts.setCompact(bool(s));
}
s = getOption(_base_dir, (String) null);
if (s != null) {
adOpts.setBaseDir(s);
}
s = getOption(_template_cache, (String) null);
if (s != null) {
adOpts.setTemplateCache(bool(s));
}
s = getOption(_parse_header_only, (String) null);
if (s != null) {
adOpts.setParseHeaderOnly(bool(s));
}
return adOpts;
}
private boolean bool(String s) {
if ("true".equals(s)) {
return true;
} else if ("false".equals(s)) {
return false;
} else {
throw new XProcException("Invalid boolean value: " + s);
}
}
}
|
package com.xmomen.module.wx.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xmomen.framework.utils.StringUtilsExt;
import com.xmomen.module.wx.constants.AuthorizeScope;
import com.xmomen.module.wx.constants.WechatUrlConstants;
import com.xmomen.module.wx.model.AccessTokenOAuth;
public class Auth2Handler {
static Logger logger = LoggerFactory.getLogger(Auth2Handler.class);
private static final String STATE = "WJHYORDER";
private static final String APPID = "wx7e9cfeede085ae15";
private static final String APPSECRET = "0ed640e24adc6a0e7b89c865c4271f74";
public static String getOauthUrl(String redirectUrl) {
String url = "";
try {
url = WechatUrlConstants.OAUTH.replace("APPID", APPID)
.replace("REDIRECT_URI", URLEncoder.encode(redirectUrl, "UTF-8"))
.replace("SCOPE", AuthorizeScope.snsapi_userinfo.toString())
.replace("STATE", STATE);
} catch (UnsupportedEncodingException e) {
logger.error("oauthURLredirectUrlurlencoder" + redirectUrl, e);
e.printStackTrace();
}
return url;
}
/**
* @param code
* @return
*/
public static AccessTokenOAuth getAccessToken(String code) {
String url = WechatUrlConstants.GET_ACCESS_TOKEN_OAUTH.replace("APPID", APPID)
.replace("SECRET", APPSECRET)
.replace("CODE", code);
logger.info("auth openid url --->" + url);
HttpRequest shc = new HttpClient();
String result = shc.doPost(url, "");
logger.info("request result -->" + result);
AccessTokenOAuth accessToken = null;
if (StringUtilsExt.isNotEmpty(result)) {
JSONObject json = JSON.parseObject(result);
if (null != json) {
if (StringUtilsExt.isNotEmpty(json.getString("errcode")) && json.getIntValue("errcode") != 0) {
logger.error("oauth access_token,code=" + json.getIntValue("errcode") + ",msg=" + json.getIntValue("errmsg"));
}
else {
accessToken = new AccessTokenOAuth();
accessToken.setAccessToken(json.getString("access_token"));
accessToken.setExpiresIn(json.getIntValue("expires_in"));
accessToken.setRefreshToken(json.getString("refresh_token"));
accessToken.setOpenid(json.getString("openid"));
accessToken.setScope(json.getString("scope"));
}
}
}
return accessToken;
}
}
|
package com.yahoo.sketches.kll;
import java.util.Arrays;
import com.yahoo.memory.Memory;
import com.yahoo.sketches.ByteArrayUtil;
import com.yahoo.sketches.Family;
import com.yahoo.sketches.SketchesArgumentException;
import com.yahoo.sketches.Util;
public class KllFloatsSketch {
public static final int DEFAULT_K = 200;
public static final int DEFAULT_M = 8;
public static final int MIN_K = 8;
public static final int MAX_K = (1 << 16) - 1; // serialized as an unsigned short
private static final int PREAMBLE_INTS_BYTE = 0;
private static final int SER_VER_BYTE = 1;
private static final int FAMILY_BYTE = 2;
private static final int FLAGS_BYTE = 3;
private static final int K_SHORT = 4; // to 5
private static final int M_BYTE = 6;
private static final int N_LONG = 8; // to 15
private static final int MIN_K_SHORT = 16; // to 17
private static final int NUM_LEVELS_BYTE = 18;
private static final int DATA_START = 20;
private static final byte serialVersionUID = 1;
private enum Flags { IS_EMPTY, IS_LEVEL_ZERO_SORTED }
private static final int PREAMBLE_INTS_EMPTY = 2;
private static final int PREAMBLE_INTS_NONEMPTY = 5;
/*
* Data is stored in items_.
* The data for level i lies in positions levels_[i] through levels_[i + 1] - 1 inclusive.
* Hence levels_ must contain (numLevels_ + 1) indices.
* The valid portion of items_ is completely packed, except for level 0.
* Level 0 is filled from the top down.
*
* Invariants:
* 1) After a compaction, or an update, or a merge, all levels are sorted except for level zero.
* 2) After a compaction, (sum of capacities) - (sum of items) >= 1,
* so there is room for least 1 more item in level zero.
* 3) There are no gaps except at the bottom, so if levels_[0] = 0,
* the sketch is exactly filled to capacity and must be compacted.
*/
private final int k_;
private final int m_; // minimum buffer "width"
private int minK_; // for error estimation after merging with different k
private long n_;
private int numLevels_;
private int[] levels_;
private float[] items_;
private float minValue_;
private float maxValue_;
private boolean isLevelZeroSorted_;
/**
* Constructor with the default K (rank error of about 1.65%)
*/
public KllFloatsSketch() {
this(DEFAULT_K);
}
/**
* Constructor with a given parameter K
* @param k parameter that controls size of the sketch and accuracy of estimates
*/
public KllFloatsSketch(final int k) {
this(k, DEFAULT_M);
}
/**
* Returns the length of the input stream.
* @return stream length
*/
public long getN() {
return n_;
}
/**
* Returns true if this sketch is empty
* @return empty flag
*/
public boolean isEmpty() {
return n_ == 0;
}
/**
* Returns the number of retained items (samples) in the sketch
* @return the number of retained items (samples) in the sketch
*/
public int getNumRetained() {
return levels_[numLevels_] - levels_[0];
}
/**
* Returns true if this sketch is in estimation mode.
* @return estimation mode flag
*/
public boolean isEstimationMode() {
return numLevels_ > 1;
}
/**
* Updates this sketch with the given data item
*
* @param value an item from a stream of items. NaNs are ignored.
*/
public void update(final float value) {
if (Float.isNaN(value)) { return; }
if (isEmpty()) {
minValue_ = value;
maxValue_ = value;
} else {
if (value < minValue_) { minValue_ = value; }
if (value > maxValue_) { maxValue_ = value; }
}
if (levels_[0] == 0) {
compressWhileUpdating();
}
n_++;
isLevelZeroSorted_ = false;
final int nextPos = levels_[0] - 1;
assert levels_[0] >= 0;
levels_[0] = nextPos;
items_[nextPos] = value;
}
/**
* Merges another sketch into this one.
* @param other sketch to merge into this one
*/
public void merge(final KllFloatsSketch other) {
if (other == null || other.isEmpty()) { return; }
if (m_ != other.m_) {
throw new SketchesArgumentException("incompatible M: " + m_ + " and " + other.m_);
}
if (isEmpty()) {
minValue_ = other.minValue_;
maxValue_ = other.maxValue_;
} else {
if (other.minValue_ < minValue_) { minValue_ = other.minValue_; }
if (other.maxValue_ > maxValue_) { maxValue_ = other.maxValue_; }
}
final long finalN = n_ + other.n_;
if (other.numLevels_ >= 1) {
for (int i = other.levels_[0]; i < other.levels_[1]; i++) {
update(other.items_[i]);
}
}
if (other.numLevels_ >= 2) {
mergeHigherLevels(other, finalN);
}
n_ = finalN;
assertCorrectTotalWeight();
minK_ = Math.min(minK_, other.minK_);
}
/**
* Returns the min value of the stream.
* If the sketch is empty this returns NaN.
*
* @return the min value of the stream
*/
public float getMinValue() {
return minValue_;
}
/**
* Returns the max value of the stream.
* If the sketch is empty this returns NaN.
*
* @return the max value of the stream
*/
public float getMaxValue() {
return maxValue_;
}
/**
* Returns an approximation to the value of the data item
* that would be preceded by the given fraction of a hypothetical sorted
* version of the input stream so far.
*
* <p>We note that this method has a fairly large overhead (microseconds instead of nanoseconds)
* so it should not be called multiple times to get different quantiles from the same
* sketch. Instead use getQuantiles(), which pays the overhead only once.
*
* <p>If the sketch is empty this returns NaN.
*
* @param fraction the specified fractional position in the hypothetical sorted stream.
* These are also called normalized ranks or fractional ranks.
* If fraction = 0.0, the true minimum value of the stream is returned.
* If fraction = 1.0, the true maximum value of the stream is returned.
*
* @return the approximation to the value at the given fraction
*/
public float getQuantile(final double fraction) {
if (isEmpty()) { return Float.NaN; }
if (fraction == 0.0) { return minValue_; }
if (fraction == 1.0) { return maxValue_; }
if ((fraction < 0.0) || (fraction > 1.0)) {
throw new SketchesArgumentException("Fraction cannot be less than zero or greater than 1.0");
}
final KllFloatsQuantileCalculator quant = getQuantileCalculator();
return quant.getQuantile(fraction);
}
/**
* This is a more efficient multiple-query version of getQuantile().
*
* <p>This returns an array that could have been generated by using getQuantile() with many different
* fractional ranks, but would be very inefficient.
* This method incurs the internal set-up overhead once and obtains multiple quantile values in
* a single query. It is strongly recommend that this method be used instead of multiple calls
* to getQuantile().
*
* <p>If the sketch is empty this returns null.
*
* @param fractions given array of fractional positions in the hypothetical sorted stream.
* These are also called normalized ranks or fractional ranks.
* These fractions must be in the interval [0.0, 1.0] inclusive.
*
* @return array of approximations to the given fractions in the same order as given fractions
* array.
*/
public float[] getQuantiles(final double[] fractions) {
if (isEmpty()) { return null; }
KllFloatsQuantileCalculator quant = null;
final float[] quantiles = new float[fractions.length];
for (int i = 0; i < fractions.length; i++) {
final double fraction = fractions[i];
if (fraction == 0.0) { quantiles[i] = minValue_; }
else if (fraction == 1.0) { quantiles[i] = maxValue_; }
else {
if (quant == null) {
quant = getQuantileCalculator();
}
quantiles[i] = quant.getQuantile(fraction);
}
}
return quantiles;
}
/**
* Returns an approximation to the normalized (fractional) rank of the given value from 0 to 1 inclusive.
* @param value to be ranked
* @return an approximate rank of the given value
*/
public double getRank(final float value) {
if (isEmpty()) { return Double.NaN; }
int level = 0;
int weight = 1;
long total = 0;
while (level < numLevels_) {
final int fromIndex = levels_[level];
final int toIndex = levels_[level + 1]; // exclusive
for (int i = fromIndex; i < toIndex; i++) {
if (items_[i] < value) {
total += weight;
} else if (level > 0 || isLevelZeroSorted_) {
break; // levels above 0 are sorted, no point comparing further
}
}
level++;
weight *= 2;
}
return (double) total / n_;
}
/**
* Returns an approximation to the Probability Mass Function (PMF) of the input stream
* given a set of splitPoints (values).
*
* <p>The resulting approximations have a probabilistic guarantee that can be obtained from the
* getNormalizedRankError() function.
*
* <p>If the sketch is empty this returns null.</p>
*
* @param splitPoints an array of <i>m</i> unique, monotonically increasing values
* that divide the real number line into <i>m+1</i> consecutive disjoint intervals.
*
* @return an array of m+1 doubles each of which is an approximation
* to the fraction of the input stream values that fell into one of those intervals.
* The definition of an "interval" is inclusive of the left splitPoint and exclusive of the right
* splitPoint.
*/
public double[] getPMF(final float[] splitPoints) {
return getPmfOrCdf(splitPoints, false);
}
/**
* Returns an approximation to the Cumulative Distribution Function (CDF), which is the
* cumulative analog of the PMF, of the input stream given a set of splitPoint (values).
*
* <p>More specifically, the value at array position j of the CDF is the
* sum of the values in positions 0 through j of the PMF (rank of the splitPoint j).
*
* <p>If the sketch is empty this returns null.</p>
*
* @param splitPoints an array of <i>m</i> unique, monotonically increasing values
* that divide the real number line into <i>m+1</i> consecutive disjoint intervals.
*
* @return an approximation to the CDF of the input stream given the splitPoints.
*/
public double[] getCDF(final float[] splitPoints) {
return getPmfOrCdf(splitPoints, true);
}
/**
* Get the rank error normalized as a fraction between zero and one.
* The error of this sketch is specified as a fraction of the normalized rank of the hypothetical
* sorted stream of items presented to the sketch.
*
* <p>Suppose the sketch is presented with N values. The raw rank (0 to N-1) of an item
* would be its index position in the sorted version of the input stream. If we divide the
* raw rank by N, it becomes the normalized rank, which is between 0 and 1.0.
*
* <p>For example, choosing a K of 200 (default) yields a normalized rank error of about 1.65%.
* The upper bound on the median value obtained by getQuantile(0.5) would be the value in the
* hypothetical ordered stream of values at the normalized rank of 0.513.
* The lower bound would be the value in the hypothetical ordered stream of values at the
* normalized rank of 0.487.
*
* <p>The returned error is for so-called "two-sided"queries corresponding to histogram bins of getPMF().
* "One-sided" queries (getRank() and getCDF()) are expected to have slightly lower error (factor of 0.85 for
* small K=16 to 0.75 for large K=4096).
*
* <p>The error of this sketch cannot be translated into an error (relative or absolute) of the
* returned quantile values.
*
* @return the rank error normalized as a fraction between zero and one.
*/
public double getNormalizedRankError() {
return getNormalizedRankError(minK_);
}
/**
* Static method version of {@link #getNormalizedRankError()}
* @param k the configuration parameter
* @return the rank error normalized as a fraction between zero and one.
*/
// constants were derived as the best fit to 99 percentile empirically measured max error in thousands of trials
public static double getNormalizedRankError(final int k) {
return 2.446 / Math.pow(k, 0.943);
}
/**
* Returns the number of bytes this sketch would require to store.
* @return the number of bytes this sketch would require to store.
*/
public int getSerializedSizeBytes() {
if (isEmpty()) return N_LONG;
return getSerializedSizeBytes(numLevels_, getNumRetained());
}
/**
* Returns upper bound on the serialized size of a sketch given a parameter K and stream length.
* The resulting size is an overestimate to make sure actual sketches don't exceed it.
* This method can be used if allocation of storage is necessary beforehand, but it is not optimal.
* @param k
* @param n
* @return upper bound on the serialized size
*/
public static int getMaxSerializedSizeBytes(final int k, final long n) {
final int numLevels = KllHelper.ubOnNumLevels(n);
final int maxNumItems = KllHelper.computeTotalCapacity(k, DEFAULT_M, numLevels);
return getSerializedSizeBytes(numLevels, maxNumItems);
}
@Override
public String toString() {
return toString(false, false);
}
/**
* Returns a summary of the sketch as a string
* @param withLevels if true include information about levels
* @param withData if true include sketch data
* @return string representation of sketch summary
*/
public String toString(final boolean withLevels, final boolean withData) {
final String epsilonPct = String.format("%.3f%%", getNormalizedRankError() * 100);
final StringBuilder sb = new StringBuilder();
sb.append(Util.LS).append("### KLL sketch summary:").append(Util.LS);
sb.append(" K : ").append(k_).append(Util.LS);
sb.append(" min K : ").append(minK_).append(Util.LS);
sb.append(" Normalized Rank Error: ").append(epsilonPct).append(Util.LS);
sb.append(" M : ").append(m_).append(Util.LS);
sb.append(" Empty : ").append(isEmpty()).append(Util.LS);
sb.append(" Estimation Mode : ").append(isEstimationMode()).append(Util.LS);
sb.append(" N : ").append(n_).append(Util.LS);
sb.append(" Levels : ").append(numLevels_).append(Util.LS);
sb.append(" Sorted : ").append(isLevelZeroSorted_).append(Util.LS);
sb.append(" Buffer Capacity Items: ").append(items_.length).append(Util.LS);
sb.append(" Retained Items : ").append(getNumRetained()).append(Util.LS);
sb.append(" Storage Bytes : ").append(getSerializedSizeBytes()).append(Util.LS);
sb.append(" Min Value : ").append(minValue_).append(Util.LS);
sb.append(" Max Value : ").append(maxValue_).append(Util.LS);
sb.append("### End sketch summary").append(Util.LS);
if (withLevels) {
sb.append("### KLL sketch levels:").append(Util.LS)
.append(" index: nominal capacity, actual size").append(Util.LS);
for (int i = 0; i < numLevels_; i++) {
sb.append(" ").append(i).append(": ").append(KllHelper.levelCapacity(k_, numLevels_, i, m_))
.append(", ").append(safeLevelSize(i)).append(Util.LS);
}
sb.append("### End sketch levels").append(Util.LS);
}
if (withData) {
sb.append("### KLL sketch data:").append(Util.LS);
int level = 0;
while (level < numLevels_) {
final int fromIndex = levels_[level];
final int toIndex = levels_[level + 1]; // exclusive
if (fromIndex < toIndex) {
sb.append(" level ").append(level).append(":").append(Util.LS);
}
for (int i = fromIndex; i < toIndex; i++) {
sb.append(" ").append(items_[i]).append(Util.LS);
}
level++;
}
sb.append("### End sketch data").append(Util.LS);
}
return sb.toString();
}
/**
* Returns serialized sketch in a byte array form.
* @return serialized sketch in a byte array form.
*/
public byte[] toByteArray() {
final byte[] bytes = new byte[getSerializedSizeBytes()];
bytes[PREAMBLE_INTS_BYTE] = (byte) (isEmpty() ? PREAMBLE_INTS_EMPTY : PREAMBLE_INTS_NONEMPTY);
bytes[SER_VER_BYTE] = serialVersionUID;
bytes[FAMILY_BYTE] = (byte) Family.KLL.getID();
bytes[FLAGS_BYTE] = (byte) (
(isEmpty() ? 1 << Flags.IS_EMPTY.ordinal() : 0)
| (isLevelZeroSorted_ ? 1 << Flags.IS_LEVEL_ZERO_SORTED.ordinal() : 0)
);
ByteArrayUtil.putShort(bytes, K_SHORT, (short) k_);
bytes[M_BYTE] = (byte) m_;
if (isEmpty()) { return bytes; }
ByteArrayUtil.putLong(bytes, N_LONG, n_);
ByteArrayUtil.putShort(bytes, MIN_K_SHORT, (short) minK_);
bytes[NUM_LEVELS_BYTE] = (byte) numLevels_;
int offset = DATA_START;
// the last integer in levels_ is not serialized because it can be derived
for (int i = 0; i < numLevels_; i++) {
ByteArrayUtil.putInt(bytes, offset, levels_[i]);
offset += Integer.BYTES;
}
ByteArrayUtil.putFloat(bytes, offset, minValue_);
offset += Float.BYTES;
ByteArrayUtil.putFloat(bytes, offset, maxValue_);
offset += Float.BYTES;
final int numItems = getNumRetained();
for (int i = 0; i < numItems; i++) {
ByteArrayUtil.putFloat(bytes, offset, items_[levels_[0] + i]);
offset += Float.BYTES;
}
return bytes;
}
/**
* Heapify takes the sketch image in Memory and instantiates an on-heap sketch.
* The resulting sketch will not retain any link to the source Memory.
* @param mem a Memory image of a sketch.
* <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
* @return a heap-based sketch based on the given Memory
*/
public static KllFloatsSketch heapify(final Memory mem) {
final int preambleInts = mem.getByte(PREAMBLE_INTS_BYTE) & 0xff;
final int serialVersion = mem.getByte(SER_VER_BYTE) & 0xff;
final int family = mem.getByte(FAMILY_BYTE) & 0xff;
final int flags = mem.getByte(FLAGS_BYTE) & 0xff;
final int m = mem.getByte(M_BYTE) & 0xff;
if (m != DEFAULT_M) {
throw new SketchesArgumentException("Possible corruption: M must be " + DEFAULT_M + ": " + m);
}
final boolean isEmpty = (flags & (1 << Flags.IS_EMPTY.ordinal())) > 0;
if (isEmpty) {
if (preambleInts != PREAMBLE_INTS_EMPTY) {
throw new SketchesArgumentException("Possible corruption: preambleInts must be "
+ PREAMBLE_INTS_EMPTY + " for an empty sketch: " + preambleInts);
}
} else {
if (preambleInts != PREAMBLE_INTS_NONEMPTY) {
throw new SketchesArgumentException("Possible corruption: preambleInts must be "
+ PREAMBLE_INTS_NONEMPTY + " for a non-empty sketch: " + preambleInts);
}
}
if (serialVersion != serialVersionUID) {
throw new SketchesArgumentException(
"Possible corruption: serial version mismatch: expected " + serialVersionUID + ", got " + serialVersion);
}
if (family != Family.KLL.getID()) {
throw new SketchesArgumentException(
"Possible corruption: family mismatch: expected " + Family.KLL.getID() + ", got " + family);
}
return new KllFloatsSketch(mem);
}
private KllFloatsSketch(final Memory mem) {
m_ = DEFAULT_M;
k_ = mem.getShort(K_SHORT) & 0xffff;
final int flags = mem.getByte(FLAGS_BYTE) & 0xff;
final boolean isEmpty = (flags & (1 << Flags.IS_EMPTY.ordinal())) > 0;
if (isEmpty) {
numLevels_ = 1;
levels_ = new int[] {k_, k_};
items_ = new float[k_];
minValue_ = Float.NaN;
maxValue_ = Float.NaN;
isLevelZeroSorted_ = false;
minK_ = k_;
} else {
n_ = mem.getLong(N_LONG);
minK_ = mem.getShort(MIN_K_SHORT) & 0xffff;
numLevels_ = mem.getByte(NUM_LEVELS_BYTE) & 0xff;
levels_ = new int[numLevels_ + 1];
int offset = DATA_START;
// the last integer in levels_ is not serialized because it can be derived
mem.getIntArray(offset, levels_, 0, numLevels_);
offset += numLevels_ * Integer.BYTES;
final int capacity = KllHelper.computeTotalCapacity(k_, m_, numLevels_);
levels_[numLevels_] = capacity;
minValue_ = mem.getFloat(offset);
offset += Float.BYTES;
maxValue_ = mem.getFloat(offset);
offset += Float.BYTES;
items_ = new float[capacity];
mem.getFloatArray(offset, items_, levels_[0], getNumRetained());
isLevelZeroSorted_ = (flags & (1 << Flags.IS_LEVEL_ZERO_SORTED.ordinal())) > 0;
}
}
private KllFloatsSketch(final int k, final int m) {
if (k < MIN_K || k > MAX_K) {
throw new SketchesArgumentException("K must be >= " + MIN_K + " and < " + MAX_K + ": " + k);
}
k_ = k;
m_ = m;
numLevels_ = 1;
levels_ = new int[] {k, k};
items_ = new float[k];
minValue_ = Float.NaN;
maxValue_ = Float.NaN;
isLevelZeroSorted_ = false;
minK_ = k;
}
private KllFloatsQuantileCalculator getQuantileCalculator() {
sortLevelZero(); // sort in the sketch to reuse if possible
return new KllFloatsQuantileCalculator(items_, levels_, numLevels_, n_);
}
private double[] getPmfOrCdf(final float[] splitPoints, boolean isCdf) {
if (isEmpty()) { return null; }
KllHelper.validateValues(splitPoints);
final double[] buckets = new double[splitPoints.length + 1];
int level = 0;
int weight = 1;
while (level < numLevels_) {
final int fromIndex = levels_[level];
final int toIndex = levels_[level + 1]; // exclusive
if (level == 0 && !isLevelZeroSorted_) {
incrementBucketsUnsortedLevel(fromIndex, toIndex, weight, splitPoints, buckets);
} else {
incrementBucketsSortedLevel(fromIndex, toIndex, weight, splitPoints, buckets);
}
level++;
weight *= 2;
}
// normalize and, if CDF, convert to cumulative
if (isCdf) {
double subtotal = 0;
for (int i = 0; i < buckets.length; i++) {
subtotal += buckets[i];
buckets[i] = subtotal / n_;
}
} else {
for (int i = 0; i < buckets.length; i++) {
buckets[i] /= n_;
}
}
return buckets;
}
private void incrementBucketsUnsortedLevel(final int fromIndex, final int toIndex, final int weight, final float[] splitPoints, final double[] buckets) {
for (int i = fromIndex; i < toIndex; i++) {
int j;
for (j = 0; j < splitPoints.length; j++) {
if (items_[i] < splitPoints[j]) {
break;
}
}
buckets[j] += weight;
}
}
private void incrementBucketsSortedLevel(final int fromIndex, final int toIndex, final int weight, final float[] splitPoints, final double[] buckets) {
int i = fromIndex;
int j = 0;
while (i < toIndex && j < splitPoints.length) {
if (items_[i] < splitPoints[j]) {
buckets[j] += weight; // this sample goes into this bucket
i++; // move on to next sample and see whether it also goes into this bucket
} else {
j++; // no more samples for this bucket
}
}
// now either i == toIndex (we are out of samples), or
// j == numSplitPoints (we are out of buckets, but there are more samples remaining)
// we only need to do something in the latter case
if (j == splitPoints.length) {
buckets[j] += weight * (toIndex - i);
}
}
// The following code is only valid in the special case of exactly reaching capacity while updating.
// It cannot be used while merging, while reducing k, or anything else.
private void compressWhileUpdating() {
final int level = findLevelToCompact();
// It is important to do add the new top level right here. Be aware that this operation grows the buffer
// and shifts the data and also the boundaries of the data and grows the levels array and increments numLevels_
if (level == numLevels_ - 1) {
addEmptyTopLevelToCompletelyFullSketch();
}
final int rawBeg = levels_[level];
final int rawLim = levels_[level + 1];
final int popAbove = levels_[level + 2] - rawLim; // +2 is OK because we already added a new top level if necessary
final int rawPop = rawLim - rawBeg;
final boolean oddPop = KllHelper.isOdd(rawPop);
final int adjBeg = oddPop ? rawBeg + 1 : rawBeg;
final int adjPop = oddPop ? rawPop - 1 : rawPop;
final int halfAdjPop = adjPop / 2;
// level zero might not be sorted, so we must sort it if we wish to compact it
if (level == 0) {
sortLevelZero();
}
if (popAbove == 0) {
KllHelper.randomlyHalveUp(items_, adjBeg, adjPop);
} else {
KllHelper.randomlyHalveDown(items_, adjBeg, adjPop);
KllHelper.mergeSortedArrays(items_, adjBeg, halfAdjPop, items_, rawLim, popAbove, items_, adjBeg + halfAdjPop);
}
levels_[level + 1] -= halfAdjPop; // adjust boundaries of the level above
if (oddPop) {
levels_[level] = levels_[level + 1] - 1; // the current level now contains one item
items_[levels_[level]] = items_[rawBeg]; // namely this leftover guy
} else {
levels_[level] = levels_[level + 1]; // the current level is now empty
}
// verify that we freed up halfAdjPop array slots just below the current level
assert levels_[level] == rawBeg + halfAdjPop;
// finally, we need to shift up the data in the levels below
// so that the freed-up space can be used by level zero
if (level > 0) {
final int amount = rawBeg - levels_[0];
System.arraycopy(items_, levels_[0], items_, levels_[0] + halfAdjPop, amount);
for (int lvl = 0; lvl < level; lvl++) {
levels_[lvl] += halfAdjPop;
}
}
}
private int findLevelToCompact() {
int level = 0;
while (true) {
assert level < numLevels_;
final int pop = levels_[level + 1] - levels_[level];
final int cap = KllHelper.levelCapacity(k_, numLevels_, level, m_);
if (pop >= cap) {
return level;
}
level++;
}
}
private void addEmptyTopLevelToCompletelyFullSketch() {
final int curTotalCap = levels_[numLevels_];
// make sure that we are following a certain growth scheme
assert levels_[0] == 0;
assert items_.length == curTotalCap;
// note that merging MIGHT over-grow levels_, in which case we might not have to grow it here
if (levels_.length < numLevels_ + 2) {
levels_ = KllHelper.growIntArray(levels_, numLevels_ + 2);
}
final int deltaCap = KllHelper.levelCapacity(k_, numLevels_ + 1, 0, m_);
final int newTotalCap = curTotalCap + deltaCap;
final float[] newBuf = new float[newTotalCap];
// copy (and shift) the current data into the new buffer
System.arraycopy(items_, levels_[0], newBuf, levels_[0] + deltaCap, curTotalCap);
items_ = newBuf;
// this loop includes the old "extra" index at the top
for (int i = 0; i <= numLevels_; i++) {
levels_[i] += deltaCap;
}
assert levels_[numLevels_] == newTotalCap;
numLevels_++;
levels_[numLevels_] = newTotalCap; // initialize the new "extra" index at the top
}
private void sortLevelZero() {
if (!isLevelZeroSorted_) {
Arrays.sort(items_, levels_[0], levels_[1]);
isLevelZeroSorted_ = true;
}
}
private void mergeHigherLevels(final KllFloatsSketch other, final long finalN) {
int tmpSpaceNeeded = getNumRetained() + other.getNumRetainedAboveLevelZero();
final float[] workbuf = new float[tmpSpaceNeeded];
final int ub = KllHelper.ubOnNumLevels(finalN);
final int[] worklevels = new int[ub + 2]; // ub+1 does not work
final int[] outlevels = new int[ub + 2];
final int provisionalNumLevels = Math.max(numLevels_, other.numLevels_);
populateWorkArrays(other, workbuf, worklevels, provisionalNumLevels);
// notice that workbuf is being used as both the input and output here
final int[] result = KllHelper.generalCompress(k_, m_, provisionalNumLevels, workbuf, worklevels, workbuf,
outlevels, isLevelZeroSorted_);
final int finalNumLevels = result[0];
final int finalCapacity = result[1];
final int finalPop = result[2];
assert (finalNumLevels <= ub); // can sometimes be much bigger
// now we need to transfer the results back into the "self" sketch
final float[] newbuf = finalCapacity == items_.length ? items_ : new float[finalCapacity];
final int freeSpaceAtBottom = finalCapacity - finalPop;
System.arraycopy(workbuf, outlevels[0], newbuf, freeSpaceAtBottom, finalPop);
final int theShift = freeSpaceAtBottom - outlevels[0];
if (levels_.length < (finalNumLevels + 1)) {
levels_ = new int[finalNumLevels + 1];
}
for (int lvl = 0; lvl < finalNumLevels + 1; lvl++) { // includes the "extra" index
levels_[lvl] = outlevels[lvl] + theShift;
}
items_ = newbuf;
numLevels_ = finalNumLevels;
}
private void populateWorkArrays(final KllFloatsSketch other, final float[] workbuf, final int[] worklevels, final int provisionalNumLevels) {
worklevels[0] = 0;
// Note: the level zero data from "other" was already inserted into "self"
final int selfPopZero = safeLevelSize(0);
System.arraycopy(items_, levels_[0], workbuf, worklevels[0], selfPopZero);
worklevels[1] = worklevels[0] + selfPopZero;
for (int lvl = 1; lvl < provisionalNumLevels; lvl++) {
final int selfPop = safeLevelSize(lvl);
final int otherPop = other.safeLevelSize(lvl);
worklevels[lvl + 1] = worklevels[lvl] + selfPop + otherPop;
if (selfPop > 0 && otherPop == 0) {
System.arraycopy(items_, levels_[lvl], workbuf, worklevels[lvl], selfPop);
} else if (selfPop == 0 && otherPop > 0) {
System.arraycopy(other.items_, other.levels_[lvl], workbuf, worklevels[lvl], otherPop);
} else if (selfPop > 0 && otherPop > 0) {
KllHelper.mergeSortedArrays(items_, levels_[lvl], selfPop, other.items_, other.levels_[lvl], otherPop, workbuf, worklevels[lvl]);
}
}
}
private int safeLevelSize(final int level) {
if (level >= numLevels_) { return 0; }
return levels_[level + 1] - levels_[level];
}
private int getNumRetainedAboveLevelZero() {
if (numLevels_ == 1) { return 0; }
return levels_[numLevels_] - levels_[1];
}
private void assertCorrectTotalWeight() {
long total = KllHelper.sumTheSampleWeights(numLevels_, levels_);
assert total == n_;
}
// the last integer in levels_ is not serialized because it can be derived
private static int getSerializedSizeBytes(final int numLevels, final int numRetained) {
return DATA_START + numLevels * Integer.BYTES + (numRetained + 2) * Float.BYTES; // + 2 for min and max
}
}
|
package com.zierfisch.gfx.shader;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL32.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.zierfisch.gfx.util.GLErrors;
public class ShaderBuilder {
private static final int NO_SHADER = Integer.MIN_VALUE;
private String vertexShaderSource;
private String fragmentShaderSource;
private String geometryShaderSource;
private int vertexShader = NO_SHADER;
private int fragmentShader = NO_SHADER;
private int geometryShader = NO_SHADER;
/**
* Caches the last built shader in case nothing changed.
* This way, multiple build calls return the same shader.
*/
private Shader shader;
public ShaderBuilder setVertexShader(String srcFilePath) {
vertexShaderSource = srcFilePath;
vertexShader = NO_SHADER;
shader = null;
return this;
}
public ShaderBuilder setFragmentShader(String srcFilePath) {
fragmentShaderSource = srcFilePath;
fragmentShader = NO_SHADER;
shader = null;
return this;
}
public ShaderBuilder setGeometryShader(String srcFilePath) {
geometryShaderSource = srcFilePath;
geometryShader = NO_SHADER;
shader = null;
return this;
}
public Shader build() {
// Be lazy if no build parameters changed since last the last build
if(shader == null) {
buildVertexShader();
buildGeometryShader();
buildFragmentShader();
int shaderProgram = compileAndLinkProgram();
checkLinkStatus(shaderProgram);
cleanupShaders(shaderProgram);
shader = new Shader(shaderProgram);
}
return shader;
}
private void buildVertexShader() {
if(vertexShaderSource == null) {
throw new IllegalStateException("Trying to build Shader but no vertex shader source file was specified");
}
if(vertexShader == NO_SHADER) {
vertexShader = compileShader(vertexShaderSource, GL_VERTEX_SHADER);
}
}
private void buildFragmentShader() {
if(fragmentShaderSource == null) {
throw new IllegalStateException("Trying to build Shader but no fragment shader source file was specified");
}
if(fragmentShader == NO_SHADER) {
fragmentShader = compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER);
}
}
private void buildGeometryShader() {
if(geometryShaderSource != null && geometryShader == NO_SHADER) {
geometryShader = compileShader(geometryShaderSource, GL_GEOMETRY_SHADER);
}
}
private int compileAndLinkProgram() {
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
if(geometryShader != NO_SHADER) {
glAttachShader(shaderProgram, geometryShader);
}
glLinkProgram(shaderProgram);
return shaderProgram;
}
private void checkLinkStatus(int shaderProgram) {
int[] isLinked = { GL_FALSE };
glGetProgramiv(shaderProgram, GL_LINK_STATUS, isLinked);
if(isLinked[0] == GL_FALSE) {
String log = glGetProgramInfoLog(shaderProgram);
glDeleteProgram(shaderProgram);
// Delete shaders when link whas unsuccessful
glDeleteShader(vertexShader);
vertexShader = NO_SHADER;
glDeleteShader(fragmentShader);
fragmentShader = NO_SHADER;
if(geometryShader != NO_SHADER) {
glDeleteShader(geometryShader);
geometryShader = NO_SHADER;
}
throw new RuntimeException("Shader program could not be linked:\n" + log);
}
}
private void cleanupShaders(int shaderProgram) {
glDetachShader(shaderProgram, vertexShader);
vertexShader = NO_SHADER;
glDetachShader(shaderProgram, fragmentShader);
fragmentShader = NO_SHADER;
if(geometryShader != NO_SHADER) {
glDetachShader(shaderProgram, geometryShader);
geometryShader = NO_SHADER;
}
}
private String load(String path) {
try {
return String.join("\n", Files.readAllLines(Paths.get(path)));
} catch (IOException e) {
throw new RuntimeException("Loading shader source failed", e);
}
}
private int compileShader(String shaderSourceFilePath, int shaderType) {
if(shaderSourceFilePath == null) {
return NO_SHADER;
}
String shaderSource = load(shaderSourceFilePath);
int shader = glCreateShader(shaderType);
GLErrors.check();
glShaderSource(shader, shaderSource);
GLErrors.check();
glCompileShader(shader);
GLErrors.check();
int[] isCompiled = new int[1];
isCompiled[0] = GL_FALSE;
glGetShaderiv(shader, GL_COMPILE_STATUS, isCompiled);
if(isCompiled[0] == GL_FALSE) {
String log = glGetShaderInfoLog(shader);
glDeleteShader(shader);
throw new RuntimeException(shaderSourceFilePath + "\nError occurred compiling shader:\n" + log);
}
return shader;
}
}
|
package org.javarosa.services.transport;
import java.io.IOException;
import java.util.Date;
import java.util.Vector;
import org.javarosa.core.services.Logger;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.services.transport.impl.TransportException;
import org.javarosa.services.transport.impl.TransportMessageStatus;
import org.javarosa.services.transport.impl.TransportMessageStore;
import org.javarosa.services.transport.senders.SenderThread;
import org.javarosa.services.transport.senders.SimpleSenderThread;
import org.javarosa.services.transport.senders.TransporterSharingSender;
/**
* The TransportService is generic. Its capabilities are extended by defining
* new kinds of Transport.
*
* To define a new kind of transport, it is necessary to implement two
* interfaces:
* <ol>
* <li>TransportMessage - a new kind of message
* <li>Transporter - an object with the ability to send one of the new messages
* </ol>
*
* A TransportMessage must be able to create an appropriate Transporter (via the
* <code>createTransporter()</code> method) whose constructor takes the message
* itself.
*
* The result is an intuitive programmer interface which involves the following
* steps alone:
* <ol>
* <li>create a Message
* <li>ask the TransportService to send the Message
* </ol>
*
* For example:
*
* <code>
* TransportMessage m = new SomeTransportMessage()
* TransportService.send(m);
* </code>
*
*/
public class TransportService {
/**
*
* The TransportService has a cache, in which all messages to be sent are
* persisted immediately
*
*/
private static TransportMessageStore T_CACHE;
private static TransporterSharingSender SENDER;
private static final String CACHE_LOCK="CACHE_LOCK";
public static final int PAYLOAD_SIZE_REPORTING_THRESHOLD = 15000;
private static TransportMessageStore CACHE() {
synchronized(CACHE_LOCK) {
if(T_CACHE == null) {
T_CACHE = new TransportMessageStore();
}
return T_CACHE;
}
}
public static synchronized void init() {
CACHE();
SENDER = new TransporterSharingSender();
}
public static void reinit() {
synchronized(CACHE_LOCK) {
T_CACHE = new TransportMessageStore();
}
}
/**
*
* Send a message in a thread, using the default number of tries and the
* default pause between tries
*
* Sending a message happens like this:
*
* <ol>
* <li>The message creates an appropriate Transporter (which contains the
* message)
* <li>The message is given a SenderDeadline, equal to the maximum time it
* can spend in a SenderThread
* <li>The message is persisted in the cache
* <li>A SenderThread is started, which tries and retries the Transporter's
* send method until either the specified number of tries are exhausted, or
* the message is successfully sent
* <li>The SenderThread is returned
* </ol>
*
* @param message
* @return Thread used to try to send message
* @throws IOException
*/
public static SenderThread send(TransportMessage message)
throws TransportException {
return send(message, SenderThread.DEFAULT_TRIES,
SenderThread.DEFAULT_DELAY);
}
/**
*
* Send a message, specifying a number of tries and the pause between the
* tries (in seconds)
*
*
* @param message
* @param tries
* @param delay
* @return
* @throws IOException
*/
public static SenderThread send(TransportMessage message, int tries, int delay) throws TransportException {
boolean sendLater = (tries == 0);
// if the message should be stored and never lost
if (message.isCacheable()) {
// record the deadline for the sending thread phase in the message
message.setSendingThreadDeadline(getSendingThreadDeadline(tries, delay));
synchronized (CACHE()) {
// persist the message
CACHE().cache(message);
if (sendLater) {
Logger.log("send", "msg cached " + message.getTag() + "; " + CACHE().getCachedMessagesCount() + " in queue");
}
}
} else {
message.setStatus(TransportMessageStatus.QUEUED);
}
if (sendLater) {
return null;
} else {
// create a sender thread
SenderThread thread = new SimpleSenderThread(message, CACHE(), tries, delay);
// start the sender thread
Logger.log("send", "start " + message.getTag());
thread.start();
// return the sender thread in case
// an application wants to permit the user to cancel it
return thread;
}
}
/**
* @param message
* @return
* @throws TransportException
*/
public static TransportMessage sendBlocking(TransportMessage message)
throws TransportException {
// if the message should be saved in case of sending failure
if (message.isCacheable()) {
// persist the message
CACHE().cache(message);
}
message.send();
// if the message had been cached..
if (message.isCacheable()) {
if (message.getStatus() == TransportMessageStatus.SENT) {
// if it was sent successfully, then remove it from cache
CACHE().decache(message);
} else {
// otherwise, set the status to cached
message.setStatus(TransportMessageStatus.CACHED);
CACHE().updateMessage(message);
}
}
return message;
}
/**
*
* Any messages which aren't successfully sent in SendingThreads are then
* "Cached".
*
* Applications can activate new attempts to send the CachedMessages via
* this sendCached method
*
*
*/
public static void sendCached(TransportListener listener) throws TransportException {
if(SENDER == null) {
//This is very bad, and the service should have been initialized
SENDER = new TransporterSharingSender();
}
//We get into a lot of trouble with synchronicity if we just let all kinds of
//senders start going at once, so we'll just use the one and queue up
//sendCached attempts.
synchronized(SENDER) {
// get all the cached messages
Vector messages = getCachedMessages();
Logger.log("send-all", "start; " + messages.size() + " msgs");
if (messages.size() > 0) {
SENDER.init(messages, CACHE(), listener);
SENDER.send();
}
}
}
/**
*
* Compute the lifetime of a sending thread with the given parameters and
* returns the time in the future at which this duration would have elapsed
*
* @param tries
* @param delay
* @return
*/
private static long getSendingThreadDeadline(int tries, int delay) {
long duration = (new Long(tries).longValue()
* new Long(delay).longValue() * 1000);
long now = new Date().getTime();
return (now + duration);
}
/**
* @return
*/
public static Vector getCachedMessages() {
return CACHE().getCachedMessages();
}
/**
* @return
*/
public static int getCachedMessagesSize() {
return CACHE().getCachedMessagesCount();
}
/**
*
* A TransportMessage is assigned a uniqueId when persisted. Applications
* can access the message again via this method
*
* @param id
* The unique id assigned to the TransportMessage when it was
* queued for sending
* @return The TransportMessage identified by the id (or null if no such
* message was found)
*/
public static TransportMessage retrieve(String id) {
return CACHE().findMessage(id);
}
public static void halt() {
if(SENDER != null) {
SENDER.halt();
}
}
}
|
package cz.muni.fi.jboss.migration.utils;
import cz.muni.fi.jboss.migration.Configuration;
import cz.muni.fi.jboss.migration.RollbackData;
import cz.muni.fi.jboss.migration.ex.CliScriptException;
import cz.muni.fi.jboss.migration.ex.CopyException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class Utils {
/**
* Method for testing if given string is null or empty and if it is then CliScriptException is thrown with given message
*
* @param string string for testing
* @param errMsg message for exception
* @param name name of property of tested value
* @throws CliScriptException if tested string is empty or null
*/
public static void throwIfBlank(String string, String errMsg, String name) throws CliScriptException {
if ((string == null) || (string.isEmpty())) {
throw new CliScriptException(name + errMsg);
}
}
/**
* Helping method for copying files from AS5 to AS7. It checks if list is empty and if not then set HomePath and
* targetPath of object of RollbackData. Plus for driver it creates special path from module of the driver.
*
* @param rollData object representing files which should be copied
* @param list List of files found for this object of RollbackData
* @param targetPath path to AS7 home dir
* @throws cz.muni.fi.jboss.migration.ex.CopyException
* if no file was found and rolldata is not representing driver and if it is then if module of
* driver is null
*/
public static void setRollbackData(RollbackData rollData, List<File> list, String targetPath)
throws CopyException {
// TODO: What is list good for? It's not really used.
// Huh? TODO: This should be wereever list is created.
if( list.isEmpty() ) {
throw new CopyException("Cannot locate file: " + rollData.getName());
}
rollData.setHomePath(list.get(0).getAbsolutePath());
switch( rollData.getType() ){
case LOG: rollData.setTargetPath( Utils.createPath(targetPath, "standalone", "log").getPath() );
break;
case RESOURCE: rollData.setTargetPath(Utils.createPath(targetPath, "standalone", "deployments").getPath());
break;
case SECURITY: rollData.setTargetPath(Utils.createPath(targetPath, "standalone", "configuration").getPath());
break;
case DRIVER: case LOGMODULE:{
rollData.setName(list.get(0).getName());
String module;
if( rollData.getModule() == null)
throw new CopyException("Module is null!");
String[] parts = rollData.getModule().split("\\.");
module = "";
for (String s : parts) {
module = module + s + File.separator;
}
// TODO: Configurable modules dir.
rollData.setTargetPath(targetPath + File.separator + "modules" + File.separator +
module + "main");
} break;
}// switch( rollData.type )
}// setRollbackData()
/**
* Helping method for writing help.
*/
public static void writeHelp() {
System.out.println();
System.out.println(" Usage:");
System.out.println();
System.out.println(" java -jar AsMigrator.jar [<option>, ...] [as5.dir=]<as5.dir> [as7.dir=]<as7.dir>");
System.out.println();
System.out.println(" Options:");
System.out.println();
System.out.println(" as5.profile=<name>");
System.out.println(" Path to AS 5 profile.");
System.out.println(" Default: \"default\"");
System.out.println();
System.out.println(" as7.confPath=<path> ");
System.out.println(" Path to AS 7 config file.");
System.out.println(" Default: \"standalone/configuration/standalone.xml\"");
System.out.println();
System.out.println(" conf.<module>.<property>=<value> := Module-specific options.");
System.out.println(" <module> := Name of one of modules. E.g. datasource, jaas, security, ...");
System.out.println(" <property> := Name of the property to set. Specific per module. " +
"May occur multiple times.");
System.out.println();
}
/**
* Method for removing copied data for migration from AS5 if the app fails. All rollbackData have set path to copied
* files in AS7. So tthis method iterate over collection of these objects and try to delete them.
*
* @param rollbackDatas files, which where copied to AS7 folder
*/
public static void removeData(Collection<RollbackData> rollbackDatas) {
for (RollbackData rolldata : rollbackDatas) {
if (!(rolldata.getType().equals(RollbackData.Type.DRIVER))) {
FileUtils.deleteQuietly(new File(rolldata.getTargetPath() + File.separator + rolldata.getName()));
}
}
}
/**
* Method for returning standalone file to its original state before migration if the app fails.
*
* @param doc object of Document representing original standalone file. This file is saved in Main before migration.
* @param config configuration of app
*/
public static void cleanStandalone(Document doc, Configuration config) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new File(config.getGlobal().getAs7ConfigFilePath()));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
}
/**
* Utils class for finding name of jar file containing class from logging configuration.
*
* @param className name of the class which must be found
* @param dirAS5 AS5 home dir
* @param profileAS5 name of AS5 profile
* @return name of jar file which contains given class
* @throws FileNotFoundException if the jar file is not found
*/
public static String findJarFileWithClass(String className, String dirAS5, String profileAS5) throws FileNotFoundException{
JarFile jarFile = null;
try {
// jar file can be in two different places in AS5 structure.
for(int i = 0; i < 2; i++){
File dir;
if( i == 0){
// First look for jar file in lib directory in given AS5 profile
dir = new File(dirAS5 + File.separator + "server" + File.separator +
profileAS5 + File.separator + "lib");
} else{
// If not found in profile's lib directory then try common/lib folder (common jars for all profiles)
dir = new File(dirAS5 + File.separator + "common" + File.separator + "lib");
}
SuffixFileFilter sf = new SuffixFileFilter(".jar");
List<File> list = (List<File>) FileUtils.listFiles(dir, sf, FileFilterUtils.makeCVSAware(null));
className = className.replace(".", "/");
for (File file : list) {
jarFile = new JarFile(file);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if ((entry.getName().contains(className)) && !(entry.isDirectory())) {
// Assuming that jar file contains some package with class (common Java practice)
return StringUtils.substringAfterLast(file.getPath(), "/");
}
}
}
}
} catch (IOException e) {
throw new FileNotFoundException(e.toString());
}
throw new FileNotFoundException("Cannot find jar file which contains class: " + className);
}
/**
* Searching for file, which is represented as RollbackData in the application, in given directory
*
* @param rollData object representing file for search
* @param dir directory for searching
* @return list of found files
*/
public static List<File> searchForFile(RollbackData rollData, File dir) {
NameFileFilter nff;
if (rollData.getType().equals(RollbackData.Type.DRIVER)) {
final String name = rollData.getName();
nff = new NameFileFilter(name) {
@Override
public boolean accept(File file) {
return file.getName().contains(name) && file.getName().contains("jar");
}
};
} else {
nff = new NameFileFilter(rollData.getName());
}
List<File> list = (List<File>) FileUtils.listFiles(dir, nff, FileFilterUtils.makeCVSAware(null));
// One more search for driver jar. Other types of rollbackData just return list.
if(rollData.getType().equals(RollbackData.Type.DRIVER)) {
// For now only expecting one jar for driver. Pick the first one.
if (list.isEmpty()) {
// Special case for freeware jdbc driver jdts.jar
if (rollData.getAltName() != null) {
final String altName = rollData.getAltName();
nff = new NameFileFilter(altName) {
@Override
public boolean accept(File file) {
return file.getName().contains(altName) && file.getName().contains("jar");
}
};
List<File> altList = (List<File>) FileUtils.listFiles(dir, nff,
FileFilterUtils.makeCVSAware(null));
return altList;
}
}
}
return list;
}
/**
* Builds up a File object with path consisting of given components.
*/
public static File createPath( String parent, String child, String ... more) {
File file = new File(parent, child);
for( String component : more ) {
file = new File(file, component);
}
return file;
}
}// class
|
package de.hwrberlin.it2014.sweproject.cbr;
import de.hwrberlin.it2014.sweproject.cbr.Request;
import de.hwrberlin.it2014.sweproject.database.DatabaseConfig;
import de.hwrberlin.it2014.sweproject.database.DatabaseConnection;
import de.hwrberlin.it2014.sweproject.database.TableResultsSQL;
import de.hwrberlin.it2014.sweproject.model.Result;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* controls the cbr-cycle. Start the algorithm with startCBR(ArrayList<String>) method.
*
* @author Max Bock & Felix Lehmann
*
*/
public class CBR {
//private ArrayList<Case> activeCases; //all cases from current userRequests
private int COUNT_TO_RETURN;
public CBR()
{
//activeCases = new ArrayList<Case>();
COUNT_TO_RETURN=30;
}
public CBR(int count)
{
//activeCases = new ArrayList<Case>();
COUNT_TO_RETURN=count;
}
/**
* leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck
* @author Max Bock
* @param usersInput (String[])
* @return aehnliche Faelle
*/
public ArrayList<Result> startCBR(String[] usersInput)
{
ArrayList<String> al = new ArrayList<>();
for(String s : usersInput){ al.add(s); }
return startCBR(al);
}
/**
* leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck
* @author Max Bock
* @param usersInput (String)
* @return aehnliche Faelle
*/
public ArrayList<Result> startCBR(String usersInput)
{
String[] ar = usersInput.split(" ");
return startCBR(ar);
}
/**
* leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck
* @author Max Bock
* @param usersInput (ArrayList<String>)
* @return aehnliche Faelle
*/
public ArrayList<Result> startCBR(ArrayList<String> usersInput)
{
ArrayList<Result> resList;
try {
Request rq = new Request(usersInput);
resList=rq.getSimilarFromDB(COUNT_TO_RETURN);
} catch (SQLException e) {
resList=new ArrayList<>();
e.printStackTrace();
}
return resList;
}
/**
* speichert die Bewertung zu einem Fall einer Anfrage
* @param id der Anfrage
* @param evaluation Bewertung
* @return
* @throws SQLException
*/
public String saveUserRating(int idOfResult, float rating) throws SQLException
{
//Request r = new Request();
String query = TableResultsSQL.getSelectSQLCode(idOfResult);
DatabaseConnection dbc=new DatabaseConnection();
dbc.connectToMysql(DatabaseConfig.DB_HOST, DatabaseConfig.DB_NAME,
DatabaseConfig.DB_USER, DatabaseConfig.DB_PASSWORD);
ResultSet rs = dbc.executeQuery(query);
ArrayList<Result> rl = dbc.convertResultSetToResultList(rs);
Result result = rl.get(0);
result.setUserRating(rating);
//TableResultsSQL.getUpdateSQLCodeForUserRating(r);
return null;
}
/**
* lscht alle Flle aus den active Cases (sind eigentlich die Nutzeranfragen!), die lter als der Parameter(miliseconds) sind
* sollte regelmig benutzt werden, damit nicht komplett bewertete Anfragen gelscht werden
* miliseconds <= 1 lscht alle Flle
* @author Max Bock
* @param miliseconds
* @return count of deleted cases(/requests)
*
public int removeOldCases(long miliseconds)
{
int count = 0;
if(1>=miliseconds)
{
count=activeCases.size();
activeCases.clear();
}
else
{
Date current = new Date();
Date before = new Date(current.getTime()-miliseconds);
for(Case c : activeCases)
{
if(c.getDateOfRequest().before(before))
{
removeCaseByID(c.getID());
count++;
}
}
}
return count;
}*/
}
|
package de.jformchecker.elements;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.coverity.security.Escape;
import de.jformchecker.AttributeUtils;
import de.jformchecker.Criterion;
import de.jformchecker.FormChecker;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.StringUtils;
import de.jformchecker.TagAttributes;
import de.jformchecker.criteria.MaxLength;
import de.jformchecker.criteria.ValidationResult;
import de.jformchecker.request.Request;
import de.jformchecker.validator.Validator;
/**
* Parent Element for all Formchecker elements Common stuff like validation...
*
* @author jochen
*
*/
public abstract class AbstractInput <T extends FormCheckerElement> implements FormCheckerElement {
protected String name;
protected String value;
protected String desc;
protected String preSetValue = "";
protected int size = -1;
private List<Criterion> criteria = new ArrayList<>();
boolean required;
private int tabIndex;
ValidationResult validationResult;
public ValidationResult getValidationResult() {
return validationResult;
}
public void setValidationResult(ValidationResult validationResult) {
this.validationResult = validationResult;
valid = validationResult.isValid();
}
boolean valid = true;
FormChecker parent;
String helpText;
// builds attribs, elementId, TabIndex
protected String buildAllAttributes(Map<String, String> attributes) {
StringBuilder allAttribs = new StringBuilder();
allAttribs.append(AttributeUtils.buildAttributes(attributes));
allAttribs.append(getElementId());
allAttribs.append(getTabIndexTag());
allAttribs.append(buildRequiredAttribute());
allAttribs.append(buildSizeAttribute());
// help-text
if (!StringUtils.isEmpty(helpText)) {
allAttribs.append(
AttributeUtils.buildAttributes(new TagAttributes("aria-describedby", FormChecker.getHelpBlockId(this))));
}
return allAttribs.toString();
}
public void addCriteria(Criterion c) {
criteria.add(c);
}
private Object buildSizeAttribute() {
if (size != -1) {
return AttributeUtils.buildSingleAttribute("size", Integer.toString(size));
}
return "";
}
protected String buildRequiredAttribute() {
if (required) {
return " required ";
} else {
return "";
}
}
public String getInputTag() {
return getInputTag(new HashMap<>());
}
// return highest tabindex of this element
public int getLastTabIndex() {
return tabIndex;
}
@Override
public void setFormChecker(FormChecker fc) {
parent = fc;
}
public String getValueHtmlEncoded() {
return Escape.html(value);
}
public void setInvalid() {
valid = false;
}
@Override
public void init(Request request, boolean firstRun, Validator validator) {
if (firstRun) {
this.setValue(this.getPreSetValue());
} else {
this.setValue(request.getParameter(this.getName()));
this.setValidationResult(validator.validate(this));
}
}
public T setRequired() {
this.required = true;
return (T) this;
}
@Override
public String getLabel() {
Map<String, String> map = new LinkedHashMap<>();
return parent.getLabelForElement(this, map);
}
@Override
public String getPreSetValue() {
return preSetValue;
}
@Override
public T setPreSetValue(String preSetValue) {
this.preSetValue = preSetValue;
this.value = preSetValue;
return (T) this;
}
@Override
public String getCompleteInput() {
return getLabel() + getInputTag();
}
// builds the maxlen attribute
public String buildMaxLen() {
List<Criterion> criteria = this.getCriteria();
if (criteria != null) {
for (Criterion criterion : criteria) {
if (criterion instanceof MaxLength) {
return AttributeUtils.buildSingleAttribute("maxlength", "" + ((MaxLength) criterion).getMaxLength());
}
}
}
return "";
}
@Override
public String getName() {
return name;
}
@Override
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public T setDescription(String desc) {
this.desc = desc;
return (T) this;
}
@Override
public void changeDescription(String desc) {
this.desc = desc;
}
@Override
public String getDescription() {
return desc;
}
@Override
public boolean isValid() {
return valid;
}
public T setCriterias(Criterion... criteria) {
this.criteria.addAll(Arrays.asList(criteria));
return (T) this;
}
public boolean isRequired() {
return required;
}
protected String getElementId() {
return AttributeUtils.buildSingleAttribute("id", "form_" + name);
}
public int getTabIndex() {
return tabIndex;
}
public String getTabIndexTag() {
return AttributeUtils.buildSingleAttribute("tabindex", "" + getTabIndex());
}
public String getTabIndexTagIncreaseBy(int addition) {
return AttributeUtils.buildSingleAttribute("tabindex", "" + (getTabIndex() + addition));
}
public T setTabIndex(int tabIndex) {
this.tabIndex = tabIndex;
return (T) this;
}
public List<Criterion> getCriteria() {
return criteria;
}
public String getHelpText() {
return helpText;
}
public T setHelpText(String helpText) {
this.helpText = helpText;
return (T) this;
}
public T setSize(int size) {
this.size = size;
return (T) this;
}
public void setName(String name) {
this.name = name;
}
}
|
package editor.gui.generic;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
/**
* This class is a listener for double clicks on the title of a component with a titled
* border. When the title is double-clicked, a text field is overlaid over it that allows
* the user to change the title of the border, or perform any other action.
*
* @author Alec Roelke
*/
public class ChangeTitleListener extends MouseAdapter
{
/**
* Component that has the border to watch.
*/
private JComponent component;
/**
* Border whose title is to be watched and edited.
*/
private TitledBorder titledBorder;
/**
* Popup containing the text field that is overlaid over the border.
*/
private JPopupMenu editPopup;
/**
* Text field containing the changes to the title.
*/
private JTextField editTextField;
/**
* Create a new ChangeTitleListener that watches for a double-click on the title
* of the border of <code>c</code> and performs the given action when the title
* is changed this way.
*
* @param c component containing the border to watch
* @param change action to perform when the title is changed
*/
public ChangeTitleListener(JComponent c, Consumer<String> change)
{
super();
component = c;
if (component.getBorder() instanceof TitledBorder)
titledBorder = (TitledBorder)component.getBorder();
else
throw new IllegalArgumentException("component must have a titled border");
editTextField = new JTextField();
// Accept entry when enter is pressed
editTextField.addActionListener((e) -> {
String value = editTextField.getText();
change.accept(value);
editPopup.setVisible(false);
editPopup.getInvoker().revalidate();
editPopup.getInvoker().repaint();
});
// Throw away entry when ESC is pressed
editTextField.registerKeyboardAction(
(e) -> editPopup.setVisible(false),
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_FOCUSED
);
// Implicitly throw away entry when something else is clicked
editPopup = new JPopupMenu();
editPopup.setBorder(new EmptyBorder(0, 0, 0, 0));
editPopup.add(editTextField);
}
@Override
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
FontMetrics fm = component.getFontMetrics(titledBorder.getTitleFont());
int titleWidth = fm.stringWidth(titledBorder.getTitle()) + 20;
if (new Rectangle(0, 0, titleWidth, fm.getHeight()).contains(e.getPoint()))
{
editTextField.setText(titledBorder.getTitle());
Dimension d = editTextField.getPreferredSize();
d.width = titleWidth;
editPopup.setPreferredSize(d);
editPopup.show(component, 0, 0);
editTextField.selectAll();
editTextField.requestFocusInWindow();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.