text
stringlengths 7
1.01M
|
|---|
package com.pthanalyzer.tabs;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
public class TabLayout {
private Composite parent;
public TabLayout(Composite parent) {
this.parent = parent;
TabFolder tabFolder = new TabFolder(this.parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
PTHTab[] tabs = new PTHTab[] {
new GeneralPTHTab(),
new HandsPTHTab(),
new PlayersPTHTab()
};
for (PTHTab tab : tabs) {
TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
tabItem.setText(tab.getName());
tabItem.setControl(tab.createControl(tabFolder));
}
tabFolder.layout(true, true);
this.parent.layout(true, true);
}
}
|
package seedu.canoe.commons.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Writes and reads files
*/
public class FileUtil {
private static final String CHARSET = "UTF-8";
public static boolean isFileExists(Path file) {
return Files.exists(file) && Files.isRegularFile(file);
}
/**
* Returns true if {@code path} can be converted into a {@code Path} via {@link Paths#get(String)},
* otherwise returns false.
* @param path A string representing the file path. Cannot be null.
*/
public static boolean isValidPath(String path) {
try {
Paths.get(path);
} catch (InvalidPathException ipe) {
return false;
}
return true;
}
/**
* Creates a file if it does not exist along with its missing parent directories.
* @throws IOException if the file or directory cannot be created.
*/
public static void createIfMissing(Path file) throws IOException {
if (!isFileExists(file)) {
createFile(file);
}
}
/**
* Creates a file if it does not exist along with its missing parent directories.
*/
public static void createFile(Path file) throws IOException {
if (Files.exists(file)) {
return;
}
createParentDirsOfFile(file);
Files.createFile(file);
}
/**
* Creates parent directories of file if it has a parent directory
*/
public static void createParentDirsOfFile(Path file) throws IOException {
Path parentDir = file.getParent();
if (parentDir != null) {
Files.createDirectories(parentDir);
}
}
/**
* Assumes file exists
*/
public static String readFromFile(Path file) throws IOException {
return new String(Files.readAllBytes(file), CHARSET);
}
/**
* Writes given string to a file.
* Will create the file if it does not exist yet.
*/
public static void writeToFile(Path file, String content) throws IOException {
Files.write(file, content.getBytes(CHARSET));
}
}
|
/*
Copyright 2009-2019 Igor Polevoy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.javalite.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.javalite.common.Collections.map;
/**
* Convenience class to convert JSON strings to and from objects.
*
* @author Igor Polevoy on 5/26/16.
*/
public class JSONHelper {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
/**
* Convert a JSON map to a Java Map
*
* @param json JSON map
* @return Java Map.
*/
public static Map toMap(String json) {
try {
return mapper.readValue(json, Map.class);
} catch (Exception e) {
throw new JSONParseException("Failed to parse JSON string into a Java Map",e);
}
}
/**
* Convenience method to convert String to {@link JSONMap}.
*
* @param json String content of some JSON object.
* @return instance of {@link JSONMap}.
*/
public static JSONMap toJSONMap(String json) {
return new JSONMap(toMap(json));
}
/**
* Convenience method to convert String to {@link JSONList}.
*
* @param json String content of some JSON array.
* @return instance of {@link JSONList}.
*/
public static JSONList toJSONList(String json) {
return new JSONList(toList(json));
}
/**
* Convert JSON Array to Java array of maps.
*
* @param json JSON array
* @return Java array.
*/
public static Map[] toMaps(String json) {
try {
return mapper.readValue(json, Map[].class);
} catch (Exception e) {
throw new JSONParseException("Failed to parse JSON string into a Java Maps",e);
}
}
/**
* Convert Java object to a JSON string.
*
* @param val Java object
* @return JSON string.
*/
public static String toJsonString(Object val) {
return toJsonString(val, false);
}
/**
* Generates a JSON object from names and values. Example: this code:
*
* <pre>
*
* String person = toJsonString("first_name", "Marilyn", "last_name", "Monroe");
* </pre>
*
* will generate this JSON string:
*
* <pre>
*
* {
* "first_name": "Marilyn",
* "last_name": "Monroe"
* }
* </pre>
* @param namesAndValues is a list of name and value pairs in a typical JavaLite fashion.
* @return JSON object with name and values passed in.
*/
public static String toJsonString(Object ...namesAndValues) {
return toJsonString(map(namesAndValues), false);
}
/**
* Generates a JSON object from names and values. Example: this code:
*
* <pre>
*
* String person = toJsonString("first_name", "Marilyn", "last_name", "Monroe");
* </pre>
*
* will generate this JSON string:
*
* <pre>
*
* {
* "first_name": "Marilyn",
* "last_name": "Monroe"
* }
* </pre>
*
* <strong>This method is a synonym for {@link #toJsonString(Object...)}.</strong>
*
* @param namesAndValues is a list of name and value pairs in a typical JavaLite fashion.
* @return JSON object with name and values passed in
*/
public static String toJson(Object ...namesAndValues) {
return toJsonString(map(namesAndValues), false);
}
/**
* Convert Java object to a JSON string.
*
* @param val Java object
* @param pretty enable/disable pretty print
* @return JSON string.
*/
public static String toJsonString(Object val, boolean pretty) {
try {
return pretty ? mapper.writerWithDefaultPrettyPrinter().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(val) : mapper.writeValueAsString(val);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Converts input into a JSON object.
*
* @param namesAndValues - expected sequence of corresponding name and value pairs (number of parameters must be even ).
* @return new string {name:value,name1:value1, etc.}
*/
public static String toJsonObject(Object... namesAndValues) {
if (namesAndValues.length % 2 != 0) {
throw new IllegalArgumentException("number or arguments must be even");
}
StringBuilder sb = new StringBuilder("{");
int count = 0;
while (true) {
Object name = namesAndValues[count];
sb.append("\"").append(name).append("\":");
if (!(namesAndValues[count + 1] instanceof Number)) {
if (namesAndValues[count + 1] == null) {
sb.append("null");
} else {
sb.append("\"").append(namesAndValues[count + 1].toString()).append("\"");
}
} else {
sb.append(namesAndValues[count + 1].toString());
}
if (count < (namesAndValues.length - 2)) {
sb.append(",");
count += 2;
} else {
sb.append("}");
break;
}
}
return sb.toString();
}
/**
* Convert JSON array tp Java List
*
* @param json JSON array string.
* @return Java List instance.
*/
public static List toList(String json) {
try {
return mapper.readValue(json, List.class);
} catch (Exception e) {
throw new JSONParseException("Failed to parse JSON string into a Java List",e);
}
}
/**
* Clean control characters in a string.
*
* @param value string to escape
* @return escaped version
*/
public static String cleanControlChars(String value) {
return sanitize(value, true);
}
/**
* Escapes control characters in a string.
*
* @param value string to escape
* @return escaped version
* @see #sanitize(String)
*/
public static String escapeControlChars(String value) {
return sanitize(value, false);
}
/**
* Escapes control characters in a string.
*
* @param value string to escape
* @return escaped version
* @see #escapeControlChars(String)
*/
public static String sanitize(String value) {
return sanitize(value, false);
}
public static String sanitize(String value, boolean clean) {
return sanitize(value, clean, null);
}
/**
* Escapes control characters in a string when you need to
* generate JSON.
*
* @param value input string
* @param clean if true will remove characters that match, if false will escape
* @param toEscape array of characters to escape. If not provided, it will escape or clean <code>'"','\\', '\t', '\b', '\n', '\r' '\f'</code>.
* This method will only escape or clean if provided chars are from this list.
* @return input string with control characters escaped or removed, depending on the <code>clean</code> flag.
*/
public static String sanitize(String value, boolean clean, Character... toEscape) {
StringBuilder builder = new StringBuilder();
Map<Character, String> replacements = clean ? CLEAN_CHARS : REPLACEMENT_CHARS;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (toEscape == null) {
if (replacements.containsKey(c)) {
builder.append(replacements.get(c));
} else {
builder.append(c);
}
} else {
if (replacements.containsKey(c) && contains(toEscape, c)) {
builder.append(replacements.get(c));
} else {
builder.append(c);
}
}
}
return builder.toString();
}
private static boolean contains(Character[] toEscape, char c) {
for (char escapeChar : toEscape) {
if (escapeChar == c) {
return true;
}
}
return false;
}
private static final Map<Character, String> REPLACEMENT_CHARS = new HashMap<>();
private static final Map<Character, String> CLEAN_CHARS = new HashMap<>();
static {
for (int i = 0; i <= 0x1f; i++) {
REPLACEMENT_CHARS.put((char) i, String.format("\\u%04x", (int) i));
}
REPLACEMENT_CHARS.put('\u2028', "\\u2028");
REPLACEMENT_CHARS.put('\u2029', "\\u2029");
REPLACEMENT_CHARS.put('"', "\\\"");
REPLACEMENT_CHARS.put('\\', "\\\\");
REPLACEMENT_CHARS.put('\t', "\\t");
REPLACEMENT_CHARS.put('\b', "\\b");
REPLACEMENT_CHARS.put('\n', "\\n");
REPLACEMENT_CHARS.put('\r', "\\r");
REPLACEMENT_CHARS.put('\f', "\\f");
for (int i = 0; i <= 0x1f; i++) {
CLEAN_CHARS.put((char) i, String.format("\\u%04x", (int) i));
}
CLEAN_CHARS.put('\u2028', "");
CLEAN_CHARS.put('\u2029', "");
CLEAN_CHARS.put('\\', "");
CLEAN_CHARS.put('\t', "");
CLEAN_CHARS.put('\b', "");
CLEAN_CHARS.put('\n', "");
CLEAN_CHARS.put('\r', "");
CLEAN_CHARS.put('\f', "");
}
}
|
/*
* Copyright (c) 2014. Heinz Max Kabutz , Sven Ruppert
* We licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rapidpm.demo.entwicklerpress.shortcut.proxies.chap2.c_2_2;
import javax.jws.WebService;
/**
* Created by Sven Ruppert on 22.09.2014.
*/
@WebService(endpointInterface = "org.rapidpm.demo.entwicklerpress.shortcut.proxies.chap2.c_2_2.Service")
public class ServiceImpl implements Service {
@Override
public String work(String txt) {
System.out.println("remote txt = " + txt);
return "ServiceImpl - " + txt;
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import org.junit.jupiter.api.Test;
import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.ClassReader;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.SpringAsmInfo;
import org.springframework.core.annotation.MergedAnnotation;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MergedAnnotationReadingVisitor}.
*
* @author Phillip Webb
*/
class MergedAnnotationMetadataVisitorTests {
private MergedAnnotation<?> annotation;
@Test
void visitWhenHasSimpleTypesCreatesAnnotation() {
loadFrom(WithSimpleTypesAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(SimpleTypesAnnotation.class);
assertThat(this.annotation.getValue("stringValue")).contains("string");
assertThat(this.annotation.getValue("byteValue")).contains((byte) 1);
assertThat(this.annotation.getValue("shortValue")).contains((short) 2);
assertThat(this.annotation.getValue("intValue")).contains(3);
assertThat(this.annotation.getValue("longValue")).contains(4L);
assertThat(this.annotation.getValue("booleanValue")).contains(true);
assertThat(this.annotation.getValue("charValue")).contains('c');
assertThat(this.annotation.getValue("doubleValue")).contains(5.0);
assertThat(this.annotation.getValue("floatValue")).contains(6.0f);
}
@Test
void visitWhenHasSimpleArrayTypesCreatesAnnotation() {
loadFrom(WithSimpleArrayTypesAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(SimpleArrayTypesAnnotation.class);
assertThat(this.annotation.getValue("stringValue")).contains(
new String[] { "string" });
assertThat(this.annotation.getValue("byteValue")).contains(new byte[] { 1 });
assertThat(this.annotation.getValue("shortValue")).contains(new short[] { 2 });
assertThat(this.annotation.getValue("intValue")).contains(new int[] { 3 });
assertThat(this.annotation.getValue("longValue")).contains(new long[] { 4 });
assertThat(this.annotation.getValue("booleanValue")).contains(
new boolean[] { true });
assertThat(this.annotation.getValue("charValue")).contains(new char[] { 'c' });
assertThat(this.annotation.getValue("doubleValue")).contains(
new double[] { 5.0 });
assertThat(this.annotation.getValue("floatValue")).contains(new float[] { 6.0f });
}
@Test
void visitWhenHasEmptySimpleArrayTypesCreatesAnnotation() {
loadFrom(WithSimpleEmptyArrayTypesAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(SimpleArrayTypesAnnotation.class);
assertThat(this.annotation.getValue("stringValue")).contains(new String[] {});
assertThat(this.annotation.getValue("byteValue")).contains(new byte[] {});
assertThat(this.annotation.getValue("shortValue")).contains(new short[] {});
assertThat(this.annotation.getValue("intValue")).contains(new int[] {});
assertThat(this.annotation.getValue("longValue")).contains(new long[] {});
assertThat(this.annotation.getValue("booleanValue")).contains(new boolean[] {});
assertThat(this.annotation.getValue("charValue")).contains(new char[] {});
assertThat(this.annotation.getValue("doubleValue")).contains(new double[] {});
assertThat(this.annotation.getValue("floatValue")).contains(new float[] {});
}
@Test
void visitWhenHasEnumAttributesCreatesAnnotation() {
loadFrom(WithEnumAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(EnumAnnotation.class);
assertThat(this.annotation.getValue("enumValue")).contains(ExampleEnum.ONE);
assertThat(this.annotation.getValue("enumArrayValue")).contains(
new ExampleEnum[] { ExampleEnum.ONE, ExampleEnum.TWO });
}
@Test
void visitWhenHasAnnotationAttributesCreatesAnnotation() {
loadFrom(WithAnnotationAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(AnnotationAnnotation.class);
MergedAnnotation<NestedAnnotation> value = this.annotation.getAnnotation(
"annotationValue", NestedAnnotation.class);
assertThat(value.isPresent()).isTrue();
assertThat(value.getString(MergedAnnotation.VALUE)).isEqualTo("a");
MergedAnnotation<NestedAnnotation>[] arrayValue = this.annotation.getAnnotationArray(
"annotationArrayValue", NestedAnnotation.class);
assertThat(arrayValue).hasSize(2);
assertThat(arrayValue[0].getString(MergedAnnotation.VALUE)).isEqualTo("b");
assertThat(arrayValue[1].getString(MergedAnnotation.VALUE)).isEqualTo("c");
}
@Test
void visitWhenHasClassAttributesCreatesAnnotation() {
loadFrom(WithClassAnnotation.class);
assertThat(this.annotation.getType()).isEqualTo(ClassAnnotation.class);
assertThat(this.annotation.getString("classValue")).isEqualTo(InputStream.class.getName());
assertThat(this.annotation.getClass("classValue")).isEqualTo(InputStream.class);
assertThat(this.annotation.getValue("classValue")).contains(InputStream.class);
assertThat(this.annotation.getStringArray("classArrayValue")).containsExactly(OutputStream.class.getName());
assertThat(this.annotation.getValue("classArrayValue")).contains(new Class<?>[] {OutputStream.class});
}
private void loadFrom(Class<?> type) {
ClassVisitor visitor = new ClassVisitor(SpringAsmInfo.ASM_VERSION) {
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return MergedAnnotationReadingVisitor.get(getClass().getClassLoader(),
null, descriptor, visible,
annotation -> MergedAnnotationMetadataVisitorTests.this.annotation = annotation);
}
};
try {
new ClassReader(type.getName()).accept(visitor, ClassReader.SKIP_DEBUG
| ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@SimpleTypesAnnotation(stringValue = "string", byteValue = 1, shortValue = 2, intValue = 3, longValue = 4, booleanValue = true, charValue = 'c', doubleValue = 5.0, floatValue = 6.0f)
static class WithSimpleTypesAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface SimpleTypesAnnotation {
String stringValue();
byte byteValue();
short shortValue();
int intValue();
long longValue();
boolean booleanValue();
char charValue();
double doubleValue();
float floatValue();
}
@SimpleArrayTypesAnnotation(stringValue = "string", byteValue = 1, shortValue = 2, intValue = 3, longValue = 4, booleanValue = true, charValue = 'c', doubleValue = 5.0, floatValue = 6.0f)
static class WithSimpleArrayTypesAnnotation {
}
@SimpleArrayTypesAnnotation(stringValue = {}, byteValue = {}, shortValue = {}, intValue = {}, longValue = {}, booleanValue = {}, charValue = {}, doubleValue = {}, floatValue = {})
static class WithSimpleEmptyArrayTypesAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface SimpleArrayTypesAnnotation {
String[] stringValue();
byte[] byteValue();
short[] shortValue();
int[] intValue();
long[] longValue();
boolean[] booleanValue();
char[] charValue();
double[] doubleValue();
float[] floatValue();
}
@EnumAnnotation(enumValue = ExampleEnum.ONE, enumArrayValue = { ExampleEnum.ONE,
ExampleEnum.TWO })
static class WithEnumAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface EnumAnnotation {
ExampleEnum enumValue();
ExampleEnum[] enumArrayValue();
}
enum ExampleEnum {
ONE, TWO, THREE
}
@AnnotationAnnotation(annotationValue = @NestedAnnotation("a"), annotationArrayValue = {
@NestedAnnotation("b"), @NestedAnnotation("c") })
static class WithAnnotationAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationAnnotation {
NestedAnnotation annotationValue();
NestedAnnotation[] annotationArrayValue();
}
@Retention(RetentionPolicy.RUNTIME)
@interface NestedAnnotation {
String value() default "";
}
@ClassAnnotation(classValue = InputStream.class, classArrayValue = OutputStream.class)
static class WithClassAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface ClassAnnotation {
Class<?> classValue();
Class<?>[] classArrayValue();
}
}
|
package org.coreasm.compiler.plugins.io;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.coreasm.compiler.CodeType;
import org.coreasm.compiler.CompilerEngine;
import org.coreasm.compiler.codefragment.CodeFragment;
import org.coreasm.compiler.components.classlibrary.ClassLibrary;
import org.coreasm.compiler.components.classlibrary.JarIncludeHelper;
import org.coreasm.compiler.components.classlibrary.LibraryEntryType;
import org.coreasm.compiler.components.mainprogram.EntryType;
import org.coreasm.compiler.components.mainprogram.MainFileEntry;
import org.coreasm.compiler.components.mainprogram.statemachine.EngineTransition;
import org.coreasm.compiler.exception.CompilerException;
import org.coreasm.compiler.exception.EntryAlreadyExistsException;
import org.coreasm.compiler.interfaces.CompilerCodePlugin;
import org.coreasm.compiler.interfaces.CompilerExtensionPointPlugin;
import org.coreasm.compiler.interfaces.CompilerInitCodePlugin;
import org.coreasm.compiler.interfaces.CompilerPlugin;
import org.coreasm.compiler.interfaces.CompilerVocabularyExtender;
import org.coreasm.compiler.plugins.io.code.ucode.PrintRuleHandler;
import org.coreasm.engine.plugin.Plugin;
/**
* Provides IO methods.
* The current version does not allow for a lot of customization in
* terms of which channels are used.
* Future versions should optimize this.
* @author Spellmaker
*
*/
public class CompilerIOPlugin extends CompilerCodePlugin implements CompilerPlugin, CompilerVocabularyExtender, CompilerExtensionPointPlugin, CompilerInitCodePlugin{
private Plugin interpreterPlugin;
/**
* Constructs a new plugin
* @param parent The interpreter version
*/
public CompilerIOPlugin(Plugin parent){
this.interpreterPlugin = parent;
}
@Override
public Plugin getInterpreterPlugin(){
return interpreterPlugin;
}
@Override
public String getName() {
return "IOPlugin";
}
@Override
public List<MainFileEntry> loadClasses(ClassLibrary classLibrary) throws CompilerException {
File enginePath = engine.getOptions().enginePath;
List<MainFileEntry> result = new ArrayList<MainFileEntry>();
if(enginePath == null){
engine.getLogger().error(getClass(), "loading classes from a directory is currently not supported");
throw new CompilerException("could not load classes");
}
else{
try {
//classLibrary.addPackageReplacement("org.coreasm.engine.plugins.string.StringElement", "plugins.StringPlugin.StringElement");
//add package replacements for classes accessible for other plugins
classLibrary.addPackageReplacement("org.coreasm.engine.plugins.io.InputProvider", engine.getPath().getEntryName(LibraryEntryType.STATIC, "InputProvider", "IOPlugin"));
classLibrary.addPackageReplacement("org.coreasm.compiler.plugins.io.include.IOPlugin", engine.getPath().getEntryName(LibraryEntryType.STATIC, "IOPlugin", "IOPlugin"));
result = (new JarIncludeHelper(engine, this)).
includeStatic("org/coreasm/engine/plugins/io/OutputFunctionElement.java", EntryType.FUNCTION, "output").
includeStatic("org/coreasm/compiler/plugins/io/include/InputFunctionElement.java", EntryType.FUNCTION, "input").
includeStatic("org/coreasm/engine/plugins/io/InputProvider.java", EntryType.INCLUDEONLY).
includeStatic("org/coreasm/compiler/plugins/io/include/IOPlugin.java", EntryType.INCLUDEONLY).
includeStatic("org/coreasm/compiler/plugins/io/include/IOAggregator.java", EntryType.AGGREGATOR).build();
} catch (EntryAlreadyExistsException e) {
throw new CompilerException(e);
}
}
return result;
}
@Override
public List<EngineTransition> getTransitions() {
List<EngineTransition> result = new ArrayList<EngineTransition>();
CodeFragment c = new CodeFragment("");
String stringelement = engine.getPath().getEntryName(LibraryEntryType.STATIC, "StringElement", "StringPlugin");
c.appendLine("try{\n@decl(CompilerRuntime.FunctionElement,outputFunction) = @RuntimeProvider@.getStorage().getFunction(\"output\");\n@decl(String,msgs) = @outputFunction@.getValue(new java.util.ArrayList<@RuntimePkg@.Element>()).toString();\n");
c.appendLine("outputStream.print(@msgs@);\n");
c.appendLine("@RuntimeProvider@.getStorage().setValue(new @RuntimePkg@.Location(\"output\", new java.util.ArrayList<@RuntimePkg@.Element>()), new " + stringelement + "(\"\"));\n");
c.appendLine("}\ncatch(@decl(Exception,e)){\n}\n");
EngineTransition et = new EngineTransition(c, "emAggregation", "emStepSucceeded");
result.add(et);
return result;
}
@Override
public CodeFragment getInitCode() {
CodeFragment result = new CodeFragment("");
result.appendLine("java.io.PrintStream outputStream = System.out;\n");
return result;
}
@Override
public void registerCodeHandlers() throws CompilerException {
register(new PrintRuleHandler(), CodeType.U, "Rule", "PrintRule", null);
}
@Override
public void init(CompilerEngine engine) {
this.engine = engine;
}
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.doris.rewrite.mvrewrite;
import org.apache.doris.analysis.Analyzer;
import org.apache.doris.analysis.CreateMaterializedViewStmt;
import org.apache.doris.analysis.Expr;
import org.apache.doris.analysis.FunctionCallExpr;
import org.apache.doris.analysis.SlotRef;
import org.apache.doris.analysis.TableName;
import org.apache.doris.catalog.AggregateType;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.FunctionSet;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.Table;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.rewrite.ExprRewriteRule;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
/**
* For duplicate table, the count distinct(k1) could be rewritten to bitmap_union_count(mv_to_bitmap_k1) when bitmap
* mv exists.
* For example:
* Table: (k1 int, k2 int)
* MV: (k1 int, mv_bitmap_union_k2 bitmap bitmap_union)
* mv_to_bitmap_k2 = to_bitmap(k2)
* Query: select k1, count(distinct k2) from table group by k1
* Rewritten query: select k1, bitmap_union_count(mv_to_bitmap_k2) from table group by k1
*/
public class CountDistinctToBitmap implements ExprRewriteRule {
public static final ExprRewriteRule INSTANCE = new CountDistinctToBitmap();
@Override
public Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException {
// meet condition
if (!(expr instanceof FunctionCallExpr)) {
return expr;
}
FunctionCallExpr fnExpr = (FunctionCallExpr) expr;
if (!fnExpr.getParams().isDistinct()) {
return expr;
}
if (!fnExpr.getFnName().getFunction().equalsIgnoreCase(FunctionSet.COUNT)) {
return expr;
}
if (fnExpr.getChildren().size() != 1 || !(fnExpr.getChild(0) instanceof SlotRef)) {
return expr;
}
SlotRef fnChild0 = (SlotRef) fnExpr.getChild(0);
Column column = fnChild0.getColumn();
Table table = fnChild0.getTable();
if (column == null || table == null || !(table instanceof OlapTable)) {
return expr;
}
OlapTable olapTable = (OlapTable) table;
// check column
String queryColumnName = column.getName();
String mvColumnName = CreateMaterializedViewStmt
.mvColumnBuilder(AggregateType.BITMAP_UNION.name().toLowerCase(), queryColumnName);
Column mvColumn = olapTable.getVisibleColumn(mvColumnName);
if (mvColumn == null) {
return expr;
}
// rewrite expr
return rewriteExpr(fnChild0, mvColumn, analyzer);
}
private Expr rewriteExpr(SlotRef queryColumnSlotRef, Column mvColumn, Analyzer analyzer) {
Preconditions.checkNotNull(mvColumn);
Preconditions.checkNotNull(queryColumnSlotRef);
TableName tableName = queryColumnSlotRef.getTableName();
Preconditions.checkNotNull(tableName);
SlotRef mvSlotRef = new SlotRef(tableName, mvColumn.getName());
List<Expr> newFnParams = Lists.newArrayList();
newFnParams.add(mvSlotRef);
FunctionCallExpr result = new FunctionCallExpr("bitmap_union_count", newFnParams);
result.analyzeNoThrow(analyzer);
return result;
}
}
|
package com.dev.shreyansh.cargocontroller;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dev.shreyansh.cargocontroller", appContext.getPackageName());
}
}
|
/*
* © Crown Copyright 2013
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.nhs.hdn.common;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public final class UUIDHelper
{
@SuppressWarnings({"NumericCastThatLosesPrecision", "MagicNumber"})
@NotNull
public static byte[] uuidToByteArray(@NotNull final UUID uuid)
{
final long mostSignificantBits = uuid.getMostSignificantBits();
final long leastSignificantBits = uuid.getLeastSignificantBits();
return new byte[]
{
(byte) (mostSignificantBits >>> 56),
(byte) (mostSignificantBits >>> 48),
(byte) (mostSignificantBits >>> 40),
(byte) (mostSignificantBits >>> 32),
(byte) (mostSignificantBits >>> 24),
(byte) (mostSignificantBits >>> 16),
(byte) (mostSignificantBits >>> 8),
(byte) mostSignificantBits,
(byte) (leastSignificantBits >>> 56),
(byte) (leastSignificantBits >>> 48),
(byte) (leastSignificantBits >>> 40),
(byte) (leastSignificantBits >>> 32),
(byte) (leastSignificantBits >>> 24),
(byte) (leastSignificantBits >>> 16),
(byte) (leastSignificantBits >>> 8),
(byte) leastSignificantBits
};
}
private UUIDHelper()
{
}
}
|
/*
* Copyright (c) 2012 by the original author
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.common.enumerations;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author John Collins
*/
public class PowerTypeTest
{
@BeforeEach
public void setUp () throws Exception
{
}
/**
* Test method for {@link org.powertac.common.enumerations.PowerType#isConsumption()}.
*/
@Test
public void testIsConsumption ()
{
PowerType pt = PowerType.CONSUMPTION;
assertTrue(pt.isConsumption(), "is consumption 1");
pt = PowerType.INTERRUPTIBLE_CONSUMPTION;
assertTrue(pt.isConsumption(), "is consumption 2");
pt = PowerType.THERMAL_STORAGE_CONSUMPTION;
assertTrue(pt.isConsumption(), "is consumption 3");
pt = PowerType.BATTERY_STORAGE;
assertFalse(pt.isConsumption(), "not consumption 1");
pt = PowerType.PRODUCTION;
assertFalse(pt.isConsumption(), "not consumption 2");
}
/**
* Test method for {@link org.powertac.common.enumerations.PowerType#isProduction()}.
*/
@Test
public void testIsProduction ()
{
PowerType pt = PowerType.PRODUCTION;
assertTrue(pt.isProduction(), "is production 1");
pt = PowerType.RUN_OF_RIVER_PRODUCTION;
assertTrue(pt.isProduction(), "is production 2");
pt = PowerType.SOLAR_PRODUCTION;
assertTrue(pt.isProduction(), "is production 3");
pt = PowerType.WIND_PRODUCTION;
assertTrue(pt.isProduction(), "is production 4");
pt = PowerType.BATTERY_STORAGE;
assertFalse(pt.isProduction(), "not production 1");
pt = PowerType.CONSUMPTION;
assertFalse(pt.isProduction(), "not production 2");
}
/**
* Test method for {@link org.powertac.common.enumerations.PowerType#isInterruptible()}.
*/
@Test
public void testIsInterruptible ()
{
PowerType pt = PowerType.INTERRUPTIBLE_CONSUMPTION;
assertTrue(pt.isInterruptible(), "is interruptible 1");
pt = PowerType.THERMAL_STORAGE_CONSUMPTION;
assertTrue(pt.isInterruptible(), "is interruptible 2");
pt = PowerType.CONSUMPTION;
assertFalse(pt.isInterruptible(), "not interruptible 1");
pt = PowerType.ELECTRIC_VEHICLE;
assertTrue(pt.isInterruptible(), "is interruptible 3");
}
@Test
public void testGenericType ()
{
assertEquals(PowerType.CONSUMPTION, PowerType.INTERRUPTIBLE_CONSUMPTION.getGenericType());
assertEquals(PowerType.STORAGE, PowerType.THERMAL_STORAGE_CONSUMPTION.getGenericType());
assertEquals(PowerType.CONSUMPTION, PowerType.CONSUMPTION.getGenericType());
assertEquals(PowerType.PRODUCTION, PowerType.CHP_PRODUCTION.getGenericType());
assertEquals(PowerType.PRODUCTION, PowerType.FOSSIL_PRODUCTION.getGenericType());
assertEquals(PowerType.PRODUCTION, PowerType.PRODUCTION.getGenericType());
assertEquals(PowerType.STORAGE, PowerType.BATTERY_STORAGE.getGenericType());
//assertEquals(PowerType.STORAGE, PowerType.PUMPED_STORAGE_PRODUCTION.getGenericType());
assertEquals(PowerType.STORAGE, PowerType.STORAGE.getGenericType());
}
/**
* Test method for {@link org.powertac.common.enumerations.PowerType#toString()}.
*/
@Test
public void testToString ()
{
PowerType pt = PowerType.INTERRUPTIBLE_CONSUMPTION;
assertEquals("INTERRUPTIBLE_CONSUMPTION", pt.toString(), "Correct string");
}
/**
* Test conversion from string
*/
@Test
public void testValueOf ()
{
assertEquals(PowerType.BATTERY_STORAGE,
PowerType.valueOf("BATTERY_STORAGE"));
assertEquals(PowerType.INTERRUPTIBLE_CONSUMPTION,
PowerType.valueOf("INTERRUPTIBLE_CONSUMPTION"));
assertEquals(PowerType.CONSUMPTION, PowerType.valueOf("CONSUMPTION"));
assertNull(PowerType.valueOf("Blah"));
}
}
|
package com.witium.util;
import okhttp3.*;
import java.io.IOException;
import java.util.Optional;
/**
* Desciption okhttp3工具类
* Create By li.bo
* CreateTime 2018/5/15 14:33
* UpdateTime 2018/5/15 14:33
*/
public class Okhttp3Util {
private Okhttp3Util() {
throw new Error("Don't instance of " + getClass());
}
/**
* request type: get
*
* @param url 完整请求路径(如"https://127.0.0.0::8088/login")
* @param params 拼接参数字段(如"?username=X&password=Y")
* @return 网络请求成功的返回体
*/
public static String get(String url, String params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url.concat(params))
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
return Optional.ofNullable(response)
.filter(r -> "200".equals(r.code()))
.get().body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
/**
* request type: post
*
* @param url 完整请求路径(如"https://127.0.0.0::8088/login")
* @param body 表单参数
* @return 网络请求成功的返回体
*/
public static String post(String url, RequestBody body) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
return Optional.ofNullable(response)
.filter(r -> 200 == r.code())
.map(r -> {
try {
return r.body().string();
} catch (IOException e) {
e.printStackTrace();
return "";
}
})
.get();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
}
|
package org.andromda.andromdapp;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Represents a prompt "condition". That is, a prompt
* value will be set if the condition is satisfied.
*
* @author Chad Brandon
*/
public class Condition
{
/**
* The id of the prompt to which this condition applies.
*/
private String id;
/**
* Gets the id of the prompt to which this condition applies.
*
* @return Returns the id.
*/
public String getId()
{
return id;
}
/**
* Sets the id of the prompt to which this condition applies.
*
* @param id The id to set.
*/
public void setId(final String id)
{
this.id = id;
}
/**
* Stores the properties to set if the condition is true.
*/
private final Map<String, Object> properties = new LinkedHashMap<String, Object>();
/**
* Sets the value of the property in the template context
* with the given <code>id</code> to have the given <code>value</code>
* if this condition is true.
*
* @param id the identifier of the prompt.
* @param value the value to give the prompt.
* @param type the fully qualified type name.
*/
public void setProperty(
final String id,
final String value,
final String type)
{
this.properties.put(
id,
AndroMDAppUtils.convert(
value,
type));
}
/**
* Gets all properties to set for this condition.
*
* @return the prompt values.
*/
public Map<String, Object> getProperties()
{
return this.properties;
}
/**
* The value of which the condition must be equal.
*/
private String equal;
/**
* Gets the value of which the condition must be equal.
*
* @return Returns the equal.
*/
public String getEqual()
{
return equal;
}
/**
* Sets the value of which the condition must be equal.
*
* @param equal The equal to set.
*/
public void setEqual(final String equal)
{
this.equal = equal;
}
/**
* The value of which the condition must not be equal.
*/
private String notEqual;
/**
* Gets the value of which the condition must <strong>not</strong> be equal.
*
* @return Returns the notEqual.
*/
public String getNotEqual()
{
return notEqual;
}
/**
* Sets the value of which the condition must <strong>not</strong> be equal.
*
* @param notEqual The notEqual to set.
*/
public void setNotEqual(final String notEqual)
{
this.notEqual = notEqual;
}
/**
* The value of which the condition must be present.
*/
private Boolean present;
/**
* Sets whether or not the condition must be present.
*
* @param present The present to set.
*/
public void setPresent(final boolean present)
{
this.present = Boolean.valueOf(present);
}
/**
* Evalutes whether or not the value is valid according to this condition.
*
* @param value the value to evaluate.
* @return true/false
*/
public boolean evaluate(Object value)
{
boolean valid = true;
if (this.present != null)
{
// - if the condition must be present, very that it is
if (this.present.booleanValue())
{
valid = value != null;
}
else if (!this.present.booleanValue())
{
// - otherwise verify that the condition is not present (if it shouldn't be)
valid = value == null;
}
}
if (valid)
{
final String equal = this.getEqual();
final String notEqual = this.getNotEqual();
final boolean equalConditionPresent = equal != null;
final boolean notEqualConditionPresent = notEqual != null;
value = String.valueOf(value);
if (equalConditionPresent && equal != null)
{
valid = equal.equals(value);
}
else if (notEqualConditionPresent && notEqual != null)
{
valid ^= notEqual.equals(value);
}
}
return valid;
}
/**
* @see Object#toString()
*/
public String toString()
{
return super.toString() + "[id=" + this.id + ", equal=" + this.equal + ", notEqual=" + this.notEqual + ']';
}
}
|
/*
* Copyright © 2014 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.tigon.data.transaction.snapshot;
import co.cask.tephra.TransactionManager;
import co.cask.tephra.persist.TransactionSnapshot;
import co.cask.tephra.snapshot.BinaryDecoder;
import co.cask.tephra.snapshot.BinaryEncoder;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.Map;
import java.util.NavigableMap;
/**
* Handles serialization/deserialization of a {@link TransactionSnapshot} and
* its elements to {@code byte[]}.
*/
public class SnapshotCodecV1 extends AbstractSnapshotCodec {
public static final int VERSION = 1;
@Override
public int getVersion() {
return VERSION;
}
@Override
protected void decodeObsoleteAttributes(BinaryDecoder decoder) throws IOException {
// watermark attribute was removed
decoder.readLong();
}
@Override
protected void encodeObsoleteAttributes(BinaryEncoder encoder) throws IOException {
// writing watermark attribute (that was removed in newer codecs), 55L - any random value, will not be used anywhere
encoder.writeLong(55L);
}
@Override
protected void encodeInProgress(BinaryEncoder encoder, Map<Long, TransactionManager.InProgressTx> inProgress)
throws IOException {
if (!inProgress.isEmpty()) {
encoder.writeInt(inProgress.size());
for (Map.Entry<Long, TransactionManager.InProgressTx> entry : inProgress.entrySet()) {
encoder.writeLong(entry.getKey()); // tx id
encoder.writeLong(entry.getValue().getExpiration());
}
}
encoder.writeInt(0); // zero denotes end of list as per AVRO spec
}
@Override
protected NavigableMap<Long, TransactionManager.InProgressTx> decodeInProgress(BinaryDecoder decoder)
throws IOException {
int size = decoder.readInt();
NavigableMap<Long, TransactionManager.InProgressTx> inProgress = Maps.newTreeMap();
while (size != 0) { // zero denotes end of list as per AVRO spec
for (int remaining = size; remaining > 0; --remaining) {
inProgress.put(decoder.readLong(),
// 1st version did not store visibilityUpperBound. It is safe to set firstInProgress to 0,
// it may decrease performance until this tx is finished, but correctness will be preserved.
new TransactionManager.InProgressTx(0L, decoder.readLong()));
}
size = decoder.readInt();
}
return inProgress;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.metastore.messaging.json;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
import org.apache.hadoop.hive.metastore.messaging.AddNotNullConstraintMessage;
import org.apache.thrift.TException;
import org.codehaus.jackson.annotate.JsonProperty;
public class JSONAddNotNullConstraintMessage extends AddNotNullConstraintMessage {
@JsonProperty
String server, servicePrincipal;
@JsonProperty
Long timestamp;
@JsonProperty
List<String> notNullConstraintListJson;
/**
* Default constructor, needed for Jackson.
*/
public JSONAddNotNullConstraintMessage() {
}
public JSONAddNotNullConstraintMessage(String server, String servicePrincipal, List<SQLNotNullConstraint> nns,
Long timestamp) {
this.server = server;
this.servicePrincipal = servicePrincipal;
this.timestamp = timestamp;
this.notNullConstraintListJson = new ArrayList<>();
try {
for (SQLNotNullConstraint nn : nns) {
notNullConstraintListJson.add(JSONMessageFactory.createNotNullConstraintObjJson(nn));
}
} catch (TException e) {
throw new IllegalArgumentException("Could not serialize: ", e);
}
}
@Override
public String getServer() {
return server;
}
@Override
public String getServicePrincipal() {
return servicePrincipal;
}
@Override
public String getDB() {
return null;
}
@Override
public Long getTimestamp() {
return timestamp;
}
@Override
public List<SQLNotNullConstraint> getNotNullConstraints() throws Exception {
List<SQLNotNullConstraint> nns = new ArrayList<>();
for (String nnJson : notNullConstraintListJson) {
nns.add((SQLNotNullConstraint)JSONMessageFactory.getTObj(nnJson, SQLNotNullConstraint.class));
}
return nns;
}
@Override
public String toString() {
try {
return JSONMessageDeserializer.mapper.writeValueAsString(this);
} catch (Exception exception) {
throw new IllegalArgumentException("Could not serialize: ", exception);
}
}
}
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.test.fixtures.server.http;
import com.sun.net.httpserver.HttpExchange;
import org.gradle.internal.time.Clock;
import org.gradle.internal.time.Time;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
class CyclicBarrierAnyOfRequestHandler implements TrackingHttpHandler, WaitPrecondition, BlockingHttpServer.BlockingHandler {
private final Lock lock;
private final Condition condition;
private final List<String> received = new ArrayList<String>();
private final List<String> released = new ArrayList<String>();
private final Map<String, ResourceHandlerWrapper> all = new TreeMap<String, ResourceHandlerWrapper>();
private final Map<String, ResourceHandlerWrapper> expected = new TreeMap<String, ResourceHandlerWrapper>();
private final int testId;
private final int timeoutMs;
private final Clock clock = Time.clock();
private int waitingFor;
private final WaitPrecondition previous;
private long mostRecentEvent;
private AssertionError failure;
CyclicBarrierAnyOfRequestHandler(Lock lock, int testId, int timeoutMs, int maxConcurrent, WaitPrecondition previous, Collection<? extends ResourceExpectation> expectedRequests) {
if (expectedRequests.size() < maxConcurrent) {
throw new IllegalArgumentException("Too few requests specified.");
}
this.lock = lock;
this.condition = lock.newCondition();
this.testId = testId;
this.timeoutMs = timeoutMs;
this.waitingFor = maxConcurrent;
this.previous = previous;
for (ResourceExpectation expectation : expectedRequests) {
ResourceHandlerWrapper handler = new ResourceHandlerWrapper(lock, expectation);
expected.put(handler.getPath(), handler);
all.put(handler.getPath(), handler);
}
}
@Override
public WaitPrecondition getWaitPrecondition() {
return this;
}
@Override
public void assertCanWait() throws IllegalStateException {
lock.lock();
try {
if (expected.isEmpty() || !released.isEmpty()) {
// Have received all requests, or have released something, so downstream can wait. This isn't quite right
return;
}
previous.assertCanWait();
throw new IllegalStateException(String.format("Cannot wait as no requests have been released. Waiting for %s, received %s.", expected.keySet(), received));
} finally {
lock.unlock();
}
}
@Override
public ResourceHandler handle(int id, HttpExchange httpExchange) throws Exception {
ResourceHandlerWrapper handler;
lock.lock();
try {
if (expected.isEmpty()) {
// barrier open, let it travel on
return null;
}
if (failure != null) {
// Busted
throw failure;
}
long now = clock.getCurrentTime();
if (mostRecentEvent < now) {
mostRecentEvent = now;
}
String path = httpExchange.getRequestURI().getPath().substring(1);
handler = expected.get(path);
if (handler == null || !handler.getMethod().equals(httpExchange.getRequestMethod()) || waitingFor == 0) {
failure = new AssertionError(String.format("Unexpected request %s %s received. Waiting for %s further requests, already received %s, released %s, still expecting %s.", httpExchange.getRequestMethod(), path, waitingFor, received, released, expected.keySet()));
condition.signalAll();
throw failure;
}
expected.remove(path);
received.add(path);
waitingFor--;
if (waitingFor == 0) {
condition.signalAll();
}
while (!released.contains(path) && failure == null) {
long waitMs = mostRecentEvent + timeoutMs - clock.getCurrentTime();
if (waitMs < 0) {
if (waitingFor > 0) {
System.out.println(String.format("[%d] timeout waiting for other requests", id));
throw timeoutWaitingForRequests();
}
System.out.println(String.format("[%d] timeout waiting to be released", id));
failure = new AssertionError(String.format("Timeout waiting to be released. Waiting for %s further requests, received %s, released %s, not yet received %s.", waitingFor, received, released, expected.keySet()));
condition.signalAll();
throw failure;
}
System.out.println(String.format("[%d] waiting to be released. Still waiting for %s further requests, already received %s", id, waitingFor, received));
condition.await(waitMs, TimeUnit.MILLISECONDS);
}
if (failure != null) {
// Broken in another thread
System.out.println(String.format("[%d] failure in another thread", id));
throw failure;
}
} finally {
lock.unlock();
}
return handler;
}
public void assertComplete() {
lock.lock();
try {
if (failure != null) {
throw failure;
}
if (!expected.isEmpty()) {
throw new AssertionError(String.format("Did not handle all expected requests. Waiting for %d further requests, received %s, released %s, not yet received %s.", waitingFor, received, released, expected.keySet()));
}
} finally {
lock.unlock();
}
}
@Override
public void release(String path) {
path = new SendFixedContent(path).getPath();
lock.lock();
try {
if (!received.contains(path)) {
throw new IllegalStateException("Expected request not received, should wait for pending calls first.");
}
if (released.contains(path)) {
throw new IllegalStateException("Expected request already released.");
}
System.out.println(String.format("[%d] releasing %s", testId, path));
released.add(path);
all.get(path).released();
doRelease(1);
} finally {
lock.unlock();
}
}
@Override
public void releaseAll() {
lock.lock();
try {
if (!expected.isEmpty()) {
throw new IllegalStateException("Expected requests not received, should wait for pending calls first.");
}
int count = 0;
for (String path : received) {
if (!released.contains(path)) {
System.out.println(String.format("[%d] releasing %s", testId, path));
released.add(path);
all.get(path).released();
count++;
}
}
doRelease(count);
} finally {
lock.unlock();
}
}
@Override
public void release(int count) {
lock.lock();
try {
int releaseCount = 0;
for (int i = 0; releaseCount < count && i < received.size(); i++) {
String path = received.get(i);
if (!released.contains(path)) {
System.out.println(String.format("[%d] releasing %s", testId, path));
released.add(path);
all.get(path).released();
releaseCount++;
}
}
if (releaseCount != count) {
throw new IllegalStateException("Too few requests released, should wait for pending calls first.");
}
doRelease(count);
} finally {
lock.unlock();
}
}
private void doRelease(int count) {
waitingFor = Math.min(expected.size(), waitingFor + count);
System.out.println(String.format("[%d] now expecting %d further requests, received %s, released %s, not yet received %s", testId, waitingFor, received, released, expected.keySet()));
condition.signalAll();
}
@Override
public void waitForAllPendingCalls() {
lock.lock();
try {
previous.assertCanWait();
long now = clock.getCurrentTime();
if (mostRecentEvent < now) {
mostRecentEvent = now;
}
while (waitingFor > 0 && failure == null) {
long waitMs = mostRecentEvent + timeoutMs - clock.getCurrentTime();
if (waitMs < 0) {
System.out.println(String.format("[%d] timeout waiting for expected requests.", testId));
throw timeoutWaitingForRequests();
}
System.out.println(String.format("[%d] waiting for %d further requests, received %s, released %s, not yet received %s", testId, waitingFor, received, released, expected.keySet()));
try {
condition.await(waitMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if (failure != null) {
throw failure;
}
System.out.println(String.format("[%d] expected requests received, received %s, released %s, not yet received %s", testId, received, released, expected.keySet()));
} finally {
lock.unlock();
}
}
private AssertionError timeoutWaitingForRequests() {
failure = new AssertionError(String.format("Timeout waiting for expected requests. Waiting for %d further requests, received %s, released %s, not yet received %s.", waitingFor, received, released, expected.keySet()));
condition.signalAll();
throw failure;
}
}
|
package org.innovateuk.ifs.interview.service;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.springframework.core.io.ByteArrayResource;
/**
* REST service for managing applicant responses to interview feedback.
*/
public interface InterviewResponseRestService {
RestResult<Void> uploadResponse(long applicationId, String contentType, long size, String originalFilename, byte[] multipartFileBytes);
RestResult<Void> deleteResponse(long applicationId);
RestResult<ByteArrayResource> downloadResponse(long applicationId);
RestResult<FileEntryResource> findResponse(long applicationId);
}
|
package com.akjava.gwt.three.client.gwt.core;
import com.akjava.gwt.three.client.js.math.Vector3;
import com.google.gwt.core.client.JavaScriptObject;
public class BoundingBox extends JavaScriptObject{
protected BoundingBox(){
}
public final native Vector3 getMax()/*-{
return this.max;
}-*/;
public final native Vector3 getMin()/*-{
return this.min;
}-*/;
public final native void setMax(Vector3 max)/*-{
this.max=max;
}-*/;
public final native void setMin(Vector3 min)/*-{
this.min=min;
}-*/;
}
|
package chord.program.visitors;
import joeq.Compiler.Quad.Quad;
/**
* Visitor over all heap accessing statements in all methods in the program.
*
* @author Mayur Naik (mhn@cs.stanford.edu)
*/
public interface IHeapInstVisitor extends IMethodVisitor {
/**
* Visits all heap accessing statements in all methods in the program.
*
* @param q A heap accessing statement.
*/
public void visitHeapInst(Quad q);
}
|
/**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Fri Nov 06 21:44:05 GMT 2020
*/
package umd.cs.shop;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class JSJshop_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "umd.cs.shop.JSJshop";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.dir", "/home/ubuntu/replication/scripts/projects/85_shop");
java.lang.System.setProperty("user.home", "/home/ubuntu");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "ubuntu");
java.lang.System.setProperty("user.timezone", "Etc/UTC");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(JSJshop_ESTest_scaffolding.class.getClassLoader() ,
"umd.cs.shop.JSListLogicalAtoms",
"umd.cs.shop.JSJshop",
"umd.cs.shop.JSParserError",
"umd.cs.shop.JSListIfThenElse",
"umd.cs.shop.JSPlanningProblem",
"umd.cs.shop.JSPredicateForm",
"umd.cs.shop.JSPlanningDomain",
"umd.cs.shop.JSJshopNode",
"umd.cs.shop.JSUtil",
"umd.cs.shop.JSJshopVars",
"umd.cs.shop.JSTState",
"umd.cs.shop.JSState",
"umd.cs.shop.JSOperator",
"umd.cs.shop.JSListSubstitution",
"umd.cs.shop.JSPairPlanTState",
"umd.cs.shop.JSAllReduction",
"umd.cs.shop.JSListMethods",
"umd.cs.shop.JSListPairPlanTStateNodes",
"umd.cs.shop.JSTaskAtom",
"umd.cs.shop.JSTerm",
"umd.cs.shop.JSReduction",
"umd.cs.shop.JSTasks",
"umd.cs.shop.JSListPlanningProblem",
"umd.cs.shop.JSMethod",
"umd.cs.shop.JSPlan",
"umd.cs.shop.JSSubstitution",
"umd.cs.shop.JSListAxioms",
"umd.cs.shop.JSPairPlanTSListNodes",
"umd.cs.shop.JSListOperators"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(JSJshop_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"umd.cs.shop.JSJshop",
"umd.cs.shop.JSJshopVars",
"umd.cs.shop.JSListPlanningProblem",
"umd.cs.shop.JSUtil",
"umd.cs.shop.JSParserError",
"umd.cs.shop.JSPredicateForm",
"umd.cs.shop.JSTaskAtom",
"umd.cs.shop.JSMethod",
"umd.cs.shop.JSOperator",
"umd.cs.shop.JSListLogicalAtoms",
"umd.cs.shop.JSState",
"umd.cs.shop.JSSubstitution",
"umd.cs.shop.JSListAxioms",
"umd.cs.shop.JSListSubstitution",
"umd.cs.shop.JSTasks",
"umd.cs.shop.JSPlan",
"umd.cs.shop.JSPairPlanTSListNodes",
"umd.cs.shop.JSPlanningDomain",
"umd.cs.shop.JSListOperators",
"umd.cs.shop.JSListMethods",
"umd.cs.shop.JSListIfThenElse",
"umd.cs.shop.JSPlanningProblem",
"umd.cs.shop.JSJshopNode"
);
}
}
|
package com.atguigu.generator.dao;
import org.apache.ibatis.annotations.Mapper;
/**
* MySQL代码生成器
*
* @author Mark sunlightcs@gmail.com
* @since 2018-07-24
*/
@Mapper
public interface MySQLGeneratorDao extends GeneratorDao {
}
|
/**
* Copyright Intellectual Reserve, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gedcomx.common;
import java.util.Map;
/**
* @author Ryan Heaton
*/
public interface HasTransientProperties {
/**
* Get the transient properties.
*
* @return the transient properties.
*/
Map<String, Object> getTransientProperties();
/**
* Get a transient (non-serialized) property.
*
* @param name The name of the property.
* @return The property.
*/
Object getTransientProperty(String name);
/**
* Set a transient (non-serialized) property.
*
* @param name the name of the property.
* @param value the property value.
*/
void setTransientProperty(String name, Object value);
}
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 31.07.2006
* Time: 13:24:17
*/
package com.intellij.openapi.vcs.impl;
import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorFactoryListener;
import com.intellij.openapi.editor.ex.DocumentBulkUpdateListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusListener;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.VcsApplicationSettings;
import com.intellij.openapi.vcs.ex.LineStatusTracker;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vfs.*;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.concurrency.QueueProcessorRemovePartner;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
public class LineStatusTrackerManager implements ProjectComponent, LineStatusTrackerManagerI {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.LineStatusTrackerManager");
@NonNls protected static final String IGNORE_CHANGEMARKERS_KEY = "idea.ignore.changemarkers";
@NotNull public final Object myLock = new Object();
@NotNull private final Project myProject;
@NotNull private final VcsBaseContentProvider myStatusProvider;
@NotNull private final Application myApplication;
@NotNull private final FileEditorManager myFileEditorManager;
@NotNull private final Disposable myDisposable;
@NotNull private final Map<Document, TrackerData> myLineStatusTrackers;
@NotNull private final QueueProcessorRemovePartner<Document, BaseRevisionLoader> myPartner;
private long myLoadCounter;
public static LineStatusTrackerManagerI getInstance(final Project project) {
return PeriodicalTasksCloser.getInstance().safeGetComponent(project, LineStatusTrackerManagerI.class);
}
public LineStatusTrackerManager(@NotNull final Project project,
@NotNull final VcsBaseContentProvider statusProvider,
@NotNull final Application application,
@NotNull final FileEditorManager fileEditorManager,
@SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
myLoadCounter = 0;
myProject = project;
myStatusProvider = statusProvider;
myApplication = application;
myFileEditorManager = fileEditorManager;
myLineStatusTrackers = new HashMap<>();
myPartner = new QueueProcessorRemovePartner<>(myProject, new Consumer<BaseRevisionLoader>() {
@Override
public void consume(BaseRevisionLoader baseRevisionLoader) {
baseRevisionLoader.run();
}
});
MessageBusConnection busConnection = project.getMessageBus().connect();
busConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
@Override
public void updateStarted(@NotNull final Document doc) {
final LineStatusTracker tracker = getLineStatusTracker(doc);
if (tracker != null) tracker.startBulkUpdate();
}
@Override
public void updateFinished(@NotNull final Document doc) {
final LineStatusTracker tracker = getLineStatusTracker(doc);
if (tracker != null) tracker.finishBulkUpdate();
}
});
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, new LineStatusTrackerSettingListener() {
@Override
public void settingsUpdated() {
synchronized (myLock) {
LineStatusTracker.Mode mode = getMode();
for (TrackerData data : myLineStatusTrackers.values()) {
data.tracker.setMode(mode);
}
}
}
});
myDisposable = new Disposable() {
@Override
public void dispose() {
synchronized (myLock) {
for (final TrackerData data : myLineStatusTrackers.values()) {
data.tracker.release();
}
myLineStatusTrackers.clear();
myPartner.clear();
}
}
};
Disposer.register(myProject, myDisposable);
}
@Override
public void projectOpened() {
StartupManager.getInstance(myProject).registerPreStartupActivity(new Runnable() {
@Override
public void run() {
final MyFileStatusListener fileStatusListener = new MyFileStatusListener();
final EditorFactoryListener editorFactoryListener = new MyEditorFactoryListener();
final MyVirtualFileListener virtualFileListener = new MyVirtualFileListener();
final FileStatusManager fsManager = FileStatusManager.getInstance(myProject);
fsManager.addFileStatusListener(fileStatusListener, myDisposable);
final EditorFactory editorFactory = EditorFactory.getInstance();
editorFactory.addEditorFactoryListener(editorFactoryListener, myDisposable);
final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
virtualFileManager.addVirtualFileListener(virtualFileListener, myDisposable);
}
});
}
@Override
public void projectClosed() {
}
@Override
@NonNls
@NotNull
public String getComponentName() {
return "LineStatusTrackerManager";
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
}
public boolean isDisabled() {
return !myProject.isOpen() || myProject.isDisposed();
}
@Override
@Nullable
public LineStatusTracker getLineStatusTracker(final Document document) {
synchronized (myLock) {
if (isDisabled()) return null;
TrackerData data = myLineStatusTrackers.get(document);
return data != null ? data.tracker : null;
}
}
private void resetTrackers() {
synchronized (myLock) {
if (isDisabled()) return;
log("resetTrackers", null);
List<LineStatusTracker> trackers = ContainerUtil.map(myLineStatusTrackers.values(), (data) -> data.tracker);
for (LineStatusTracker tracker : trackers) {
resetTracker(tracker.getDocument(), tracker.getVirtualFile(), tracker);
}
final VirtualFile[] openFiles = myFileEditorManager.getOpenFiles();
for (final VirtualFile openFile : openFiles) {
resetTracker(openFile, true);
}
}
}
private void resetTracker(@NotNull final VirtualFile virtualFile) {
resetTracker(virtualFile, false);
}
private void resetTracker(@NotNull final VirtualFile virtualFile, boolean insertOnly) {
final Document document = FileDocumentManager.getInstance().getCachedDocument(virtualFile);
if (document == null) {
log("resetTracker: no cached document", virtualFile);
return;
}
synchronized (myLock) {
if (isDisabled()) return;
final LineStatusTracker tracker = getLineStatusTracker(document);
if (insertOnly && tracker != null) return;
resetTracker(document, virtualFile, tracker);
}
}
private void resetTracker(@NotNull Document document, @NotNull VirtualFile virtualFile, @Nullable LineStatusTracker tracker) {
final boolean editorOpened = myFileEditorManager.isFileOpen(virtualFile);
final boolean shouldBeInstalled = editorOpened && shouldBeInstalled(virtualFile);
log("resetTracker: shouldBeInstalled - " + shouldBeInstalled + ", tracker - " + (tracker == null ? "null" : "found"), virtualFile);
if (tracker != null && shouldBeInstalled) {
refreshTracker(tracker);
}
else if (tracker != null) {
releaseTracker(document);
}
else if (shouldBeInstalled) {
installTracker(virtualFile, document);
}
}
private boolean shouldBeInstalled(@Nullable final VirtualFile virtualFile) {
if (isDisabled()) return false;
if (virtualFile == null || virtualFile instanceof LightVirtualFile) return false;
final FileStatusManager statusManager = FileStatusManager.getInstance(myProject);
if (statusManager == null) return false;
if (!myStatusProvider.isSupported(virtualFile)) {
log("shouldBeInstalled failed: no support found", virtualFile);
return false;
}
final FileStatus status = statusManager.getStatus(virtualFile);
if (status == FileStatus.NOT_CHANGED || status == FileStatus.ADDED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) {
log("shouldBeInstalled skipped: status=" + status, virtualFile);
return false;
}
return true;
}
private void refreshTracker(@NotNull LineStatusTracker tracker) {
synchronized (myLock) {
if (isDisabled()) return;
startAlarm(tracker.getDocument(), tracker.getVirtualFile());
}
}
private void releaseTracker(@NotNull final Document document) {
synchronized (myLock) {
if (isDisabled()) return;
myPartner.remove(document);
final TrackerData data = myLineStatusTrackers.remove(document);
if (data != null) {
data.tracker.release();
}
}
}
private void installTracker(@NotNull final VirtualFile virtualFile, @NotNull final Document document) {
synchronized (myLock) {
if (isDisabled()) return;
if (myLineStatusTrackers.containsKey(document)) return;
assert !myPartner.containsKey(document);
final LineStatusTracker tracker = LineStatusTracker.createOn(virtualFile, document, myProject, getMode());
myLineStatusTrackers.put(document, new TrackerData(tracker));
startAlarm(document, virtualFile);
}
}
@NotNull
private static LineStatusTracker.Mode getMode() {
VcsApplicationSettings vcsApplicationSettings = VcsApplicationSettings.getInstance();
if (!vcsApplicationSettings.SHOW_LST_GUTTER_MARKERS) return LineStatusTracker.Mode.SILENT;
return vcsApplicationSettings.SHOW_WHITESPACES_IN_LST ? LineStatusTracker.Mode.SMART : LineStatusTracker.Mode.DEFAULT;
}
private void startAlarm(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
synchronized (myLock) {
myPartner.add(document, new BaseRevisionLoader(document, virtualFile));
}
}
private class BaseRevisionLoader implements Runnable {
@NotNull private final VirtualFile myVirtualFile;
@NotNull private final Document myDocument;
private BaseRevisionLoader(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
myDocument = document;
myVirtualFile = virtualFile;
}
@Override
public void run() {
if (isDisabled()) return;
if (!myVirtualFile.isValid()) {
log("BaseRevisionLoader failed: virtual file not valid", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
VcsBaseContentProvider.BaseContent baseContent = myStatusProvider.getBaseRevision(myVirtualFile);
if (baseContent == null) {
log("BaseRevisionLoader failed: null returned for base revision", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
// loads are sequential (in single threaded QueueProcessor);
// so myLoadCounter can't take less value for greater base revision -> the only thing we want from it
final VcsRevisionNumber revisionNumber = baseContent.getRevisionNumber();
final Charset charset = myVirtualFile.getCharset();
final long loadCounter = myLoadCounter;
myLoadCounter++;
synchronized (myLock) {
final TrackerData data = myLineStatusTrackers.get(myDocument);
if (data == null) {
log("BaseRevisionLoader canceled: tracker already released", myVirtualFile);
return;
}
if (!data.shouldBeUpdated(revisionNumber, charset, loadCounter)) {
log("BaseRevisionLoader canceled: no need to update", myVirtualFile);
return;
}
}
String lastUpToDateContent = baseContent.loadContent();
if (lastUpToDateContent == null) {
log("BaseRevisionLoader failed: can't load up-to-date content", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
final String converted = StringUtil.convertLineSeparators(lastUpToDateContent);
final Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (myLock) {
final TrackerData data = myLineStatusTrackers.get(myDocument);
if (data == null) {
log("BaseRevisionLoader initializing: tracker already released", myVirtualFile);
return;
}
if (!data.shouldBeUpdated(revisionNumber, charset, loadCounter)) {
log("BaseRevisionLoader initializing: canceled", myVirtualFile);
return;
}
log("BaseRevisionLoader initializing: success", myVirtualFile);
myLineStatusTrackers.put(myDocument, new TrackerData(data.tracker, revisionNumber, charset, loadCounter));
data.tracker.setBaseRevision(converted);
}
}
};
nonModalAliveInvokeLater(runnable);
}
private void nonModalAliveInvokeLater(@NotNull Runnable runnable) {
myApplication.invokeLater(runnable, ModalityState.NON_MODAL, new Condition() {
@Override
public boolean value(final Object ignore) {
return isDisabled();
}
});
}
private void reportTrackerBaseLoadFailed() {
synchronized (myLock) {
releaseTracker(myDocument);
}
}
}
private class MyFileStatusListener implements FileStatusListener {
@Override
public void fileStatusesChanged() {
resetTrackers();
}
@Override
public void fileStatusChanged(@NotNull VirtualFile virtualFile) {
resetTracker(virtualFile);
}
}
private class MyEditorFactoryListener extends EditorFactoryAdapter {
@Override
public void editorCreated(@NotNull EditorFactoryEvent event) {
// note that in case of lazy loading of configurables, this event can happen
// outside of EDT, so the EDT check mustn't be done here
Editor editor = event.getEditor();
if (editor.getProject() != null && editor.getProject() != myProject) return;
final Document document = editor.getDocument();
final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) return;
if (shouldBeInstalled(virtualFile)) {
installTracker(virtualFile, document);
}
}
@Override
public void editorReleased(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
if (editor.getProject() != null && editor.getProject() != myProject) return;
final Document doc = editor.getDocument();
final Editor[] editors = event.getFactory().getEditors(doc, myProject);
if (editors.length == 0 || (editors.length == 1 && editor == editors[0])) {
releaseTracker(doc);
}
}
}
private class MyVirtualFileListener extends VirtualFileAdapter {
@Override
public void beforeContentsChange(@NotNull VirtualFileEvent event) {
if (event.isFromRefresh()) {
resetTracker(event.getFile());
}
}
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
if (VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) {
resetTracker(event.getFile());
}
}
}
private static class TrackerData {
@NotNull public final LineStatusTracker tracker;
@Nullable private final ContentInfo currentContent;
public TrackerData(@NotNull LineStatusTracker tracker) {
this.tracker = tracker;
this.currentContent = null;
}
public TrackerData(@NotNull LineStatusTracker tracker,
@NotNull VcsRevisionNumber revision,
@NotNull Charset charset,
long loadCounter) {
this.tracker = tracker;
this.currentContent = new ContentInfo(revision, charset, loadCounter);
}
public boolean shouldBeUpdated(@NotNull VcsRevisionNumber revision, @NotNull Charset charset, long loadCounter) {
if (currentContent == null) return true;
if (currentContent.revision.equals(revision) && !currentContent.revision.equals(VcsRevisionNumber.NULL)) {
return !currentContent.charset.equals(charset);
}
return currentContent.loadCounter < loadCounter;
}
}
private static class ContentInfo {
@NotNull public final VcsRevisionNumber revision;
@NotNull public final Charset charset;
public final long loadCounter;
public ContentInfo(@NotNull VcsRevisionNumber revision, @NotNull Charset charset, long loadCounter) {
this.revision = revision;
this.charset = charset;
this.loadCounter = loadCounter;
}
}
private static void log(@NotNull String message, @Nullable VirtualFile file) {
if (LOG.isDebugEnabled()) {
if (file != null) message += "; file: " + file.getPath();
LOG.debug(message);
}
}
}
|
//license WCBN CC-BY-NON 2018
//original by Mike Huang 201?-2017
//modified by Tony Audas 2018
package org.wcbn.android;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.crashlytics.android.Crashlytics;
import net.moraleboost.streamscraper.Stream;
import org.wcbn.android.StreamService.StreamBinder;
import org.wcbn.android.station.Station;
import java.util.ArrayList;
import java.util.List;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity implements OnNavigationListener,
StreamService.OnStateUpdateListener {
private StreamService mService;
private boolean mBound, mIsManualOpen = false;
private final List<UiFragment> mFragments = new ArrayList<UiFragment>();
private PlaybackFragment mPlaybackFragment = new PlaybackFragment();
private SongInfoFragment mSongInfoFragment = new SongInfoFragment();
private Activity mActivity = this;
private String mShareString;
private CharSequence mTitle, mDrawerTitle;
private static final Station sStation;
private ListView mDrawerList;
private String[] mTabNames;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private int mCurItem;
private SharedPreferences mPrefs;
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
static {
sStation = Utils.getStation();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mTabNames = getResources().getStringArray(sStation.getTabNames());
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerList = findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTabNames));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getString(R.string.wcbn);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
if(mIsManualOpen) {
SharedPreferences.Editor prefEditor = mPrefs.edit();
prefEditor.putBoolean("drawer_opened", true);
prefEditor.apply();
}
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(mFragments.isEmpty()) {
for(Class<? extends UiFragment> cls : sStation.getUiFragments()) {
try {
mFragments.add(cls.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.playback, mPlaybackFragment)
.commit();
getSupportFragmentManager().beginTransaction()
.replace(R.id.info, mSongInfoFragment)
.commit();
if(savedInstanceState == null ||
!savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
mCurItem = 0;
}
else {
mCurItem = savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
if(mBound) {
// Create a new fragment and specify the planet to show based on position
UiFragment fragment = mFragments.get(position);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, (Fragment) fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mTabNames[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
mCurItem = position;
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, StreamService.class);
bindService(intent, mConnection, Context.BIND_IMPORTANT);
startService(intent);
}
@Override
protected void onResume() {
super.onResume();
if(mBound)
mService.setMetadataRefresh(true);
}
@Override
protected void onPause() {
super.onPause();
if(mBound)
mService.setMetadataRefresh(false);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState.containsKey("share_string")) {
mShareString = savedInstanceState.getString("share_string");
}
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
mCurItem);
if(mShareString != null)
outState.putString("share_string", mShareString);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.action_share:
if(mBound && mService.getStream() != null)
startActivity(getShareIntent(mService.getStream()));
}
return false;
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
UiFragment fragment = mFragments.get(position);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, (Fragment) fragment)
.commit();
return true;
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
StreamBinder binder = (StreamBinder) service;
mService = binder.getService();
mService.setOnStateUpdateListener((StreamService.OnStateUpdateListener) mActivity);
mBound = true;
if(mService.isPreparing()) {
setProgressBarIndeterminateVisibility(true);
}
else {
setProgressBarIndeterminateVisibility(false);
}
mPlaybackFragment.setService(mService);
mSongInfoFragment.setService(mService);
for(UiFragment fragment : mFragments) {
fragment.setService(mService);
}
selectItem(mCurItem);
mService.setMetadataRefresh(true);
if(!mPrefs.getBoolean("drawer_opened", false)) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
mIsManualOpen = true;
}
@Override
public void onServiceDisconnected(ComponentName className) {
mService.setOnStateUpdateListener(null);
mBound = false;
mService.setMetadataRefresh(false);
}
};
@Override
public void onMediaError(MediaPlayer mp, int what, int extra) {
setProgressBarIndeterminateVisibility(false);
mPlaybackFragment.handleMediaError(mp, what, extra);
mSongInfoFragment.handleMediaError(mp, what, extra);
for(UiFragment f : mFragments) {
f.handleMediaError(mp, what, extra);
}
}
@Override
public void onMediaPlay() {
setProgressBarIndeterminateVisibility(false);
mPlaybackFragment.handleMediaPlay();
mSongInfoFragment.handleMediaPlay();
for(UiFragment f : mFragments) {
f.handleMediaPlay();
}
}
@Override
public void onMediaPause() {
setProgressBarIndeterminateVisibility(false);
mPlaybackFragment.handleMediaPause();
mSongInfoFragment.handleMediaPause();
for(UiFragment f : mFragments) {
f.handleMediaPause();
}
}
@Override
public void onMediaStop() {
setProgressBarIndeterminateVisibility(false);
mPlaybackFragment.handleMediaStop();
mSongInfoFragment.handleMediaStop();
for(UiFragment f : mFragments) {
f.handleMediaStop();
}
}
@Override
public void updateTrack(Stream stream, Station station, Bitmap albumArt) {
mPlaybackFragment.handleUpdateTrack(stream, station, albumArt);
mSongInfoFragment.handleUpdateTrack(stream, station, albumArt);
for(UiFragment f : mFragments) {
f.handleUpdateTrack(stream, station, albumArt);
}
}
private Intent getShareIntent(Stream stream) {
Intent intent = new Intent();
intent.setType("text/plain");
intent.setAction(Intent.ACTION_SEND);
mShareString = String.format(
getString(R.string.share_string),
Utils.capitalizeTitle(stream.getCurrentSong()),
((StreamExt) stream).getProgram());
intent.putExtra(Intent.EXTRA_TEXT, mShareString);
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_title));
return intent;
}
}
|
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import okhttp3.testing.PlatformRule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static java.util.Arrays.asList;
import static okhttp3.internal.Internal.applyConnectionSpec;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
public final class ConnectionSpecTest {
@RegisterExtension public final PlatformRule platform = new PlatformRule();
@Test public void noTlsVersions() {
try {
new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(new TlsVersion[0])
.build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("At least one TLS version is required");
}
}
@Test public void noCipherSuites() {
try {
new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.cipherSuites(new CipherSuite[0])
.build();
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("At least one cipher suite is required");
}
}
@Test public void cleartextBuilder() {
ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(false).build();
assertThat(cleartextSpec.isTls()).isFalse();
}
@Test public void tlsBuilder_explicitCiphers() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true)
.build();
assertThat(tlsSpec.cipherSuites()).containsExactly(CipherSuite.TLS_RSA_WITH_RC4_128_MD5);
assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
}
@Test public void tlsBuilder_defaultCiphers() throws Exception {
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true)
.build();
assertThat(tlsSpec.cipherSuites()).isNull();
assertThat(tlsSpec.tlsVersions()).containsExactly(TlsVersion.TLS_1_2);
assertThat(tlsSpec.supportsTlsExtensions()).isTrue();
}
@Test public void tls_defaultCiphers_noFallbackIndicator() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(false)
.build();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
});
socket.setEnabledProtocols(new String[] {
TlsVersion.TLS_1_2.javaName(),
TlsVersion.TLS_1_1.javaName(),
});
assertThat(tlsSpec.isCompatible(socket)).isTrue();
applyConnectionSpec(tlsSpec, socket, false /* isFallback */);
assertThat(socket.getEnabledProtocols()).containsExactly(TlsVersion.TLS_1_2.javaName());
assertThat(socket.getEnabledCipherSuites()).containsExactlyInAnyOrder(
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName());
}
@Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(false)
.build();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
});
socket.setEnabledProtocols(new String[] {
TlsVersion.TLS_1_2.javaName(),
TlsVersion.TLS_1_1.javaName(),
});
assertThat(tlsSpec.isCompatible(socket)).isTrue();
applyConnectionSpec(tlsSpec, socket, true /* isFallback */);
assertThat(socket.getEnabledProtocols()).containsExactly(TlsVersion.TLS_1_2.javaName());
List<String> expectedCipherSuites = new ArrayList<>();
expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName());
expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName());
if (asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSuites.add("TLS_FALLBACK_SCSV");
}
assertThat(socket.getEnabledCipherSuites()).containsExactlyElementsOf(expectedCipherSuites);
}
@Test public void tls_explicitCiphers() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(false)
.build();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
});
socket.setEnabledProtocols(new String[] {
TlsVersion.TLS_1_2.javaName(),
TlsVersion.TLS_1_1.javaName(),
});
assertThat(tlsSpec.isCompatible(socket)).isTrue();
applyConnectionSpec(tlsSpec, socket, true /* isFallback */);
assertThat(socket.getEnabledProtocols()).containsExactly(TlsVersion.TLS_1_2.javaName());
List<String> expectedCipherSuites = new ArrayList<>();
expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName());
if (asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
expectedCipherSuites.add("TLS_FALLBACK_SCSV");
}
assertThat(socket.getEnabledCipherSuites()).containsExactlyElementsOf(expectedCipherSuites);
}
@Test public void tls_stringCiphersAndVersions() throws Exception {
// Supporting arbitrary input strings allows users to enable suites and versions that are not
// yet known to the library, but are supported by the platform.
new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.cipherSuites("MAGIC-CIPHER")
.tlsVersions("TLS9k")
.build();
}
@Test public void tls_missingRequiredCipher() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(false)
.build();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledProtocols(new String[] {
TlsVersion.TLS_1_2.javaName(),
TlsVersion.TLS_1_1.javaName(),
});
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
});
assertThat(tlsSpec.isCompatible(socket)).isTrue();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
});
assertThat(tlsSpec.isCompatible(socket)).isFalse();
}
@Test public void allEnabledCipherSuites() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledCipherSuites()
.build();
assertThat(tlsSpec.cipherSuites()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
});
applyConnectionSpec(tlsSpec, sslSocket, false);
assertThat(sslSocket.getEnabledCipherSuites()).containsExactly(
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName(),
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName());
}
@Test public void allEnabledTlsVersions() throws Exception {
platform.assumeNotConscrypt();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledTlsVersions()
.build();
assertThat(tlsSpec.tlsVersions()).isNull();
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
sslSocket.setEnabledProtocols(new String[] {
TlsVersion.SSL_3_0.javaName(),
TlsVersion.TLS_1_1.javaName()
});
applyConnectionSpec(tlsSpec, sslSocket, false);
assertThat(sslSocket.getEnabledProtocols()).containsExactly(
TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName());
}
@Test public void tls_missingTlsVersion() throws Exception {
platform.assumeNotConscrypt();
platform.assumeNotBouncyCastle();
ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(false)
.build();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledCipherSuites(new String[] {
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName(),
});
socket.setEnabledProtocols(
new String[] {TlsVersion.TLS_1_2.javaName(), TlsVersion.TLS_1_1.javaName()});
assertThat(tlsSpec.isCompatible(socket)).isTrue();
socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName()});
assertThat(tlsSpec.isCompatible(socket)).isFalse();
}
@Test public void equalsAndHashCode() throws Exception {
ConnectionSpec allCipherSuites = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledCipherSuites()
.build();
ConnectionSpec allTlsVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledTlsVersions()
.build();
Set<Object> set = new CopyOnWriteArraySet<>();
assertThat(set.add(ConnectionSpec.MODERN_TLS)).isTrue();
assertThat(set.add(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertThat(set.add(ConnectionSpec.CLEARTEXT)).isTrue();
assertThat(set.add(allTlsVersions)).isTrue();
assertThat(set.add(allCipherSuites)).isTrue();
allCipherSuites.hashCode();
assertThat(allCipherSuites.equals(null)).isFalse();
assertThat(set.remove(ConnectionSpec.MODERN_TLS)).isTrue();
assertThat(set.remove(ConnectionSpec.COMPATIBLE_TLS)).isTrue();
assertThat(set.remove(ConnectionSpec.CLEARTEXT)).isTrue();
assertThat(set.remove(allTlsVersions)).isTrue();
assertThat(set.remove(allCipherSuites)).isTrue();
assertThat(set).isEmpty();
allTlsVersions.hashCode();
assertThat(allTlsVersions.equals(null)).isFalse();
}
@Test public void allEnabledToString() throws Exception {
ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledTlsVersions()
.allEnabledCipherSuites()
.build();
assertThat(connectionSpec.toString()).isEqualTo(
("ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], "
+ "supportsTlsExtensions=true)"));
}
@Test public void simpleToString() throws Exception {
ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
.build();
assertThat(connectionSpec.toString()).isEqualTo(
("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], "
+ "supportsTlsExtensions=true)"));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>APPE <SP> <pathname> <CRLF></code><br>
*
* This command causes the server-DTP to accept the data transferred via the
* data connection and to store the data in a file at the server site. If the
* file specified in the pathname exists at the server site, then the data shall
* be appended to that file; otherwise the file specified in the pathname shall
* be created at the server site.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class APPE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(APPE.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// SEEBURGER: in encryption mode files can't be modified
if (!session.getFileSystemView().isRandomAccessible())
{
session.write(new DefaultFtpReply(550, "APPE not available in encryption mode"));
return;
}
// reset state variables
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"APPE", null));
return;
}
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
DataConnectionFactory connFactory = session.getDataConnection();
if (connFactory instanceof IODataConnectionFactory) {
InetAddress address = ((IODataConnectionFactory) connFactory)
.getInetAddress();
if (address == null) {
session.write(new DefaultFtpReply(
FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS,
"PORT or PASV must be issued first"));
return;
}
}
// get filenames
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception e) {
LOG.debug("File system threw exception", e);
setSessionException(session, e);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.invalid", fileName));
return;
}
fileName = file.getAbsolutePath();
// check file existance
if (file.doesExist() && !file.isFile()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.invalid", fileName));
return;
}
// check permission
if (!file.isWritable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.permission", fileName));
return;
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "APPE", fileName));
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception when getting data input stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "APPE",
fileName));
setSessionException(session, e);
return;
}
// get data from client
boolean failure = false;
OutputStream os = null;
try {
// find offset
long offset = 0L;
if (file.doesExist()) {
offset = file.getSize();
}
// open streams
os = file.createOutputStream(offset);
// transfer data
long transSz = dataConnection.transferFromClient(session.getFtpletSession(), os);
// attempt to close the output stream so that errors in
// closing it will return an error to the client (FTPSERVER-119)
if(os != null) {
os.close();
}
LOG.info("File uploaded {} transferred size {} file size {}", new Object[] {fileName, transSz, file.getSize()});
// notify the statistics component
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
ftpStat.setUpload(session, file, transSz);
} catch (SocketException e) {
LOG.debug("SocketException during file upload", e);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"APPE", fileName));
setSessionException(session, e);
} catch (IOException e) {
LOG.debug("IOException during file upload", e);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"APPE", fileName));
setSessionException(session, e);
} finally {
// make sure we really close the output stream
IoUtils.close(os);
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "APPE",
fileName));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
}
|
/**
* Copyright 2016-2021 The Reaktivity Project
*
* The Reaktivity Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.reaktivity.reaktor.internal.context;
import static java.util.Objects.requireNonNull;
import org.reaktivity.reaktor.config.Vault;
import org.reaktivity.reaktor.nukleus.Elektron;
import org.reaktivity.reaktor.nukleus.vault.BindingVault;
final class VaultContext
{
private final Vault vault;
private final Elektron elektron;
private BindingVault attached;
VaultContext(
Vault vault,
Elektron elektron)
{
this.vault = requireNonNull(vault);
this.elektron = requireNonNull(elektron);
}
public void attach()
{
attached = elektron.attach(vault);
}
public void detach()
{
elektron.detach(vault);
attached = null;
}
public BindingVault vaultFactory()
{
return attached;
}
}
|
package eina.unizar.freshtech;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.google.android.material.textfield.TextInputLayout;
import eina.unizar.freshtech.io.ApiAdapter;
import eina.unizar.freshtech.model.Registrar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RegisterActivity extends AppCompatActivity implements Callback<Registrar> {
private static final int ACTIVITY_LOGIN=0;
private EditText correo;
private EditText contraseña;
private EditText confirmarContraseña;
private TextView seguridadContraseña;
private TextInputLayout huecoContraseña;
private ProgressBar progressBar;
private AwesomeValidation awesomeValidation;
private AwesomeValidation awesomeValidationContraseñas;
private boolean isAtLeast8, hasMayus, hasMinus, hasNums, hasEsp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
correo = (EditText) findViewById(R.id.correoRegister);
huecoContraseña = (TextInputLayout) findViewById(R.id.huecoContraseñaRegister);
contraseña = (EditText) findViewById(R.id.contraseñaRegister);
confirmarContraseña = (EditText) findViewById(R.id.confirmarContraseñaRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
contraseña.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void afterTextChanged(Editable s) {
int porcentajeSegura = SeguridadContraseña.calcularSeguridad(s.toString(), isAtLeast8, hasMayus, hasMinus, hasNums, hasEsp);
progressBar.setProgress(porcentajeSegura);
progressBar.setVisibility(View.VISIBLE);
LayerDrawable progressBarDrawable = (LayerDrawable) progressBar.getProgressDrawable();
Drawable progressDrawable = progressBarDrawable.getDrawable(1);
progressDrawable.setColorFilter(ContextCompat.getColor(RegisterActivity.this, SeguridadContraseña.colorProgressBar(porcentajeSegura)), PorterDuff.Mode.SRC_IN);
}
});
}
public void onClickCrearCuenta(View view) {
//Validar campos
String nombre = correo.getText().toString();
String password = contraseña.getText().toString();
String passwordConfirmada = confirmarContraseña.getText().toString();
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
awesomeValidation.addValidation(this, R.id.correoRegister,
Patterns.EMAIL_ADDRESS, R.string.invalid_email);
awesomeValidationContraseñas = new AwesomeValidation(ValidationStyle.TEXT_INPUT_LAYOUT);
awesomeValidationContraseñas.addValidation(this, R.id.huecoContraseñaRegister,
"(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%*])\\S{8,}$", R.string.invalid_password);
awesomeValidationContraseñas.addValidation(this, R.id.huecoConfirmarContraseñaRegister,
R.id.huecoContraseñaRegister, R.string.invalid_confirm_password);
boolean correoCorrecto = awesomeValidation.validate();
boolean contraseñasCorrectas = awesomeValidationContraseñas.validate();
//Conectarse a API
if (correoCorrecto && contraseñasCorrectas) {
Call<Registrar> call = ApiAdapter.getApiService().registrarUsuario(nombre, password);
call.enqueue(this);
}
else {
Toast.makeText(this, "Revise la validación de los campos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onResponse(Call<Registrar> call, Response<Registrar> response) {
if (response.isSuccessful()) {
Registrar registrar = response.body();
Log.d("onResponse registro", "Mensaje => " + registrar.getMessage());
Toast.makeText(this, "Usuario registrado correctamente", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, LoginActivity.class);
startActivityForResult(i, ACTIVITY_LOGIN);
finish();
} else {
correo.setError("Usuario ya existe");
Toast.makeText(this, "Revise la validación de los campos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Registrar> call, Throwable t) {
Toast.makeText(this, "No se ha podido registrar el usuario", Toast.LENGTH_SHORT).show();
}
}
|
package net.selsela.almobarakeya.ui.orders;
import net.selsela.almobarakeya.data.model.order.Order;
import net.selsela.almobarakeya.ui.base.MvpView;
import java.util.List;
public interface OrdresMvpView extends MvpView {
void showOrders(List<Order> orders);
}
|
/* -*- Java -*-
*
* Copyright (c) 2008
* Spoken Language Systems Group
* MIT Computer Science and Artificial Intelligence Laboratory
* Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.mit.csail.sls.wami.applet.sound;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
/**
* Controls playing of audio
*
* Unless otherwise noted, methods are not thread-safe.
*
*/
class AudioPlayer implements Player {
protected volatile SourceDataLine line = null;
protected volatile boolean enabled = true; // Used for aborting play
protected volatile boolean playing = false; // Set when in play loop
protected int position = 0; // Number of bytes sent to line
protected volatile int startPosition = 0; // Start of segment
protected byte[] data = new byte[1024];
Converter currentConverter = null;
protected Mixer.Info preferredMixerInfo = null;
protected class Converter {
AudioFormat currentAudioFormat;
AudioFormat convertFormat;
AudioFormat lineFormat;
Converter(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
this.currentAudioFormat = currentAudioFormat;
this.convertFormat = convertFormat;
this.lineFormat = lineFormat;
}
boolean matches(AudioFormat desiredAudioFormat) {
return currentAudioFormat.matches(desiredAudioFormat);
}
int doSamples(AudioInputStream ais) throws IOException {
return ais.read(data);
}
}
// Converts 1-channel bytes to 2-channel bytes
protected class Converter1 extends Converter {
byte[] indata = new byte[data.length / 2];
Converter1(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
super(currentAudioFormat, convertFormat, lineFormat);
}
@Override
public int doSamples(AudioInputStream ais) throws IOException {
int n = ais.read(indata);
if (n < 0)
return n;
int j = 0;
for (int i = 0; i < n; i++) {
byte b = indata[i];
data[j++] = b;
data[j++] = b;
}
return n * 2;
}
}
// Converts 1-channel shorts to 2-channel shorts
protected class Converter2 extends Converter {
byte[] indata = new byte[data.length / 2];
Converter2(AudioFormat currentAudioFormat, AudioFormat convertFormat,
AudioFormat lineFormat) {
super(currentAudioFormat, convertFormat, lineFormat);
}
@Override
public int doSamples(AudioInputStream ais) throws IOException {
int n = ais.read(indata);
if (n < 0)
return n;
int j = 0;
for (int i = 0; i < n;) {
byte b0 = indata[i++];
byte b1 = indata[i++];
data[j++] = b0;
data[j++] = b1;
data[j++] = b0;
data[j++] = b1;
}
return n * 2;
}
}
LinkedList<Listener> listeners = new LinkedList<Listener>();
/**
* Add an event listener
*
* @param l
* The listener
*
*/
public void addListener(Listener l) {
listeners.add(l);
}
/**
* Remove an event listener
*
* @param l
* The listener
*
*/
public void removeListener(Listener l) {
listeners.remove(l);
}
void playingHasStarted() {
for (Listener listener : listeners) {
listener.playingHasStarted();
}
}
void playingHasEnded() {
for (Listener listener : listeners) {
listener.playingHasEnded();
}
}
/**
* Find the best conversion for a desired audio format
*
*/
Converter getConverter(AudioFormat desiredAudioFormat)
throws LineUnavailableException {
if (currentConverter != null
&& currentConverter.matches(desiredAudioFormat))
return currentConverter;
AudioFormat minFormat = null;
AudioFormatComparator comp = new AudioFormatComparator(
desiredAudioFormat) {
@Override
public int conversionCompare(AudioFormat f1, AudioFormat f2) {
boolean c1 = AudioSystem.isConversionSupported(f1,
desiredAudioFormat);
boolean c2 = AudioSystem.isConversionSupported(f2,
desiredAudioFormat);
if (c1) {
if (!c2) {
return -1;
}
} else if (!c2) {
return 1;
}
return 0;
}
};
// Hunt for the line that supports the format best
ArrayList<Mixer.Info> minfoList = new ArrayList<Mixer.Info>(Arrays
.asList(AudioSystem.getMixerInfo()));
if (preferredMixerInfo != null) {
minfoList.remove(preferredMixerInfo);
minfoList.add(0, preferredMixerInfo);
}
Mixer.Info[] minfo = minfoList
.toArray(new Mixer.Info[minfoList.size()]);
for (int i = 0; i < minfo.length; i++) {
Mixer mixer = AudioSystem.getMixer(minfo[i]);
Line.Info[] linfo = mixer.getSourceLineInfo();
for (int j = 0; j < linfo.length; j++) {
if (!(linfo[j] instanceof DataLine.Info)) {
// Port info doesn't tell us anything about formats
continue;
}
DataLine.Info dinfo = (DataLine.Info) linfo[j];
AudioFormat[] formats = dinfo.getFormats();
for (int k = 0; k < formats.length; k++) {
AudioFormat f = formats[k];
if (comp.compare(f, minFormat) == -1) {
minFormat = f;
}
}
}
}
AudioFormat lineFormat = minFormat;
if (lineFormat.getSampleRate() == AudioSystem.NOT_SPECIFIED) {
// A java sound feature: If all sample rates are supported,
// then AudioSystem.NOT_SPECIFIED may be returned
lineFormat = new AudioFormat(lineFormat.getEncoding(),
// +DSC
// Pretend we only have 16KHz
// 16000,
// -DSC
desiredAudioFormat.getSampleRate(), lineFormat
.getSampleSizeInBits(), lineFormat.getChannels(),
lineFormat.getFrameSize(), desiredAudioFormat
.getFrameRate(), lineFormat.isBigEndian());
}
AudioFormat clf = AudioFormatComparator.channelFormat(lineFormat,
desiredAudioFormat.getChannels());
AudioFormat convertFormat = AudioSystem.isConversionSupported(clf,
desiredAudioFormat) ? clf : desiredAudioFormat;
if (lineFormat.getChannels() == 2
&& desiredAudioFormat.getChannels() == 1) {
switch (convertFormat.getFrameSize()) {
case 1:
return new Converter1(desiredAudioFormat, convertFormat,
lineFormat);
case 2:
return new Converter2(desiredAudioFormat, convertFormat,
lineFormat);
default:
throw new LineUnavailableException("Cannot play "
+ desiredAudioFormat + " on audio device");
}
} else {
return new Converter(desiredAudioFormat, convertFormat, lineFormat);
}
}
/**
* Wait for playing to complete, and then close the line.
*
*/
public synchronized void closeLine() {
if (line == null)
return;
double padding = .3 * line.getFormat().getFrameRate()
* line.getFormat().getFrameSize();
int nbuffers = (int) ((padding + data.length - 1) / data.length);
for (int i = 0; i < nbuffers; i++) {
Arrays.fill(data, (byte) 0);
line.write(data, 0, data.length);
}
line.drain();
synchronized (this) {
line.close();
line = null;
}
}
/**
* Play the stream. This is the same as play(stream, true, true).
*
* @param stream
* The stream to play
*
*/
public void play(AudioInputStream stream) throws LineUnavailableException {
play(stream, true, true);
}
/**
* Play the stream
*
* @param stream
* The stream to play
*
* @param setStart
* If true, getFramePosition() will consider the start of
* this stream as frame 0, and playingHasStarted() will
* be called.
*
* @param last
* If true, playingHasEnded() will be called when playing
* stops.
*
*/
public void play(AudioInputStream stream, boolean setStart, boolean last)
throws LineUnavailableException {
AudioFormat desiredAudioFormat = stream.getFormat();
// Start by getting the right encoding
if (desiredAudioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
stream = AudioSystem.getAudioInputStream(
AudioFormat.Encoding.PCM_SIGNED, stream);
desiredAudioFormat = stream.getFormat();
}
currentConverter = getConverter(desiredAudioFormat);
// Convert stream
AudioInputStream ais = desiredAudioFormat
.matches(currentConverter.convertFormat) ? stream : AudioSystem
.getAudioInputStream(currentConverter.convertFormat, stream);
// System.err.println("Request for "+desiredAudioFormat);
// System.err.println("Converted to "+ais.getFormat());
// System.err.println("Line selected "+currentConverter.lineFormat);
if (ais.getFormat().getSampleRate() != currentConverter.lineFormat
.getSampleRate()) {
// TBD: Enhance the protocol so we can tell Galaxy what
// sampling rates can be used for synthesis. For now, just
// die informatively
if (2 * ais.getFormat().getSampleRate() == currentConverter.lineFormat
.getSampleRate()) {
play(new UpSample2(ais), setStart, last);
return;
}
System.out.println("Here we go...");
throw new LineUnavailableException(
"Audio device does not support a sampling rate of "
+ ais.getFormat().getSampleRate());
}
if (line != null) {
if (!line.getFormat().matches(currentConverter.lineFormat)) {
closeLine();
}
}
// Open line
if (line == null) {
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
currentConverter.lineFormat);
synchronized (this) {
try {
System.out.println("(player) preferred mixer is: "
+ preferredMixerInfo);
if (preferredMixerInfo != null) {
Mixer mixer = AudioSystem.getMixer(preferredMixerInfo);
try {
line = (SourceDataLine) mixer.getLine(info);
} catch (IllegalArgumentException e) {
// line not supported in this mixer, so try a
// different one
line = (SourceDataLine) AudioSystem.getLine(info);
}
} else {
line = (SourceDataLine) AudioSystem.getLine(info);
}
position = 0;
line.open(currentConverter.lineFormat);
line.start();
} catch (LineUnavailableException e) {
line = null;
throw e;
}
}
}
if (setStart) {
startPosition = position;
}
try {
synchronized (this) {
playing = true;
notifyAll();
}
if (setStart)
playingHasStarted();
while (true) {
synchronized (this) {
if (ais == null || line == null || !enabled)
break;
}
int n = -1;
try {
n = currentConverter.doSamples(ais);
} catch (IOException e) {
break;
}
if (n < 0) {
try {
ais.close();
} catch (IOException e) {
}
synchronized (this) {
notifyAll();
}
break;
} else {
position += n;
line.write(data, 0, n);
}
}
} finally {
synchronized (this) {
playing = false;
notifyAll();
}
if (last) {
closeLine();
playingHasEnded();
}
}
}
/**
* Returns true if in the play loop
*
*/
public synchronized boolean isPlaying() {
return playing;
}
/**
* Break out of playing
*
* Can be called from any thread
*/
public synchronized void stopPlaying() {
if (!playing)
return;
enabled = false;
while (playing) {
try {
wait();
} catch (InterruptedException e) {
}
}
enabled = true;
}
/**
* Return the frame position in the currently playing stream.
*
* Can be called from any thread
*
*/
public synchronized int getFramePosition() {
return line == null ? 0 : line.getFramePosition() - startPosition;
}
/**
* Returns the closest supported sample rate
*
*/
public int supportedSampleRate(int desiredSampleRate)
throws LineUnavailableException {
AudioFormat format = new AudioFormat((float) desiredSampleRate, 16, 2,
true, true);
Converter converter = getConverter(format);
return (int) converter.lineFormat.getSampleRate();
}
/**
* Set the preferred mixer to use to playback (note, not thread safe at
* the moment)
*/
public void setPreferredMixer(Mixer.Info mInfo) {
preferredMixerInfo = mInfo;
}
public void setPreferredMixer(String name){
for(Mixer.Info mi : AudioSystem.getMixerInfo()){
if (mi.getName().equals(name)){
setPreferredMixer(mi);
return;
}
}
}
public Mixer.Info getPreferredMixer() {
return preferredMixerInfo;
}
}
|
/*
* Copyright (c) 2019 flow.ci
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.flowci.core.common.manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component("eventManager")
public class SpringEventManager {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publish(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
|
/**
* Copyright (C) 2013 – 2015 SLUB Dresden & Avantgarde Labs GmbH (<code@dswarm.org>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dswarm.converter.morph;
import java.util.Map;
import java.util.Optional;
import com.google.common.collect.Iterators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.dswarm.converter.DMPConverterException;
import org.dswarm.persistence.model.job.Filter;
import org.dswarm.persistence.model.job.Task;
/**
* @author tgaengler
*/
public class FilterMorphScriptBuilder extends AbstractMorphScriptBuilder<FilterMorphScriptBuilder> {
private static final Logger LOG = LoggerFactory.getLogger(FilterMorphScriptBuilder.class);
private static final String SKIP_FILTER = "skip_filter_";
private static final String MF_ELEMENT_CONSTANT = "constant";
private static final String COMBINE_VALUE_VARIABLE = "out";
@Override public FilterMorphScriptBuilder apply(final Task task) throws DMPConverterException {
final Optional<Filter> optionalSkipFilter = Optional.ofNullable(task.getJob().getSkipFilter());
if (!optionalSkipFilter.isPresent()) {
LOG.debug("there is no skip filter at job '{}' of task '{}'", task.getJob().getUuid(), task.getUuid());
return this;
}
final Filter skipFilter = optionalSkipFilter.get();
final Optional<String> optionalSkipFilterExpression = Optional.ofNullable(skipFilter.getExpression());
if (!optionalSkipFilterExpression.isPresent()) {
LOG.debug("there is no filter expression in skip filter '{}' of job '{}' of task '{}'", skipFilter.getUuid(), task.getJob().getUuid(),
task.getUuid());
return this;
}
final String filterExpressionString = optionalSkipFilterExpression.get();
final Map<String, String> filterExpressionMap = extractFilterExpressions(filterExpressionString);
if (filterExpressionMap == null || filterExpressionMap.isEmpty()) {
LOG.debug("there are no filter conditions in filter expression in skip filter '{}' of job '{}' of task '{}'", skipFilter.getUuid(),
task.getJob().getUuid(), task.getUuid());
return this;
}
super.apply(task);
metaName.setTextContent(SKIP_FILTER + task.getJob().getUuid());
final String attributePathStringXMLEscaped = Iterators.getLast(filterExpressionMap.keySet().iterator());
addFilter(attributePathStringXMLEscaped, COMBINE_VALUE_VARIABLE, filterExpressionMap, rules, false);
return this;
}
@Override protected Element createFilterDataElement(final String variable, final String attributePathString) {
final Element combineAsFilterDataOut = doc.createElement(METAMORPH_ELEMENT_DATA);
combineAsFilterDataOut.setAttribute(METAMORPH_DATA_TARGET, variable);
combineAsFilterDataOut.setAttribute(METAMORPH_DATA_SOURCE, attributePathString);
final Element constantElement = doc.createElement(MF_ELEMENT_CONSTANT);
constantElement.setAttribute(MF_ELEMENT_VALUE_ATTRIBUTE_IDENTIFIER, BOOLEAN_VALUE_TRUE);
combineAsFilterDataOut.appendChild(constantElement);
return combineAsFilterDataOut;
}
}
|
package com.example.models.station;
import com.example.dtos.station.CityGateStationView;
import com.example.dtos.station.GasView;
import com.example.dtos.users.UserView;
import com.example.models.users.UserEntity;
import com.fasterxml.jackson.annotation.JsonView;
import core.hosSein.core.model.BaseEntity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "gas")
public class GasEntity extends BaseEntity {
private Double nitrogen;
private Double carbonDioxide;
private Double methan;
private Double ethane;
private Double propane;
private Double nButane;
private Double isoButane;
private Double nPentane;
private Double isoPentane;
private Double hexane;
private Double heptane;
private Double octane;
private Double nonane;
private Double decane;
private Double hydrogen;
private Double oxygen;
private Double carbonMonoxide;
private Double water;
private Double hydrogenSulfide;
private Double helium;
private Double argon;
private Boolean moleWightPersent;
private String name;
@JsonView
@ManyToOne
@JoinColumn(referencedColumnName = "id")
public CityGateStationEntity cityGateStation;
@JsonView
@OneToMany(mappedBy = "gas")
public List<CalculationEntity> calculationEntities;
@Basic
@Column(name = "carbon_dioxide")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "nitrogen")
public Double getNitrogen() {
return nitrogen;
}
public void setNitrogen(Double nitrogen) {
this.nitrogen = nitrogen;
}
@Basic
@Column(name = "carbon_dioxide")
public Double getCarbonDioxide() {
return carbonDioxide;
}
public void setCarbonDioxide(Double carbonDioxide) {
this.carbonDioxide = carbonDioxide;
}
@Basic
@Column(name = "methan")
public Double getMethan() {
return methan;
}
public void setMethan(Double methan) {
this.methan = methan;
}
@Basic
@Column(name = "ethane")
public Double getEthane() {
return ethane;
}
public void setEthane(Double ethane) {
this.ethane = ethane;
}
@Basic
@Column(name = "propane")
public Double getPropane() {
return propane;
}
public void setPropane(Double propane) {
this.propane = propane;
}
@Basic
@Column(name = "n_butane")
public Double getnButane() {
return nButane;
}
public void setnButane(Double nButane) {
this.nButane = nButane;
}
@Basic
@Column(name = "iso_butane")
public Double getIsoButane() {
return isoButane;
}
public void setIsoButane(Double isoButane) {
this.isoButane = isoButane;
}
@Basic
@Column(name = "n_pentane")
public Double getnPentane() {
return nPentane;
}
public void setnPentane(Double nPentane) {
this.nPentane = nPentane;
}
@Basic
@Column(name = "iso_pentane")
public Double getIsoPentane() {
return isoPentane;
}
public void setIsoPentane(Double isoPentane) {
this.isoPentane = isoPentane;
}
@Basic
@Column(name = "hexane")
public Double getHexane() {
return hexane;
}
public void setHexane(Double hexane) {
this.hexane = hexane;
}
@Basic
@Column(name = "heptane")
public Double getHeptane() {
return heptane;
}
public void setHeptane(Double heptane) {
this.heptane = heptane;
}
@Basic
@Column(name = "octane")
public Double getOctane() {
return octane;
}
public void setOctane(Double octane) {
this.octane = octane;
}
@Basic
@Column(name = "nonane")
public Double getNonane() {
return nonane;
}
public void setNonane(Double nonane) {
this.nonane = nonane;
}
@Basic
@Column(name = "decane")
public Double getDecane() {
return decane;
}
public void setDecane(Double decane) {
this.decane = decane;
}
@Basic
@Column(name = "hydrogen")
public Double getHydrogen() {
return hydrogen;
}
public void setHydrogen(Double hydrogen) {
this.hydrogen = hydrogen;
}
@Basic
@Column(name = "oxygen")
public Double getOxygen() {
return oxygen;
}
public void setOxygen(Double oxygen) {
this.oxygen = oxygen;
}
@Basic
@Column(name = "carbon_monoxide")
public Double getCarbonMonoxide() {
return carbonMonoxide;
}
public void setCarbonMonoxide(Double carbonMonoxide) {
this.carbonMonoxide = carbonMonoxide;
}
@Basic
@Column(name = "water")
public Double getWater() {
return water;
}
public void setWater(Double water) {
this.water = water;
}
@Basic
@Column(name = "hydrogen_sulfide")
public Double getHydrogenSulfide() {
return hydrogenSulfide;
}
public void setHydrogenSulfide(Double hydrogenSulfide) {
this.hydrogenSulfide = hydrogenSulfide;
}
@Basic
@Column(name = "helium")
public Double getHelium() {
return helium;
}
public void setHelium(Double helium) {
this.helium = helium;
}
@Basic
@Column(name = "argon")
public Double getArgon() {
return argon;
}
public void setArgon(Double argon) {
this.argon = argon;
}
@Column(name = "mole_wight_persent")
@NotNull
public Boolean isMoleWightPersent() {
if (moleWightPersent == null) {
return false;
}
return moleWightPersent;
}
public void setMoleWightPersent(Boolean moleWightPersent) {
this.moleWightPersent = moleWightPersent;
}
@Override
public int hashCode() {
return Objects.hash(id, nitrogen, carbonDioxide, methan, ethane, propane, nButane, isoButane, nPentane, isoPentane, hexane, heptane, octane, nonane, decane, hydrogen, oxygen, carbonMonoxide, water, hydrogenSulfide, helium, argon, moleWightPersent);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.jcache.interceptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.interceptor.AbstractCacheInvoker;
import org.springframework.cache.interceptor.BasicOperation;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.CacheOperationInvoker;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Base class for JSR-107 caching aspects, such as the {@link JCacheInterceptor}
* or an AspectJ aspect.
*
* <p>Use the Spring caching abstraction for cache-related operations. No JSR-107
* {@link javax.cache.Cache} or {@link javax.cache.CacheManager} are required to
* process standard JSR-107 cache annotations.
*
* <p>The {@link JCacheOperationSource} is used for determining caching operations
*
* <p>A cache aspect is serializable if its {@code JCacheOperationSource} is serializable.
*
* @author Stephane Nicoll
* @see org.springframework.cache.interceptor.CacheAspectSupport
* @see KeyGeneratorAdapter
* @see CacheResolverAdapter
* @since 4.1
*/
public class JCacheAspectSupport extends AbstractCacheInvoker implements InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
@Nullable
private JCacheOperationSource cacheOperationSource;
@Nullable
private CacheResultInterceptor cacheResultInterceptor;
@Nullable
private CachePutInterceptor cachePutInterceptor;
@Nullable
private CacheRemoveEntryInterceptor cacheRemoveEntryInterceptor;
@Nullable
private CacheRemoveAllInterceptor cacheRemoveAllInterceptor;
private boolean initialized = false;
/**
* Return the CacheOperationSource for this cache aspect.
*/
public JCacheOperationSource getCacheOperationSource() {
Assert.state(this.cacheOperationSource != null, "The 'cacheOperationSource' property is required: " +
"If there are no cacheable methods, then don't use a cache aspect.");
return this.cacheOperationSource;
}
/**
* Set the CacheOperationSource for this cache aspect.
*/
public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) {
Assert.notNull(cacheOperationSource, "JCacheOperationSource must not be null");
this.cacheOperationSource = cacheOperationSource;
}
public void afterPropertiesSet() {
getCacheOperationSource();
this.cacheResultInterceptor = new CacheResultInterceptor(getErrorHandler());
this.cachePutInterceptor = new CachePutInterceptor(getErrorHandler());
this.cacheRemoveEntryInterceptor = new CacheRemoveEntryInterceptor(getErrorHandler());
this.cacheRemoveAllInterceptor = new CacheRemoveAllInterceptor(getErrorHandler());
this.initialized = true;
}
@Nullable
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
// Check whether aspect is enabled to cope with cases where the AJ is pulled in automatically
if (this.initialized) {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
JCacheOperation<?> operation = getCacheOperationSource().getCacheOperation(method, targetClass);
if (operation != null) {
CacheOperationInvocationContext<?> context =
createCacheOperationInvocationContext(target, args, operation);
return execute(context, invoker);
}
}
return invoker.invoke();
}
@SuppressWarnings("unchecked")
private CacheOperationInvocationContext<?> createCacheOperationInvocationContext(
Object target, Object[] args, JCacheOperation<?> operation) {
return new DefaultCacheInvocationContext<>(
(JCacheOperation<Annotation>) operation, target, args);
}
@SuppressWarnings("unchecked")
@Nullable
private Object execute(CacheOperationInvocationContext<?> context, CacheOperationInvoker invoker) {
CacheOperationInvoker adapter = new CacheOperationInvokerAdapter(invoker);
BasicOperation operation = context.getOperation();
if (operation instanceof CacheResultOperation) {
Assert.state(this.cacheResultInterceptor != null, "No CacheResultInterceptor");
return this.cacheResultInterceptor.invoke(
(CacheOperationInvocationContext<CacheResultOperation>) context, adapter);
} else if (operation instanceof CachePutOperation) {
Assert.state(this.cachePutInterceptor != null, "No CachePutInterceptor");
return this.cachePutInterceptor.invoke(
(CacheOperationInvocationContext<CachePutOperation>) context, adapter);
} else if (operation instanceof CacheRemoveOperation) {
Assert.state(this.cacheRemoveEntryInterceptor != null, "No CacheRemoveEntryInterceptor");
return this.cacheRemoveEntryInterceptor.invoke(
(CacheOperationInvocationContext<CacheRemoveOperation>) context, adapter);
} else if (operation instanceof CacheRemoveAllOperation) {
Assert.state(this.cacheRemoveAllInterceptor != null, "No CacheRemoveAllInterceptor");
return this.cacheRemoveAllInterceptor.invoke(
(CacheOperationInvocationContext<CacheRemoveAllOperation>) context, adapter);
} else {
throw new IllegalArgumentException("Cannot handle " + operation);
}
}
/**
* Execute the underlying operation (typically in case of cache miss) and return
* the result of the invocation. If an exception occurs it will be wrapped in
* a {@code ThrowableWrapper}: the exception can be handled or modified but it
* <em>must</em> be wrapped in a {@code ThrowableWrapper} as well.
*
* @param invoker the invoker handling the operation being cached
* @return the result of the invocation
* @see CacheOperationInvoker#invoke()
*/
protected Object invokeOperation(CacheOperationInvoker invoker) {
return invoker.invoke();
}
private class CacheOperationInvokerAdapter implements CacheOperationInvoker {
private final CacheOperationInvoker delegate;
public CacheOperationInvokerAdapter(CacheOperationInvoker delegate) {
this.delegate = delegate;
}
@Override
public Object invoke() throws ThrowableWrapper {
return invokeOperation(this.delegate);
}
}
}
|
package mage.cards.f;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.TapTargetCost;
import mage.abilities.effects.common.PreventDamageToTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.filter.predicate.Predicates;
import mage.filter.predicate.permanent.TappedPredicate;
import mage.target.common.TargetControlledCreaturePermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author LoneFox
*/
public final class FieldSurgeon extends CardImpl {
private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("an untapped creature you control");
static {
filter.add(Predicates.not(new TappedPredicate()));
}
public FieldSurgeon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.CLERIC);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// Tap an untapped creature you control: Prevent the next 1 damage that would be dealt to target creature this turn.
Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new PreventDamageToTargetEffect(Duration.EndOfTurn, 1),
new TapTargetCost(new TapTargetCost(new TargetControlledCreaturePermanent(filter))));
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
}
public FieldSurgeon(final FieldSurgeon card) {
super(card);
}
@Override
public FieldSurgeon copy() {
return new FieldSurgeon(this);
}
}
|
/*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf;
import net.hasor.core.BindInfo;
import net.hasor.rsf.domain.RsfServiceType;
import java.util.Set;
/**
* Rsf绑定信息。
* @version : 2014年11月12日
* @author 赵永春(zyc@hasor.net)
*/
public interface RsfBindInfo<T> extends BindInfo<T> {
/** @return 唯一标识(客户端唯一标识)。*/
public String getBindID();
/** @return 服务名称。*/
public String getBindName();
/** @return 获取已经定义的别名 */
public Set<String> getAliasTypes();
/** @return 别名 */
public String getAliasName(String aliasType);
/** @return 服务分组。*/
public String getBindGroup();
/** @return 服务版本。*/
public String getBindVersion();
/** @return 注册的服务类型。*/
public Class<T> getBindType();
/**是提供者还是消费者*/
public RsfServiceType getServiceType();
/**
* 返回接口是否为一个 Message 接口。
* @see RsfMessage
*/
public boolean isMessage();
/** 接口是否要求工作在隐藏模式下。*/
public boolean isShadow();
/** @return 获取客户端调用服务超时时间。*/
public int getClientTimeout();
/** @return 获取序列化方式*/
public String getSerializeType();
/** 服务的执行线程池是否为共享线程池。 */
public boolean isSharedThreadPool();
}
|
/*
* (c) Copyright 2017 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.remoting3.servers.jersey;
import com.google.common.base.Strings;
import com.palantir.remoting.api.tracing.Span;
import com.palantir.remoting.api.tracing.SpanType;
import com.palantir.remoting.api.tracing.TraceHttpHeaders;
import com.palantir.remoting3.tracing.Tracer;
import com.palantir.remoting3.tracing.Tracers;
import java.io.IOException;
import java.util.Optional;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ExtendedUriInfo;
import org.glassfish.jersey.server.model.Resource;
@Provider
public final class TraceEnrichingFilter implements ContainerRequestFilter, ContainerResponseFilter {
public static final TraceEnrichingFilter INSTANCE = new TraceEnrichingFilter();
@Context
private ExtendedUriInfo uriInfo;
// Handles incoming request
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String path = Optional.ofNullable(uriInfo)
.map(ExtendedUriInfo::getMatchedModelResource)
.map(Resource::getPath)
.orElse("(unknown)");
String operation = requestContext.getMethod() + " " + path;
// The following strings are all nullable
String traceId = requestContext.getHeaderString(TraceHttpHeaders.TRACE_ID);
String spanId = requestContext.getHeaderString(TraceHttpHeaders.SPAN_ID);
// Set up thread-local span that inherits state from HTTP headers
if (Strings.isNullOrEmpty(traceId)) {
// HTTP request did not indicate a trace; initialize trace state and create a span.
Tracer.initTrace(hasSampledHeader(requestContext), Tracers.randomId());
Tracer.startSpan(operation, SpanType.SERVER_INCOMING);
} else {
Tracer.initTrace(hasSampledHeader(requestContext), traceId);
if (spanId == null) {
Tracer.startSpan(operation, SpanType.SERVER_INCOMING);
} else {
// caller's span is this span's parent.
Tracer.startSpan(operation, spanId, SpanType.SERVER_INCOMING);
}
}
// Give asynchronous downstream handlers access to the trace id
requestContext.setProperty("com.palantir.remoting3.traceId", Tracer.getTraceId());
}
// Handles outgoing response
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
Optional<Span> maybeSpan = Tracer.completeSpan();
if (maybeSpan.isPresent()) {
Span span = maybeSpan.get();
headers.putSingle(TraceHttpHeaders.TRACE_ID, span.getTraceId());
}
}
// Returns true iff the context contains a "1" X-B3-Sampled header, or absent if there is no such header.
private static Optional<Boolean> hasSampledHeader(ContainerRequestContext context) {
String header = context.getHeaderString(TraceHttpHeaders.IS_SAMPLED);
if (header == null) {
return Optional.empty();
} else {
return Optional.of(header.equals("1"));
}
}
}
|
package com.example.yhao.floatwindow;
import android.content.Context;
import androidx.appcompat.widget.AppCompatImageView;
import android.util.AttributeSet;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义悬浮的ImageView
*
* @author xxl.
* @date 2020/01/02.
*/
public class FloatingImageView extends AppCompatImageView {
//region:成员变量
private List<ConversationEntity> mConversationEntities = new ArrayList<>();
//endregion
//region: 构造函数
public FloatingImageView(Context context) {
super(context);
}
public FloatingImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FloatingImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//endregion
//region: get or set
/**
* 设置会话实体
*
* @param conversationEntity
*/
public void addConversationEntity(ConversationEntity conversationEntity) {
if (mConversationEntities.contains(conversationEntity)) {
return;
}
mConversationEntities.add(conversationEntity);
}
/**
* 获取会话实体
*
* @return
*/
public List<ConversationEntity> getConversationEntities() {
return mConversationEntities;
}
//endregion
}
|
package de.adorsys.opba.starter;
import de.adorsys.opba.api.security.external.service.RequestSigningService;
import de.adorsys.opba.api.security.generator.api.DataToSignProvider;
import de.adorsys.opba.api.security.generator.api.RequestToSign;
import de.adorsys.opba.api.security.requestsigner.OpenBankingDataToSignProvider;
import de.adorsys.opba.protocol.api.dto.result.fromprotocol.dialog.AuthorizationRequiredResult;
import de.adorsys.opba.protocol.xs2a.entrypoint.ais.Xs2aListAccountsEntrypoint;
import de.adorsys.opba.protocol.xs2a.entrypoint.ais.Xs2aSandboxListTransactionsEntrypoint;
import de.adorsys.opba.protocol.xs2a.entrypoint.pis.Xs2aGetPaymentStatusEntrypoint;
import de.adorsys.opba.protocol.xs2a.entrypoint.pis.Xs2aInitiateSinglePaymentEntrypoint;
import de.adorsys.opba.protocol.xs2a.tests.e2e.stages.CommonGivenStages;
import de.adorsys.opba.starter.config.FintechRequestSigningTestConfig;
import de.adorsys.xs2a.adapter.adapter.StandardPaymentProduct;
import io.restassured.RestAssured;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.testcontainers.shaded.com.google.common.io.Resources;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static de.adorsys.opba.protocol.xs2a.tests.HeaderNames.X_REQUEST_SIGNATURE;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.PaymentStagesCommonUtil.withPaymentHeaders;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.AIS_ACCOUNTS_ENDPOINT;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.AIS_TRANSACTIONS_ENDPOINT;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.ANTON_BRUECKNER;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.PIS_PAYMENT_STATUS_ENDPOINT;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.PIS_SINGLE_PAYMENT_ENDPOINT;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.withAccountsHeaders;
import static de.adorsys.opba.protocol.xs2a.tests.e2e.stages.StagesCommonUtil.withTransactionsHeaders;
import static de.adorsys.opba.restapi.shared.HttpHeaders.SERVICE_SESSION_ID;
import static io.restassured.RestAssured.config;
import static io.restassured.config.RedirectConfig.redirectConfig;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* This is a very basic test to ensure application starts up and components are bundled properly.
* Protocols are tested in their own packages exhaustively.
*/
@ActiveProfiles("test")
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@SpringBootTest(classes = {OpenBankingEmbeddedApplication.class, FintechRequestSigningTestConfig.class}, webEnvironment = RANDOM_PORT)
class BasicOpenBankingStartupTest {
@SpyBean
private Xs2aListAccountsEntrypoint xs2aListAccountsEntrypoint;
@SpyBean
private Xs2aSandboxListTransactionsEntrypoint xs2aListTransactionsEntrypoint;
@SpyBean
private Xs2aInitiateSinglePaymentEntrypoint xs2aInitiateSinglePaymentEntrypoint;
@MockBean
private Xs2aGetPaymentStatusEntrypoint xs2aGetPaymentStatusEntrypoint;
@Autowired
private RequestSigningService signingService;
@LocalServerPort
private int serverPort;
@BeforeEach
void setupRestAssured() {
RestAssured.baseURI = "http://localhost:" + serverPort;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
config = config().redirect(redirectConfig().followRedirects(false));
RestAssured.replaceFiltersWith(new CommonGivenStages.RequestSigner(signingService, new OpenBankingDataToSignProvider()));
}
@Test
void testAppStartsUp() {
// NOP - just test that context loads OK
}
@Test
void testXs2aProtocolIsWiredForSandboxAccountList() {
xs2aAccountList(HttpStatus.ACCEPTED);
verify(xs2aListAccountsEntrypoint).execute(any());
}
@Test
void testXs2aProtocolIsWiredForSandboxTransactionList() {
xs2aTransactionList(HttpStatus.ACCEPTED);
verify(xs2aListTransactionsEntrypoint).execute(any());
}
@Test
void testXs2aProtocolIsWiredForPaymentsGetStatus() {
xs2aPaymentStatusGet(HttpStatus.ACCEPTED);
verify(xs2aGetPaymentStatusEntrypoint).execute(any());
}
@Test
void testXs2aProtocolIsWiredForPayments() {
xs2aPaymentCreate(HttpStatus.ACCEPTED);
verify(xs2aInitiateSinglePaymentEntrypoint).execute(any());
}
@Test
void testCorrectSignatureRequiredForSandboxAccountList() {
RestAssured.replaceFiltersWith(new SignatureHashTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aAccountList(HttpStatus.NOT_FOUND);
RestAssured.replaceFiltersWith(new NaiveSignatureTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aAccountList(HttpStatus.NOT_FOUND);
verify(xs2aListAccountsEntrypoint, never()).execute(any());
}
@Test
void testCorrectSignatureRequiredForTransactionList() {
RestAssured.replaceFiltersWith(new SignatureHashTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aTransactionList(HttpStatus.NOT_FOUND);
RestAssured.replaceFiltersWith(new NaiveSignatureTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aTransactionList(HttpStatus.NOT_FOUND);
verify(xs2aListTransactionsEntrypoint, never()).execute(any());
}
@Test
void testCorrectSignatureRequiredForPaymentsGetStatus() {
RestAssured.replaceFiltersWith(new SignatureHashTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aPaymentStatusGet(HttpStatus.NOT_FOUND);
RestAssured.replaceFiltersWith(new NaiveSignatureTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aPaymentStatusGet(HttpStatus.NOT_FOUND);
verify(xs2aGetPaymentStatusEntrypoint, never()).execute(any());
}
@Test
void testCorrectSignatureRequiredForPayments() {
RestAssured.replaceFiltersWith(new SignatureHashTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aPaymentCreate(HttpStatus.NOT_FOUND);
RestAssured.replaceFiltersWith(new NaiveSignatureTamperer(signingService, new OpenBankingDataToSignProvider()));
xs2aPaymentCreate(HttpStatus.NOT_FOUND);
verify(xs2aInitiateSinglePaymentEntrypoint, never()).execute(any());
}
private void xs2aAccountList(HttpStatus expected) {
withAccountsHeaders(ANTON_BRUECKNER)
.header(SERVICE_SESSION_ID, UUID.randomUUID().toString())
.when()
.get(AIS_ACCOUNTS_ENDPOINT)
.then()
.statusCode(expected.value());
}
private void xs2aTransactionList(HttpStatus expected) {
withTransactionsHeaders(ANTON_BRUECKNER)
.header(SERVICE_SESSION_ID, UUID.randomUUID().toString())
.when()
.get(AIS_TRANSACTIONS_ENDPOINT, "ACCOUNT-1")
.then()
.statusCode(expected.value());
}
private void xs2aPaymentStatusGet(HttpStatus expected) {
when(xs2aGetPaymentStatusEntrypoint.execute(any()))
.thenReturn(CompletableFuture.completedFuture(new AuthorizationRequiredResult<>(URI.create(""), null)));
withPaymentHeaders(ANTON_BRUECKNER)
.header(SERVICE_SESSION_ID, UUID.randomUUID().toString())
.when()
.contentType(ContentType.JSON.withCharset(StandardCharsets.UTF_8))
.get(PIS_PAYMENT_STATUS_ENDPOINT, StandardPaymentProduct.SEPA_CREDIT_TRANSFERS.getSlug())
.then()
.statusCode(expected.value());
}
private void xs2aPaymentCreate(HttpStatus expected) {
withPaymentHeaders(ANTON_BRUECKNER)
.header(SERVICE_SESSION_ID, UUID.randomUUID().toString())
.when()
.contentType(ContentType.JSON.withCharset(StandardCharsets.UTF_8))
.body(getPaymentBodyStub())
.post(PIS_SINGLE_PAYMENT_ENDPOINT, StandardPaymentProduct.SEPA_CREDIT_TRANSFERS.getSlug())
.then()
.statusCode(expected.value());
}
@SneakyThrows
private String getPaymentBodyStub() {
return Resources.asCharSource(Resources.getResource("anton-brueckner-single-sepa-payment.json"), StandardCharsets.UTF_8).read();
}
@RequiredArgsConstructor
public static class SignatureHashTamperer implements Filter {
private final RequestSigningService signingService;
private final DataToSignProvider dataToSignProvider;
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
RequestToSign toSign = computeRequestToSign(requestSpec);
String signature = dataToSignProvider.normalizerFor(toSign).canonicalStringToSign(toSign) + "1234";
requestSpec = requestSpec.replaceHeader(X_REQUEST_SIGNATURE, signingService.signature(signature));
return ctx.next(requestSpec, responseSpec);
}
}
@RequiredArgsConstructor
public static class NaiveSignatureTamperer implements Filter {
private final RequestSigningService signingService;
private final DataToSignProvider dataToSignProvider;
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
RequestToSign toSign = computeRequestToSign(requestSpec);
String signature = dataToSignProvider.normalizerFor(toSign).canonicalStringToSign(toSign);
requestSpec = requestSpec.replaceHeader(X_REQUEST_SIGNATURE, signingService.signature(signature).replaceAll("A", "B"));
return ctx.next(requestSpec, responseSpec);
}
}
private static RequestToSign computeRequestToSign(FilterableRequestSpecification requestSpec) {
Map<String, String> headers = requestSpec.getHeaders().asList().stream()
.collect(Collectors.toMap(Header::getName, Header::getValue, (old, newer) -> newer, HashMap::new));
return RequestToSign.builder()
.method(DataToSignProvider.HttpMethod.valueOf(requestSpec.getMethod()))
.path(requestSpec.getDerivedPath())
.headers(headers)
.queryParams(requestSpec.getQueryParams())
.body(requestSpec.getBody())
.build();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.spatial.prefix;
import static org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree.UnitNRShape;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.search.DoubleValuesSource;
import org.apache.lucene.spatial.prefix.tree.Cell;
import org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree;
import org.apache.lucene.util.Bits;
import org.locationtech.spatial4j.shape.Point;
import org.locationtech.spatial4j.shape.Shape;
/**
* A PrefixTree based on Number/Date ranges. This isn't very "spatial" on the surface (to the user)
* but it's implemented using spatial so that's why it's here extending a SpatialStrategy. When
* using this class, you will use various utility methods on the prefix tree implementation to
* convert objects/strings to/from shapes.
*
* <p>To use with dates, pass in {@link org.apache.lucene.spatial.prefix.tree.DateRangePrefixTree}.
*
* @lucene.experimental
*/
public class NumberRangePrefixTreeStrategy extends RecursivePrefixTreeStrategy {
public NumberRangePrefixTreeStrategy(NumberRangePrefixTree prefixTree, String fieldName) {
super(prefixTree, fieldName);
setPruneLeafyBranches(false);
setPrefixGridScanLevel(prefixTree.getMaxLevels() - 2); // user might want to change, however
setPointsOnly(false);
setDistErrPct(0);
}
@Override
public NumberRangePrefixTree getGrid() {
return (NumberRangePrefixTree) super.getGrid();
}
@Override
protected boolean isPointShape(Shape shape) {
if (shape instanceof NumberRangePrefixTree.UnitNRShape) {
return ((NumberRangePrefixTree.UnitNRShape) shape).getLevel() == grid.getMaxLevels();
} else {
return false;
}
}
@Override
protected boolean isGridAlignedShape(Shape shape) {
// any UnitNRShape other than the world is a single cell/term
if (shape instanceof NumberRangePrefixTree.UnitNRShape) {
return ((NumberRangePrefixTree.UnitNRShape) shape).getLevel() > 0;
} else {
return false;
}
}
/** Unsupported. */
@Override
public DoubleValuesSource makeDistanceValueSource(Point queryPoint, double multiplier) {
throw new UnsupportedOperationException();
}
/**
* Calculates facets between {@code start} and {@code end} to a detail level one greater than that
* provided by the arguments. For example providing March to October of 2014 would return facets
* to the day level of those months. This is just a convenience method.
*
* @see #calcFacets(IndexReaderContext, Bits, Shape, int)
*/
public Facets calcFacets(
IndexReaderContext context, Bits topAcceptDocs, UnitNRShape start, UnitNRShape end)
throws IOException {
Shape facetRange = getGrid().toRangeShape(start, end);
int detailLevel = Math.max(start.getLevel(), end.getLevel()) + 1;
return calcFacets(context, topAcceptDocs, facetRange, detailLevel);
}
/**
* Calculates facets (aggregated counts) given a range shape (start-end span) and a level, which
* specifies the detail. To get the level of an existing shape, say a Calendar, call {@link
* org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree#toUnitShape(Object)} then call
* {@link org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree.UnitNRShape#getLevel()}.
* Facet computation is implemented by navigating the underlying indexed terms efficiently.
*/
public Facets calcFacets(
IndexReaderContext context, Bits topAcceptDocs, Shape facetRange, final int level)
throws IOException {
final Facets facets = new Facets(level);
PrefixTreeFacetCounter.compute(
this,
context,
topAcceptDocs,
facetRange,
level,
new PrefixTreeFacetCounter.FacetVisitor() {
Facets.FacetParentVal parentFacet;
UnitNRShape parentShape;
@Override
public void visit(Cell cell, int count) {
if (cell.getLevel()
< level - 1) { // some ancestor of parent facet level, direct or distant
parentFacet = null; // reset
parentShape = null; // reset
facets.topLeaves += count;
} else if (cell.getLevel() == level - 1) { // parent
// set up FacetParentVal
setupParent((UnitNRShape) cell.getShape());
parentFacet.parentLeaves += count;
} else { // at facet level
UnitNRShape unitShape = (UnitNRShape) cell.getShape();
UnitNRShape unitShapeParent = unitShape.getShapeAtLevel(unitShape.getLevel() - 1);
if (parentFacet == null || !parentShape.equals(unitShapeParent)) {
setupParent(unitShapeParent);
}
// lazy init childCounts
if (parentFacet.childCounts == null) {
parentFacet.childCounts = new int[parentFacet.childCountsLen];
}
parentFacet.childCounts[unitShape.getValAtLevel(cell.getLevel())] += count;
}
}
private void setupParent(UnitNRShape unitShape) {
parentShape = unitShape.clone();
// Look for existing parentFacet (from previous segment), or create anew if needed
parentFacet = facets.parents.get(parentShape);
if (parentFacet == null) { // didn't find one; make a new one
parentFacet = new Facets.FacetParentVal();
parentFacet.childCountsLen = getGrid().getNumSubCells(parentShape);
facets.parents.put(parentShape, parentFacet);
}
}
});
return facets;
}
/** Facet response information */
public static class Facets {
// TODO consider a variable-level structure -- more general purpose.
public Facets(int detailLevel) {
this.detailLevel = detailLevel;
}
/** The bottom-most detail-level counted, as requested. */
public final int detailLevel;
/**
* The count of documents with ranges that completely spanned the parents of the detail level.
* In more technical terms, this is the count of leaf cells 2 up and higher from the bottom.
* Usually you only care about counts at detailLevel, and so you will add this number to all
* other counts below, including to omitted/implied children counts of 0. If there are no
* indexed ranges (just instances, i.e. fully specified dates) then this value will always be 0.
*/
public int topLeaves;
/**
* Holds all the {@link FacetParentVal} instances in order of the key. This is sparse; there
* won't be an instance if it's count and children are all 0. The keys are {@link
* org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree.UnitNRShape} shapes, which can be
* converted back to the original Object (i.e. a Calendar) via {@link
* NumberRangePrefixTree#toObject(org.apache.lucene.spatial.prefix.tree.NumberRangePrefixTree.UnitNRShape)}.
*/
public final SortedMap<UnitNRShape, FacetParentVal> parents = new TreeMap<>();
/** Holds a block of detailLevel counts aggregated to their parent level. */
public static class FacetParentVal {
/**
* The count of ranges that span all of the childCounts. In more technical terms, this is the
* number of leaf cells found at this parent. Treat this like {@link Facets#topLeaves}.
*/
public int parentLeaves;
/**
* The length of {@link #childCounts}. If childCounts is not null then this is
* childCounts.length, otherwise it says how long it would have been if it weren't null.
*/
public int childCountsLen;
/**
* The detail level counts. It will be null if there are none, and thus they are assumed 0.
* Most apps, when presenting the information, will add {@link #topLeaves} and {@link
* #parentLeaves} to each count.
*/
public int[] childCounts;
// assert childCountsLen == childCounts.length
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(2048);
buf.append("Facets: level=")
.append(detailLevel)
.append(" topLeaves=")
.append(topLeaves)
.append(" parentCount=")
.append(parents.size());
for (Map.Entry<UnitNRShape, FacetParentVal> entry : parents.entrySet()) {
buf.append('\n');
if (buf.length() > 1000) {
buf.append("...");
break;
}
final FacetParentVal pVal = entry.getValue();
buf.append(' ').append(entry.getKey()).append(" leafCount=").append(pVal.parentLeaves);
if (pVal.childCounts != null) {
buf.append(' ').append(Arrays.toString(pVal.childCounts));
}
}
return buf.toString();
}
}
}
|
package com.builtbroken.breadstone.common.item;
import com.builtbroken.breadstone.BreadStoneMod;
import net.minecraft.item.ItemHoe;
public class ItemStaleBreadHoe extends ItemHoe {
public ItemStaleBreadHoe() {
super(ToolMaterial.STONE);
this.setRegistryName("stalebreadhoe");
this.setTranslationKey("stalebreadhoe");
this.setCreativeTab(BreadStoneMod.tab);
}
}
|
package com.douglaswhitehead.model.digitaldata;
import com.douglaswhitehead.model.digitaldata.cart.Cart;
import com.douglaswhitehead.model.digitaldata.component.Component;
import com.douglaswhitehead.model.digitaldata.event.Event;
import com.douglaswhitehead.model.digitaldata.page.Page;
import com.douglaswhitehead.model.digitaldata.privacy.Privacy;
import com.douglaswhitehead.model.digitaldata.product.Product;
import com.douglaswhitehead.model.digitaldata.transaction.Transaction;
import com.douglaswhitehead.model.digitaldata.user.User;
/**
* <p>DigitalData interface.</p>
*
* <p>From the W3C CEDDL specification:</p>
*
* <p>6. The Customer Experience Digital Data Object</p>
*
* <p>This section carries the core specification.</p>
*
* <p>
* Use of this specification can be adapted to specific cases, since the objects in the specification
* can be included or omitted as necessary or desired. None of the objects in this specification are
* required, but where objects are included they MUST conform to the Object Names and Types
* listed here.
* </p>
*
* <p>6.1 The Root JavaScript Object</p>
*
* <p>
* The root JavaScript Object (JSO) MUST be <tt>digitalData</tt>, and all data properties within this
* specification MUST fall within the hierarchy of the <tt>digitalData</tt> object.
* </p>
*
* <p>The following sub-objects are defined as children of the <tt>digitalData</tt> object.</p>
*
* <p>
* <ul>
* <li><tt>digitalData.pageInstanceID</tt></li>
* <li><tt>digitalData.page</tt></li>
* <li><tt>digitalData.product[n]</tt></li>
* <li><tt>digitalData.cart</tt></li>
* <li><tt>digitalData.transaction</tt></li>
* <li><tt>digitalData.event[n]</tt></li>
* <li><tt>digitalData.component[n]</tt></li>
* <li><tt>digitalData.user[n]</tt></li>
* <li><tt>digitalData.privacy</tt></li>
* <li><tt>digitalData.version</tt></li>
* </ul>
* </p>
*
* <p>The following subsections detail each of these sub-objects.</p>
*/
public interface DigitalData {
/**
* Returns the PageInstanceID object.
*
* @return String
*/
public String getPageInstanceID();
/**
* Returns the Page object.
*
* @return Page
*/
public Page getPage();
/**
* Returns the Product array.
*
* @return Product[]
*/
public Product[] getProduct();
/**
* Returns the Cart object.
*
* @return Cart
*/
public Cart getCart();
/**
* Returns the Transaction object.
*
* @return Transaction
*/
public Transaction getTransaction();
/**
* Returns the Event[] array.
*
* @return Event[]
*/
public Event[] getEvent();
/**
* Returns the Component array.
*
* @return Component[]
*/
public Component[] getComponent();
/**
* Returns the User array.
*
* @return User[]
*/
public User[] getUser();
/**
* Returns the Privacy object.
*
* @return Privacy
*/
public Privacy getPrivacy();
/**
* Returns the Version object.
*
* @return String
*/
public String getVersion();
/**
* DigitalData.Builder inner interface.
*
* @author douglas.whitehead
*
*/
public static interface Builder {
/**
* Builds the PageInstanceID object.
*
* @param String pageInstanceID
* @return Builder
*/
public Builder pageInstanceID(String pageInstanceID);
/**
* Builds the Page object.
*
* @param Page page
* @return Builder
*/
public Builder page(Page page);
/**
* Builds the Product array.
*
* @param Product[] product
* @return Builder
*/
public Builder product(Product[] product);
/**
* Builds the Cart object.
*
* @param Cart cart
* @return Builder
*/
public Builder cart(Cart cart);
/**
* Builds the Transaction object.
*
* @param Transaction transaction
* @return Builder
*/
public Builder transaction(Transaction transaction);
/**
* Builds the Event array.
*
* @param Event[] event
* @return Builder
*/
public Builder event(Event[] event);
/**
* Builds the Component array.
*
* @param Component[] component
* @return Builder
*/
public Builder component(Component[] component);
/**
* Builds the User array.
*
* @param User[] user
* @return Builder
*/
public Builder user(User[] user);
/**
* Builds the Privacy object.
*
* @param Privacy privacy
* @return Builder
*/
public Builder privacy(Privacy privacy);
/**
* Builds the Version object.
*
* @param String version
* @return Builder
*/
public Builder version(String version);
/**
* Builds and returns the DigitalData object.
*
* @return Builder
*/
public DigitalData build();
}
}
|
package me.purplesmp.ojs05.hideandseek.utilities;
import com.google.common.collect.ImmutableList;
import lombok.Getter;
import me.purplesmp.ojs05.hideandseek.HideAndSeek;
import me.purplesmp.ojs05.hideandseek.objects.HSPlayer;
import me.purplesmp.ojs05.hideandseek.objects.HSTeam;
import net.minecraft.network.MessageType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Formatting;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class GameManager {
private static final ThreadLocalRandom random = ThreadLocalRandom.current();
public static ThreadLocalRandom getRandom() {
return random;
}
private HSTeam hiders;
public HSTeam getHiders() {
return hiders;
}
private HSTeam seekers;
public HSTeam getSeekers() {
return seekers;
}
private boolean gameRunning;
public boolean isGameRunning() {
return gameRunning;
}
private boolean canHidersJoin;
public boolean isCanHidersJoin() {
return canHidersJoin;
}
@Getter
private int gameLength;
@Getter
private final List<ScheduledFuture> taskList = new ArrayList<>();
@Getter
private final List<UUID> exemptPlayers = new ArrayList<>();
public void setupGame() {
this.hiders = new HSTeam("Hider", TeamType.HIDER);
this.seekers = new HSTeam("Seeker", TeamType.SEEKER);
this.gameRunning = false;
this.gameLength = 15;
Config.getExemptPlayerList().forEach(uuidString -> {
UUID uuid = UUID.fromString(uuidString);
exemptPlayers.add(uuid);
});
}
public void createGame(ServerCommandSource context) {
if (this.gameRunning) return;
ImmutableList<ServerPlayerEntity> onlinePlayers = ImmutableList.copyOf(context.getServer().getPlayerManager().getPlayerList());
ServerPlayerEntity randomPlayer = onlinePlayers.get(random.nextInt(onlinePlayers.size()));
HSPlayer randomHsPlayer = HSPlayer.getExact(randomPlayer.getUuid());
randomHsPlayer.setCurrentTeam(seekers, false);
onlinePlayers.forEach(player -> {
HSPlayer hsPlayer = HSPlayer.getExact(player.getUuid());
if (hsPlayer.getCurrentTeam() == null && !hsPlayer.isExempt()) hsPlayer.setCurrentTeam(hiders, false);
});
this.gameRunning = true;
this.canHidersJoin = true;
taskList.add(HideAndSeek.getScheduler().schedule(() -> {
this.canHidersJoin = false;
}, 2, TimeUnit.MINUTES));
taskList.add(HideAndSeek.getScheduler().schedule(this::finishGame, gameLength, TimeUnit.MINUTES));
taskList.add(HideAndSeek.getScheduler().schedule(() -> {
HideAndSeek.getServer().getPlayerManager().broadcastChatMessage(new LiteralText(Formatting.AQUA + "The hiders have won!"), MessageType.CHAT, HideAndSeek.getServer().getPlayerManager().getPlayer("OJS05").getUuid());
}, 899, TimeUnit.SECONDS));
}
public void calculateWinner() {
int hiderSize = hiders.getMembers().size();
if (hiderSize == 0) {
HideAndSeek.getInstance().getGameManager().getSeekers().getMembers().forEach(seeker -> {
ServerPlayerEntity player = HideAndSeek.getServer().getPlayerManager().getPlayer(seeker.getUuid());
player.sendMessage(new LiteralText(Formatting.RED + "The seekers have won!"),true);
});
finishGame();
}
}
public void finishGame() {
hiders.getMembers().clear();
seekers.getMembers().clear();
HSPlayer.getHsPlayerMap().values().forEach(hsPlayer -> hsPlayer.setCurrentTeam(null, false));
this.gameRunning = false;
taskList.forEach(scheduledFuture -> {
if (!scheduledFuture.isCancelled()) scheduledFuture.cancel(true);
});
}
}
|
/*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.druid.metadata;
import com.google.common.base.Supplier;
import io.druid.metadata.storage.derby.DerbyConnector;
import org.junit.Assert;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException;
import java.sql.SQLException;
public class TestDerbyConnector extends DerbyConnector
{
public TestDerbyConnector(
Supplier<MetadataStorageConnectorConfig> config,
Supplier<MetadataStorageTablesConfig> dbTables
)
{
super(config, dbTables, new DBI("jdbc:derby:memory:druidTest;create=true"));
}
public void tearDown()
{
try {
new DBI("jdbc:derby:memory:druidTest;drop=true").open().close();
} catch(UnableToObtainConnectionException e) {
SQLException cause = (SQLException) e.getCause();
// error code "08006" indicates proper shutdown
Assert.assertEquals("08006", cause.getSQLState());
}
}
}
|
package com.projectomega.main.packets.types;
import com.projectomega.main.game.Player;
import com.projectomega.main.game.entity.Entity;
import com.projectomega.main.packets.OutboundPacket;
import com.projectomega.main.packets.PacketType;
import com.projectomega.main.packets.datatype.MetaData;
import com.projectomega.main.packets.datatype.VarInt;
public class PacketEntityMetaData extends OutboundPacket {
public PacketEntityMetaData(Player player, Entity entity, MetaData metaData) {
super(PacketType.ENTITY_METADATA,player.getProtocolVersion(), new VarInt(entity.getEntityID()), metaData);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.util.fst;
import java.util.Arrays;
import java.util.Random;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TimeUnits;
import org.apache.lucene.util.packed.PackedInts;
import org.junit.Ignore;
import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
@Ignore("Requires tons of heap to run (30 GB hits OOME but 35 GB passes after ~4.5 hours)")
@TimeoutSuite(millis = 100 * TimeUnits.HOUR)
public class Test2BFST extends LuceneTestCase {
private static long LIMIT = 3L*1024*1024*1024;
public void test() throws Exception {
int[] ints = new int[7];
IntsRef input = new IntsRef(ints, 0, ints.length);
long seed = random().nextLong();
Directory dir = new MMapDirectory(createTempDir("2BFST"));
for(int doPackIter=0;doPackIter<2;doPackIter++) {
boolean doPack = doPackIter == 1;
// Build FST w/ NoOutputs and stop when nodeCount > 2.2B
if (!doPack) {
System.out.println("\nTEST: 3B nodes; doPack=false output=NO_OUTPUTS");
Outputs<Object> outputs = NoOutputs.getSingleton();
Object NO_OUTPUT = outputs.getNoOutput();
final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
doPack, PackedInts.COMPACT, true, 15);
int count = 0;
Random r = new Random(seed);
int[] ints2 = new int[200];
IntsRef input2 = new IntsRef(ints2, 0, ints2.length);
while(true) {
//System.out.println("add: " + input + " -> " + output);
for(int i=10;i<ints2.length;i++) {
ints2[i] = r.nextInt(256);
}
b.add(input2, NO_OUTPUT);
count++;
if (count % 100000 == 0) {
System.out.println(count + ": " + b.fstRamBytesUsed() + " bytes; " + b.getNodeCount() + " nodes");
}
if (b.getNodeCount() > Integer.MAX_VALUE + 100L * 1024 * 1024) {
break;
}
nextInput(r, ints2);
}
FST<Object> fst = b.finish();
for(int verify=0;verify<2;verify++) {
System.out.println("\nTEST: now verify [fst size=" + fst.ramBytesUsed() + "; nodeCount=" + b.getNodeCount() + "; arcCount=" + b.getArcCount() + "]");
Arrays.fill(ints2, 0);
r = new Random(seed);
for(int i=0;i<count;i++) {
if (i % 1000000 == 0) {
System.out.println(i + "...: ");
}
for(int j=10;j<ints2.length;j++) {
ints2[j] = r.nextInt(256);
}
assertEquals(NO_OUTPUT, Util.get(fst, input2));
nextInput(r, ints2);
}
System.out.println("\nTEST: enum all input/outputs");
IntsRefFSTEnum<Object> fstEnum = new IntsRefFSTEnum<>(fst);
Arrays.fill(ints2, 0);
r = new Random(seed);
int upto = 0;
while(true) {
IntsRefFSTEnum.InputOutput<Object> pair = fstEnum.next();
if (pair == null) {
break;
}
for(int j=10;j<ints2.length;j++) {
ints2[j] = r.nextInt(256);
}
assertEquals(input2, pair.input);
assertEquals(NO_OUTPUT, pair.output);
upto++;
nextInput(r, ints2);
}
assertEquals(count, upto);
if (verify == 0) {
System.out.println("\nTEST: save/load FST and re-verify");
IndexOutput out = dir.createOutput("fst", IOContext.DEFAULT);
fst.save(out);
out.close();
IndexInput in = dir.openInput("fst", IOContext.DEFAULT);
fst = new FST<>(in, outputs);
in.close();
} else {
dir.deleteFile("fst");
}
}
}
// Build FST w/ ByteSequenceOutputs and stop when FST
// size = 3GB
{
System.out.println("\nTEST: 3 GB size; doPack=" + doPack + " outputs=bytes");
Outputs<BytesRef> outputs = ByteSequenceOutputs.getSingleton();
final Builder<BytesRef> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
doPack, PackedInts.COMPACT, true, 15);
byte[] outputBytes = new byte[20];
BytesRef output = new BytesRef(outputBytes);
Arrays.fill(ints, 0);
int count = 0;
Random r = new Random(seed);
while(true) {
r.nextBytes(outputBytes);
//System.out.println("add: " + input + " -> " + output);
b.add(input, BytesRef.deepCopyOf(output));
count++;
if (count % 1000000 == 0) {
System.out.println(count + "...: " + b.fstRamBytesUsed() + " bytes");
}
if (b.fstRamBytesUsed() > LIMIT) {
break;
}
nextInput(r, ints);
}
FST<BytesRef> fst = b.finish();
for(int verify=0;verify<2;verify++) {
System.out.println("\nTEST: now verify [fst size=" + fst.ramBytesUsed() + "; nodeCount=" + b.getNodeCount() + "; arcCount=" + b.getArcCount() + "]");
r = new Random(seed);
Arrays.fill(ints, 0);
for(int i=0;i<count;i++) {
if (i % 1000000 == 0) {
System.out.println(i + "...: ");
}
r.nextBytes(outputBytes);
assertEquals(output, Util.get(fst, input));
nextInput(r, ints);
}
System.out.println("\nTEST: enum all input/outputs");
IntsRefFSTEnum<BytesRef> fstEnum = new IntsRefFSTEnum<>(fst);
Arrays.fill(ints, 0);
r = new Random(seed);
int upto = 0;
while(true) {
IntsRefFSTEnum.InputOutput<BytesRef> pair = fstEnum.next();
if (pair == null) {
break;
}
assertEquals(input, pair.input);
r.nextBytes(outputBytes);
assertEquals(output, pair.output);
upto++;
nextInput(r, ints);
}
assertEquals(count, upto);
if (verify == 0) {
System.out.println("\nTEST: save/load FST and re-verify");
IndexOutput out = dir.createOutput("fst", IOContext.DEFAULT);
fst.save(out);
out.close();
IndexInput in = dir.openInput("fst", IOContext.DEFAULT);
fst = new FST<>(in, outputs);
in.close();
} else {
dir.deleteFile("fst");
}
}
}
// Build FST w/ PositiveIntOutputs and stop when FST
// size = 3GB
{
System.out.println("\nTEST: 3 GB size; doPack=" + doPack + " outputs=long");
Outputs<Long> outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> b = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs,
doPack, PackedInts.COMPACT, true, 15);
long output = 1;
Arrays.fill(ints, 0);
int count = 0;
Random r = new Random(seed);
while(true) {
//System.out.println("add: " + input + " -> " + output);
b.add(input, output);
output += 1+r.nextInt(10);
count++;
if (count % 1000000 == 0) {
System.out.println(count + "...: " + b.fstRamBytesUsed() + " bytes");
}
if (b.fstRamBytesUsed() > LIMIT) {
break;
}
nextInput(r, ints);
}
FST<Long> fst = b.finish();
for(int verify=0;verify<2;verify++) {
System.out.println("\nTEST: now verify [fst size=" + fst.ramBytesUsed() + "; nodeCount=" + b.getNodeCount() + "; arcCount=" + b.getArcCount() + "]");
Arrays.fill(ints, 0);
output = 1;
r = new Random(seed);
for(int i=0;i<count;i++) {
if (i % 1000000 == 0) {
System.out.println(i + "...: ");
}
// forward lookup:
assertEquals(output, Util.get(fst, input).longValue());
// reverse lookup:
assertEquals(input, Util.getByOutput(fst, output));
output += 1 + r.nextInt(10);
nextInput(r, ints);
}
System.out.println("\nTEST: enum all input/outputs");
IntsRefFSTEnum<Long> fstEnum = new IntsRefFSTEnum<>(fst);
Arrays.fill(ints, 0);
r = new Random(seed);
int upto = 0;
output = 1;
while(true) {
IntsRefFSTEnum.InputOutput<Long> pair = fstEnum.next();
if (pair == null) {
break;
}
assertEquals(input, pair.input);
assertEquals(output, pair.output.longValue());
output += 1 + r.nextInt(10);
upto++;
nextInput(r, ints);
}
assertEquals(count, upto);
if (verify == 0) {
System.out.println("\nTEST: save/load FST and re-verify");
IndexOutput out = dir.createOutput("fst", IOContext.DEFAULT);
fst.save(out);
out.close();
IndexInput in = dir.openInput("fst", IOContext.DEFAULT);
fst = new FST<>(in, outputs);
in.close();
} else {
dir.deleteFile("fst");
}
}
}
}
dir.close();
}
private void nextInput(Random r, int[] ints) {
int downTo = 6;
while(downTo >= 0) {
// Must add random amounts (and not just 1) because
// otherwise FST outsmarts us and remains tiny:
ints[downTo] += 1+r.nextInt(10);
if (ints[downTo] < 256) {
break;
} else {
ints[downTo] = 0;
downTo--;
}
}
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2018 the original author or authors.
*/
package org.assertj.core.api.exception;
public final class PathsException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PathsException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
package com.example.android.miwok;
import android.app.Activity;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<Word> {
private int mbackground_Clr;
//custom constructor
public WordAdapter(Activity context, ArrayList<Word> words, int back_colr)
{
//2nd argument is 0 since we are not using only one text view
super(context, 0, words);
mbackground_Clr = back_colr;
}
@Override
public View getView(int position,View convertView,ViewGroup parent) {
//checking if existing view is being used, else inflating
View listitemview = convertView;
if (listitemview == null) {
listitemview = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Word currentword = getItem(position);
TextView nameTextView = (TextView) listitemview.findViewById(R.id.miowk_v);
// Get the version name from the current word object and
// set this text on the name TextView
nameTextView.setText(currentword.getmiowktrans());
// Find the TextView in the list_item.xml layout with the ID english trans
TextView numberTextView = (TextView) listitemview.findViewById(R.id.eng_v);
// Get the eng trans from the current word object and
// set this text on the number TextView
numberTextView.setText(currentword.getdefaulttrans());
//image view
ImageView img = (ImageView) listitemview.findViewById(R.id.img);
if (currentword.hasimg()) { //if image is associated with the word
//get the image from current word object
img.setImageResource(currentword.getImg_res());
img.setVisibility(View.VISIBLE);
}
else
//GONE--> so that no imageview space is taken
img.setVisibility(View.GONE);
// Set the theme color for the list item
View textContainer = listitemview.findViewById(R.id.wordstrans);
// Find the color that the resource ID maps to
int color = ContextCompat.getColor(getContext(), mbackground_Clr);
textContainer.setBackgroundColor(color);
// Return the whole list item layout (containing 2 TextViews and an ImageView)
// so that it can be shown in the ListView
return listitemview;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.testsuites;
import junit.framework.TestSuite;
import org.apache.ignite.internal.binary.BinaryArrayIdentityResolverSelfTest;
import org.apache.ignite.internal.binary.BinaryBasicIdMapperSelfTest;
import org.apache.ignite.internal.binary.BinaryBasicNameMapperSelfTest;
import org.apache.ignite.internal.binary.BinaryConfigurationConsistencySelfTest;
import org.apache.ignite.internal.binary.BinaryConfigurationCustomSerializerSelfTest;
import org.apache.ignite.internal.binary.BinaryEnumsSelfTest;
import org.apache.ignite.internal.binary.BinaryFieldsHeapSelfTest;
import org.apache.ignite.internal.binary.BinaryFieldsOffheapSelfTest;
import org.apache.ignite.internal.binary.BinaryFooterOffsetsHeapSelfTest;
import org.apache.ignite.internal.binary.BinaryFooterOffsetsOffheapSelfTest;
import org.apache.ignite.internal.binary.BinaryMarshallerSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectBuilderAdditionalSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectBuilderDefaultMappersSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectBuilderSimpleNameLowerCaseMappersSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectExceptionSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectToStringSelfTest;
import org.apache.ignite.internal.binary.BinaryObjectTypeCompatibilityTest;
import org.apache.ignite.internal.binary.BinarySerialiedFieldComparatorSelfTest;
import org.apache.ignite.internal.binary.BinarySimpleNameTestPropertySelfTest;
import org.apache.ignite.internal.binary.BinaryTreeSelfTest;
import org.apache.ignite.internal.binary.GridBinaryAffinityKeySelfTest;
import org.apache.ignite.internal.binary.GridBinaryMarshallerCtxDisabledSelfTest;
import org.apache.ignite.internal.binary.GridBinaryWildcardsSelfTest;
import org.apache.ignite.internal.binary.GridDefaultBinaryMappersBinaryMetaDataSelfTest;
import org.apache.ignite.internal.binary.GridSimpleLowerCaseBinaryMappersBinaryMetaDataSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryFieldsHeapNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryFieldsOffheapNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryFooterOffsetsHeapNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryFooterOffsetsOffheapNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryMarshallerNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryObjectBuilderAdditionalNonCompactSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryObjectBuilderNonCompactDefaultMappersSelfTest;
import org.apache.ignite.internal.binary.noncompact.BinaryObjectBuilderNonCompactSimpleNameLowerCaseMappersSelfTest;
import org.apache.ignite.internal.binary.streams.BinaryAbstractOutputStreamTest;
import org.apache.ignite.internal.binary.streams.BinaryHeapStreamByteOrderSelfTest;
import org.apache.ignite.internal.binary.streams.BinaryOffheapStreamByteOrderSelfTest;
import org.apache.ignite.internal.processors.cache.binary.BinaryAtomicCacheLocalEntriesSelfTest;
import org.apache.ignite.internal.processors.cache.binary.BinaryMetadataUpdatesFlowTest;
import org.apache.ignite.internal.processors.cache.binary.BinaryTxCacheLocalEntriesSelfTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryObjectMetadataExchangeMultinodeTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryObjectUserClassloaderSelfTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryStoreBinariesDefaultMappersSelfTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryStoreBinariesSimpleNameMappersSelfTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryStoreObjectsSelfTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheClientNodeBinaryObjectMetadataMultinodeTest;
import org.apache.ignite.internal.processors.cache.binary.GridCacheClientNodeBinaryObjectMetadataTest;
import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinaryObjectsAtomicNearDisabledSelfTest;
import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinaryObjectsAtomicSelfTest;
import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinaryObjectsPartitionedNearDisabledSelfTest;
import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinaryObjectsPartitionedSelfTest;
import org.apache.ignite.internal.processors.cache.binary.distributed.replicated.GridCacheBinaryObjectsReplicatedSelfTest;
import org.apache.ignite.internal.processors.cache.binary.local.GridCacheBinaryObjectsAtomicLocalSelfTest;
import org.apache.ignite.internal.processors.cache.binary.local.GridCacheBinaryObjectsLocalSelfTest;
import org.apache.ignite.internal.processors.cache.distributed.IgniteBinaryMetadataUpdateChangingTopologySelfTest;
/**
* Test for binary objects stored in cache.
*/
public class IgniteBinaryObjectsTestSuite extends TestSuite {
/**
* @return Suite.
* @throws Exception If failed.
*/
public static TestSuite suite() throws Exception {
TestSuite suite = new TestSuite("Ignite Binary Objects Test Suite");
suite.addTestSuite(BinarySimpleNameTestPropertySelfTest.class);
suite.addTestSuite(BinaryBasicIdMapperSelfTest.class);
suite.addTestSuite(BinaryBasicNameMapperSelfTest.class);
suite.addTestSuite(BinaryTreeSelfTest.class);
suite.addTestSuite(BinaryMarshallerSelfTest.class);
suite.addTestSuite(BinaryObjectExceptionSelfTest.class);
suite.addTestSuite(BinarySerialiedFieldComparatorSelfTest.class);
suite.addTestSuite(BinaryArrayIdentityResolverSelfTest.class);
suite.addTestSuite(BinaryConfigurationConsistencySelfTest.class);
suite.addTestSuite(BinaryConfigurationCustomSerializerSelfTest.class);
suite.addTestSuite(GridBinaryMarshallerCtxDisabledSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderDefaultMappersSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderSimpleNameLowerCaseMappersSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderAdditionalSelfTest.class);
//suite.addTestSuite(BinaryFieldExtractionSelfTest.class);
suite.addTestSuite(BinaryFieldsHeapSelfTest.class);
suite.addTestSuite(BinaryFieldsOffheapSelfTest.class);
suite.addTestSuite(BinaryFooterOffsetsHeapSelfTest.class);
suite.addTestSuite(BinaryFooterOffsetsOffheapSelfTest.class);
suite.addTestSuite(BinaryEnumsSelfTest.class);
suite.addTestSuite(GridDefaultBinaryMappersBinaryMetaDataSelfTest.class);
suite.addTestSuite(GridSimpleLowerCaseBinaryMappersBinaryMetaDataSelfTest.class);
suite.addTestSuite(GridBinaryAffinityKeySelfTest.class);
suite.addTestSuite(GridBinaryWildcardsSelfTest.class);
suite.addTestSuite(BinaryObjectToStringSelfTest.class);
suite.addTestSuite(BinaryObjectTypeCompatibilityTest.class);
// Tests for objects with non-compact footers.
suite.addTestSuite(BinaryMarshallerNonCompactSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderNonCompactDefaultMappersSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderNonCompactSimpleNameLowerCaseMappersSelfTest.class);
suite.addTestSuite(BinaryObjectBuilderAdditionalNonCompactSelfTest.class);
suite.addTestSuite(BinaryFieldsHeapNonCompactSelfTest.class);
suite.addTestSuite(BinaryFieldsOffheapNonCompactSelfTest.class);
suite.addTestSuite(BinaryFooterOffsetsHeapNonCompactSelfTest.class);
suite.addTestSuite(BinaryFooterOffsetsOffheapNonCompactSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsLocalSelfTest.class);
//suite.addTestSuite(GridCacheBinaryObjectsLocalOnheapSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsAtomicLocalSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsReplicatedSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsPartitionedSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsPartitionedNearDisabledSelfTest.class);
//suite.addTestSuite(GridCacheBinaryObjectsPartitionedNearDisabledOnheapSelfTest.class);
//suite.addTestSuite(GridCacheBinaryObjectsPartitionedOnheapSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsAtomicSelfTest.class);
//suite.addTestSuite(GridCacheBinaryObjectsAtomicOnheapSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectsAtomicNearDisabledSelfTest.class);
//suite.addTestSuite(GridCacheBinaryObjectsAtomicNearDisabledOnheapSelfTest.class);
suite.addTestSuite(GridCacheBinaryStoreObjectsSelfTest.class);
suite.addTestSuite(GridCacheBinaryStoreBinariesDefaultMappersSelfTest.class);
suite.addTestSuite(GridCacheBinaryStoreBinariesSimpleNameMappersSelfTest.class);
suite.addTestSuite(GridCacheClientNodeBinaryObjectMetadataTest.class);
suite.addTestSuite(GridCacheBinaryObjectMetadataExchangeMultinodeTest.class);
suite.addTestSuite(BinaryMetadataUpdatesFlowTest.class);
suite.addTestSuite(GridCacheClientNodeBinaryObjectMetadataMultinodeTest.class);
suite.addTestSuite(IgniteBinaryMetadataUpdateChangingTopologySelfTest.class);
suite.addTestSuite(BinaryTxCacheLocalEntriesSelfTest.class);
suite.addTestSuite(BinaryAtomicCacheLocalEntriesSelfTest.class);
// Byte order
suite.addTestSuite(BinaryHeapStreamByteOrderSelfTest.class);
suite.addTestSuite(BinaryAbstractOutputStreamTest.class);
suite.addTestSuite(BinaryOffheapStreamByteOrderSelfTest.class);
suite.addTestSuite(GridCacheBinaryObjectUserClassloaderSelfTest.class);
return suite;
}
}
|
package org.distributeme.test.mod.client;
import org.distributeme.core.ServiceLocator;
import org.distributeme.test.mod.ModedService;
public class EchoClient{
public static void main(String a[]) throws Exception{
ModedService service = ServiceLocator.getRemote(ModedService.class);
long start = System.currentTimeMillis();
int errors = 0 ;
int mistakes = 0;
int LIMIT = 100;
for (int i = 0; i<LIMIT; i++){
try{
long reply = service.modEcho(i);
if (!(reply==(long)i))
mistakes++;
}catch(Exception e){
e.printStackTrace();
errors++;
}
}
long end = System.currentTimeMillis();
System.out.println("Tries "+LIMIT+", errors: "+errors+", wrong answers: "+mistakes+", time: "+(end-start)+" ms");
}
}
|
package org.kairosdb.datastore.cassandra;
import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.EC2AwareRoundRobinPolicy;
import com.datastax.driver.core.policies.EC2MultiRegionAddressTranslator;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
/**
Created by bhawkins on 3/4/15.
*/
public class CassandraClientImpl implements CassandraClient {
private static final Logger logger = LoggerFactory.getLogger(CassandraClientImpl.class);
private final Cluster m_cluster;
private String m_keyspace;
private static final String CASSANDRA_READ_TIMEOUT = "kairosdb.datastore.cassandra.read.timeout";
@javax.inject.Inject
@Named(CASSANDRA_READ_TIMEOUT)
// We set the default timeout as configured by the upstream driver.
private int m_cassandraReadTimeout = 12000;
@Inject
public CassandraClientImpl(CassandraConfiguration config) {
final Cluster.Builder builder = new Cluster.Builder().withSocketOptions(
new SocketOptions().setReadTimeoutMillis(m_cassandraReadTimeout));
if (config.getAddressTranslator().equals(CassandraConfiguration.ADDRESS_TRANSLATOR_TYPE.EC2)) {
builder.withAddressTranslator(new EC2MultiRegionAddressTranslator());
// This should work, seems the EC2AwareRoundRobinPolicy uses REMOTE for not being in the SAME az
builder.withLoadBalancingPolicy(new TokenAwarePolicy(EC2AwareRoundRobinPolicy.CreateEC2AwareRoundRobinPolicy()));
} else {
builder.withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()));
}
final QueryOptions queryOptions = new QueryOptions().setConsistencyLevel(config.getDataReadLevel());
builder.withQueryOptions(queryOptions);
for (String node : config.getHostList().split(",")) {
builder.addContactPoint(node.trim());
}
final String user = config.getUser();
final String password = config.getPassword();
if (null != user && null != password && !"".equals(user) && !"".equals(password)) {
builder.withCredentials(user, password);
}
m_cluster = builder.build();
m_keyspace = config.getKeyspaceName();
logConnectionPoolConfig(m_cluster.getConfiguration().getPoolingOptions());
}
@Override
public Session getKeyspaceSession() {
return m_cluster.connect(m_keyspace);
}
@Override
public Session getSession() {
return m_cluster.connect();
}
@Override
public String getKeyspace() {
return m_keyspace;
}
@Override
public void close() {
m_cluster.close();
}
private void logConnectionPoolConfig(PoolingOptions poolOpts) {
logger.warn("Core connections per host (remote): " + poolOpts.getCoreConnectionsPerHost(HostDistance.REMOTE));
logger.warn("Core connections per host (local): " + poolOpts.getCoreConnectionsPerHost(HostDistance.LOCAL));
logger.warn("Max connections per host (remote): " + poolOpts.getMaxConnectionsPerHost(HostDistance.REMOTE));
logger.warn("Max connections per host (local): " + poolOpts.getMaxConnectionsPerHost(HostDistance.LOCAL));
logger.warn("Max requests per connection (remote): " + poolOpts.getMaxRequestsPerConnection(HostDistance.REMOTE));
logger.warn("Max requests per connection (local): " + poolOpts.getMaxRequestsPerConnection(HostDistance.LOCAL));
logger.warn("Max queue size: " + poolOpts.getMaxQueueSize());
logger.warn("Pool timeout mills: " + poolOpts.getPoolTimeoutMillis());
logger.warn("Idle timeout seconds: " + poolOpts.getIdleTimeoutSeconds());
final ProtocolOptions protocolOpts = m_cluster.getConfiguration().getProtocolOptions();
if (protocolOpts != null && protocolOpts.getProtocolVersion() != null) {
logger.warn("Protocol version: " + protocolOpts.getProtocolVersion().toString());
}
}
public void logConnectionStats(final Session session) {
final Session.State state = session.getState();
final Configuration configuration = session.getCluster().getConfiguration();
final PoolingOptions poolingOptions = configuration.getPoolingOptions();
final Collection<Host> connectedHosts = state.getConnectedHosts();
for (Host host : connectedHosts) {
final HostDistance distance = configuration.getPolicies().getLoadBalancingPolicy().distance(host);
final int connections = state.getOpenConnections(host);
final int inFlightQueries = state.getInFlightQueries(host);
final int maxRequestsPerConnection = poolingOptions.getMaxRequestsPerConnection(distance);
logger.debug("connection_stats: hosts_count={} host={} distance={} connections={}, current_load={}, max_load={}",
connectedHosts.size(), host, distance.name(), connections, inFlightQueries, connections * maxRequestsPerConnection);
}
}
}
|
package org.redisson;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.awaitility.Duration;
import org.joor.Reflect;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.redisson.api.MapOptions;
import org.redisson.api.MapOptions.WriteMode;
import org.redisson.api.RMap;
import org.redisson.api.RMapCache;
import org.redisson.api.map.event.EntryCreatedListener;
import org.redisson.api.map.event.EntryEvent;
import org.redisson.api.map.event.EntryExpiredListener;
import org.redisson.api.map.event.EntryRemovedListener;
import org.redisson.api.map.event.EntryUpdatedListener;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.DoubleCodec;
import org.redisson.client.codec.IntegerCodec;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.CompositeCodec;
import org.redisson.eviction.EvictionScheduler;
public class RedissonMapCacheTest extends BaseMapTest {
@Test
public void testDestroy() {
RMapCache<String, String> cache = redisson.getMapCache("test");
EvictionScheduler evictionScheduler = ((Redisson)redisson).getEvictionScheduler();
Map<?, ?> map = Reflect.on(evictionScheduler).get("tasks");
assertThat(map.isEmpty()).isFalse();
cache.destroy();
assertThat(map.isEmpty()).isTrue();
}
@Override
protected <K, V> RMap<K, V> getMap(String name) {
return redisson.getMapCache(name);
}
@Override
protected <K, V> RMap<K, V> getMap(String name, Codec codec) {
return redisson.getMapCache(name, codec);
}
@Override
protected <K, V> RMap<K, V> getWriterTestMap(String name, Map<K, V> map) {
MapOptions<K, V> options = MapOptions.<K, V>defaults().writer(createMapWriter(map));
return redisson.getMapCache("test", options);
}
@Override
protected <K, V> RMap<K, V> getWriteBehindTestMap(String name, Map<K, V> map) {
MapOptions<K, V> options = MapOptions.<K, V>defaults()
.writer(createMapWriter(map))
.writeMode(WriteMode.WRITE_BEHIND);
return redisson.getMapCache("test", options);
}
@Override
protected <K, V> RMap<K, V> getLoaderTestMap(String name, Map<K, V> map) {
MapOptions<K, V> options = MapOptions.<K, V>defaults().loader(createMapLoader(map));
return redisson.getMapCache("test", options);
}
@Test
public void testSizeInMemory() {
Assume.assumeTrue(RedisRunner.getDefaultRedisServerInstance().getRedisVersion().compareTo("4.0.0") > 0);
RMapCache<Integer, Integer> map = redisson.getMapCache("test");
for (int i = 0; i < 10; i++) {
map.put(i, i, 5, TimeUnit.SECONDS);
}
assertThat(map.sizeInMemory()).isGreaterThanOrEqualTo(466);
}
@Test
public void testRemainTimeToLive() {
RMapCache<String, String> map = redisson.getMapCache("test");
map.put("1", "2", 2, TimeUnit.SECONDS);
assertThat(map.remainTimeToLive("1")).isLessThan(1900);
map.put("3", "4");
assertThat(map.remainTimeToLive("3")).isEqualTo(-1);
assertThat(map.remainTimeToLive("0")).isEqualTo(-2);
map.put("5", "6", 20, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
assertThat(map.remainTimeToLive("1")).isLessThan(9900);
map.destroy();
}
@Test
public void testFastPutTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("getAll");
map.trySetMaxSize(1);
map.fastPut(new SimpleKey("1"), new SimpleValue("3"), 5, TimeUnit.SECONDS, 0, TimeUnit.SECONDS);
Thread.sleep(5000);
assertThat(map.get(new SimpleKey("1"))).isNull();
map.fastPut(new SimpleKey("1"), new SimpleValue("4"), 5, TimeUnit.SECONDS, 0, TimeUnit.SECONDS);
Thread.sleep(10000);
assertThat(map.get(new SimpleKey("1"))).isNull();
}
@Test
public void testWriterPutIfAbsentTTL() {
Map<String, String> store = new HashMap<>();
RMapCache<String, String> map = (RMapCache<String, String>) getWriterTestMap("test", store);
map.putIfAbsent("1", "11", 10, TimeUnit.SECONDS);
map.putIfAbsent("1", "00", 10, TimeUnit.SECONDS);
map.putIfAbsent("2", "22", 10, TimeUnit.SECONDS);
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
assertThat(store).isEqualTo(expected);
map.destroy();
}
@Test
public void testWriterPutTTL() {
Map<String, String> store = new HashMap<>();
RMapCache<String, String> map = (RMapCache<String, String>) getWriterTestMap("test", store);
map.put("1", "11", 10, TimeUnit.SECONDS);
map.put("2", "22", 10, TimeUnit.SECONDS);
map.put("3", "33", 10, TimeUnit.SECONDS);
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
map.destroy();
}
@Test
public void testWriterFastPutIfAbsentTTL() {
Map<String, String> store = new HashMap<>();
RMapCache<String, String> map = (RMapCache<String, String>) getWriterTestMap("test", store);
map.fastPutIfAbsent("1", "11", 10, TimeUnit.SECONDS);
map.fastPutIfAbsent("1", "00", 10, TimeUnit.SECONDS);
map.fastPutIfAbsent("2", "22", 10, TimeUnit.SECONDS);
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
assertThat(store).isEqualTo(expected);
map.destroy();
}
@Test
public void testWriterFastPutTTL() {
Map<String, String> store = new HashMap<>();
RMapCache<String, String> map = (RMapCache<String, String>) getWriterTestMap("test", store);
map.fastPut("1", "11", 10, TimeUnit.SECONDS);
map.fastPut("2", "22", 10, TimeUnit.SECONDS);
map.fastPut("3", "33", 10, TimeUnit.SECONDS);
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
map.destroy();
}
@Test
public void testMaxSize() {
final AtomicInteger maxSize = new AtomicInteger(2);
Map<String, String> store = new LinkedHashMap<String, String>() {
@Override
protected boolean removeEldestEntry(Entry<String, String> eldest) {
return size() > maxSize.get();
}
};
MapOptions<String, String> options = MapOptions.<String, String>defaults().writer(createMapWriter(store));
RMapCache<String, String> map = redisson.getMapCache("test", options);
assertThat(map.trySetMaxSize(maxSize.get())).isTrue();
assertThat(map.trySetMaxSize(1)).isFalse();
assertThat(map.fastPutIfAbsent("01", "00")).isTrue();
assertThat(map.fastPutIfAbsent("02", "00")).isTrue();
assertThat(map.put("03", "00")).isNull();
assertThat(map.fastPutIfAbsent("04", "00", 10, TimeUnit.SECONDS)).isTrue();
assertThat(map.fastPut("1", "11", 10, TimeUnit.SECONDS)).isTrue();
assertThat(map.size()).isEqualTo(2);
assertThat(map.fastPut("2", "22", 10, TimeUnit.SECONDS)).isTrue();
assertThat(map.fastPut("3", "33", 10, TimeUnit.SECONDS)).isTrue();
assertThat(map.size()).isEqualTo(maxSize.get());
Map<String, String> expected = new HashMap<>();
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
assertThat(map.get("2")).isEqualTo("22");
assertThat(map.get("0")).isNull();
assertThat(map.putIfAbsent("2", "3")).isEqualTo("22");
assertThat(map.putIfAbsent("3", "4", 10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)).isEqualTo("33");
assertThat(map.containsKey("2")).isTrue();
assertThat(map.containsKey("0")).isFalse();
assertThat(map.containsValue("22")).isTrue();
assertThat(map.containsValue("00")).isFalse();
assertThat(map.getAll(new HashSet<String>(Arrays.asList("2", "3")))).isEqualTo(expected);
assertThat(map.remove("2", "33")).isFalse();
assertThat(map.remove("2", "22")).isTrue();
assertThat(map.remove("0")).isNull();
assertThat(map.remove("3")).isEqualTo("33");
maxSize.set(6);
map.setMaxSize(maxSize.get());
assertThat(map.fastPut("01", "00")).isTrue();
assertThat(map.fastPut("02", "00")).isTrue();
assertThat(map.fastPut("03", "00")).isTrue();
assertThat(map.fastPut("04", "00")).isTrue();
assertThat(map.fastPut("05", "00")).isTrue();
assertThat(map.fastPut("06", "00")).isTrue();
assertThat(map.fastPut("07", "00")).isTrue();
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("02", "03", "04", "05", "06", "07");
map.put("08", "00");
map.put("09", "00");
map.put("10", "00");
map.put("11", "00");
map.put("12", "00");
map.put("13", "00");
map.put("14", "00");
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("09", "10", "11", "12", "13", "14");
map.putIfAbsent("15", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("16", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("17", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("18", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("19", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("20", "00", 1, TimeUnit.SECONDS);
map.putIfAbsent("21", "00", 1, TimeUnit.SECONDS);
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("16", "17", "18", "19", "20", "21");
map.putIfAbsent("22", "00");
map.putIfAbsent("23", "00");
map.putIfAbsent("24", "00");
map.putIfAbsent("25", "00");
map.putIfAbsent("26", "00");
map.putIfAbsent("27", "00");
map.putIfAbsent("28", "00");
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("23", "24", "25", "26", "27", "28");
map.fastPut("29", "00", 1, TimeUnit.SECONDS);
map.fastPut("30", "00", 1, TimeUnit.SECONDS);
map.fastPut("31", "00", 1, TimeUnit.SECONDS);
map.fastPut("32", "00", 1, TimeUnit.SECONDS);
map.fastPut("33", "00", 1, TimeUnit.SECONDS);
map.fastPut("34", "00", 1, TimeUnit.SECONDS);
map.fastPut("35", "00", 1, TimeUnit.SECONDS);
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("30", "31", "32", "33", "34", "35");
map.put("36", "00", 1, TimeUnit.SECONDS);
map.put("37", "00", 1, TimeUnit.SECONDS);
map.put("38", "00", 1, TimeUnit.SECONDS);
map.put("39", "00", 1, TimeUnit.SECONDS);
map.put("40", "00", 1, TimeUnit.SECONDS);
map.put("41", "00", 1, TimeUnit.SECONDS);
map.put("42", "00", 1, TimeUnit.SECONDS);
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("37", "38", "39", "40", "41", "42");
map.fastPutIfAbsent("43", "00");
map.fastPutIfAbsent("44", "00");
map.fastPutIfAbsent("45", "00");
map.fastPutIfAbsent("46", "00");
map.fastPutIfAbsent("47", "00");
map.fastPutIfAbsent("48", "00");
map.fastPutIfAbsent("49", "00");
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("44", "45", "46", "47", "48", "49");
map.fastPutIfAbsent("50", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("51", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("52", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("53", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("54", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("55", "00", 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("56", "00", 1, TimeUnit.SECONDS);
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("51", "52", "53", "54", "55", "56");
Map<String, String> newMap = new LinkedHashMap<>();
newMap.put("57", "00");
newMap.put("58", "00");
newMap.put("59", "00");
newMap.put("60", "00");
newMap.put("61", "00");
newMap.put("62", "00");
newMap.put("63", "00");
map.putAll(newMap);
assertThat(map.size()).isEqualTo(maxSize.get());
assertThat(map.keySet()).containsExactly("58", "59", "60", "61", "62", "63");
map.destroy();
}
@Test
public void testCacheValues() {
final RMapCache<String, String> map = redisson.getMapCache("testRMapCacheValues");
map.put("1234", "5678", 0, TimeUnit.MINUTES, 60, TimeUnit.MINUTES);
assertThat(map.values()).containsOnly("5678");
map.destroy();
}
@Test
public void testGetAllTTL() throws InterruptedException {
RMapCache<Integer, Integer> map = redisson.getMapCache("getAll");
map.put(1, 100);
map.put(2, 200, 1, TimeUnit.SECONDS);
map.put(3, 300, 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS);
map.put(4, 400);
Map<Integer, Integer> filtered = map.getAll(new HashSet<Integer>(Arrays.asList(2, 3, 5)));
Map<Integer, Integer> expectedMap = new HashMap<Integer, Integer>();
expectedMap.put(2, 200);
expectedMap.put(3, 300);
Assert.assertEquals(expectedMap, filtered);
Thread.sleep(1000);
Map<Integer, Integer> filteredAgain = map.getAll(new HashSet<Integer>(Arrays.asList(2, 3, 5)));
Assert.assertTrue(filteredAgain.isEmpty());
map.destroy();
}
@Test
public void testGetAllWithStringKeys() {
RMapCache<String, Integer> map = redisson.getMapCache("getAllStrings");
map.put("A", 100);
map.put("B", 200);
map.put("C", 300);
map.put("D", 400);
Map<String, Integer> filtered = map.getAll(new HashSet<String>(Arrays.asList("B", "C", "E")));
Map<String, Integer> expectedMap = new HashMap<String, Integer>();
expectedMap.put("B", 200);
expectedMap.put("C", 300);
Assert.assertEquals(expectedMap, filtered);
map.destroy();
}
@Test
public void testExpiredIterator() throws InterruptedException {
RMapCache<String, String> cache = redisson.getMapCache("simple");
cache.put("0", "8");
cache.put("1", "6", 1, TimeUnit.SECONDS);
cache.put("2", "4", 3, TimeUnit.SECONDS);
cache.put("3", "2", 4, TimeUnit.SECONDS);
cache.put("4", "4", 1, TimeUnit.SECONDS);
Thread.sleep(1000);
assertThat(cache.keySet()).containsOnly("0", "2", "3");
cache.destroy();
}
@Test
public void testExpire() throws InterruptedException {
RMapCache<String, String> cache = redisson.getMapCache("simple");
cache.put("0", "8", 1, TimeUnit.SECONDS);
cache.expire(100, TimeUnit.MILLISECONDS);
Thread.sleep(500);
Assert.assertEquals(0, cache.size());
cache.destroy();
}
@Test
public void testExpireAt() throws InterruptedException {
RMapCache<String, String> cache = redisson.getMapCache("simple");
cache.put("0", "8", 1, TimeUnit.SECONDS);
cache.expireAt(System.currentTimeMillis() + 100);
Thread.sleep(500);
Assert.assertEquals(0, cache.size());
cache.destroy();
}
@Test
public void testClearExpire() throws InterruptedException {
RMapCache<String, String> cache = redisson.getMapCache("simple");
cache.put("0", "8", 1, TimeUnit.SECONDS);
cache.expireAt(System.currentTimeMillis() + 100);
cache.clearExpire();
Thread.sleep(500);
Assert.assertEquals(1, cache.size());
cache.destroy();
}
@Test
public void testEntrySet() throws InterruptedException {
RMapCache<Integer, String> map = redisson.getMapCache("simple12");
map.put(1, "12");
map.put(2, "33", 1, TimeUnit.SECONDS);
map.put(3, "43");
Map<Integer, String> expected = new HashMap<>();
map.put(1, "12");
map.put(3, "43");
assertThat(map.entrySet()).containsAll(expected.entrySet());
assertThat(map).hasSize(3);
map.destroy();
}
@Test
public void testKeySet() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple03");
map.put(new SimpleKey("33"), new SimpleValue("44"), 1, TimeUnit.SECONDS);
map.put(new SimpleKey("1"), new SimpleValue("2"));
Assert.assertTrue(map.keySet().contains(new SimpleKey("33")));
Assert.assertFalse(map.keySet().contains(new SimpleKey("44")));
Assert.assertTrue(map.keySet().contains(new SimpleKey("1")));
Thread.sleep(1000);
Assert.assertFalse(map.keySet().contains(new SimpleKey("33")));
Assert.assertFalse(map.keySet().contains(new SimpleKey("44")));
Assert.assertTrue(map.keySet().contains(new SimpleKey("1")));
map.destroy();
}
@Test
public void testValues() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple05");
map.put(new SimpleKey("33"), new SimpleValue("44"), 1, TimeUnit.SECONDS);
map.put(new SimpleKey("1"), new SimpleValue("2"));
Assert.assertTrue(map.values().contains(new SimpleValue("44")));
Assert.assertFalse(map.values().contains(new SimpleValue("33")));
Assert.assertTrue(map.values().contains(new SimpleValue("2")));
Thread.sleep(1000);
Assert.assertFalse(map.values().contains(new SimpleValue("44")));
Assert.assertFalse(map.values().contains(new SimpleValue("33")));
Assert.assertTrue(map.values().contains(new SimpleValue("2")));
map.destroy();
}
@Test
public void testKeySetByPatternTTL() {
RMapCache<String, String> map = redisson.getMapCache("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200", 1, TimeUnit.MINUTES);
map.put("30", "300");
assertThat(map.keySet("?0")).containsExactly("10", "20", "30");
assertThat(map.keySet("1")).isEmpty();
assertThat(map.keySet("10")).containsExactly("10");
map.destroy();
}
@Test
public void testValuesByPatternTTL() {
RMapCache<String, String> map = redisson.getMapCache("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200", 1, TimeUnit.MINUTES);
map.put("30", "300");
assertThat(map.values("?0")).containsExactly("100", "200", "300");
assertThat(map.values("1")).isEmpty();
assertThat(map.values("10")).containsExactly("100");
map.destroy();
}
@Test
public void testEntrySetByPatternTTL() {
RMapCache<String, String> map = redisson.getMapCache("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200", 1, TimeUnit.MINUTES);
map.put("30", "300");
assertThat(map.entrySet("?0")).containsExactly(new AbstractMap.SimpleEntry("10", "100"), new AbstractMap.SimpleEntry("20", "200"), new AbstractMap.SimpleEntry("30", "300"));
assertThat(map.entrySet("1")).isEmpty();
assertThat(map.entrySet("10")).containsExactly(new AbstractMap.SimpleEntry("10", "100"));
map.destroy();
}
@Test
public void testContainsValueTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple01");
Assert.assertFalse(map.containsValue(new SimpleValue("34")));
map.put(new SimpleKey("33"), new SimpleValue("44"), 1, TimeUnit.SECONDS);
Assert.assertTrue(map.containsValue(new SimpleValue("44")));
Assert.assertFalse(map.containsValue(new SimpleValue("34")));
Thread.sleep(1000);
Assert.assertFalse(map.containsValue(new SimpleValue("44")));
map.destroy();
}
@Test
public void testContainsKeyTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple30");
map.put(new SimpleKey("33"), new SimpleValue("44"), 1, TimeUnit.SECONDS);
Assert.assertTrue(map.containsKey(new SimpleKey("33")));
Assert.assertFalse(map.containsKey(new SimpleKey("34")));
Thread.sleep(1000);
Assert.assertFalse(map.containsKey(new SimpleKey("33")));
map.destroy();
}
@Test
public void testRemoveValueTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"), 1, TimeUnit.SECONDS);
boolean res = map.remove(new SimpleKey("1"), new SimpleValue("2"));
Assert.assertTrue(res);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertNull(val1);
Assert.assertEquals(0, map.size());
map.put(new SimpleKey("3"), new SimpleValue("4"), 1, TimeUnit.SECONDS);
Thread.sleep(1000);
assertThat(map.remove(new SimpleKey("3"), new SimpleValue("4"))).isFalse();
assertThat(map.get(new SimpleKey("3"))).isNull();
map.destroy();
}
@Test
public void testRemoveValueFail() {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.remove(new SimpleKey("2"), new SimpleValue("1"));
Assert.assertFalse(res);
boolean res1 = map.remove(new SimpleKey("1"), new SimpleValue("3"));
Assert.assertFalse(res1);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("2", val1.getValue());
map.destroy();
}
@Test
public void testReplaceOldValueFail() {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("43"), new SimpleValue("31"));
Assert.assertFalse(res);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("2", val1.getValue());
map.destroy();
}
@Test
public void testReplaceOldValueSuccess() {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
Assert.assertTrue(res);
boolean res1 = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
Assert.assertFalse(res1);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("3", val1.getValue());
map.destroy();
}
@Test
public void testReplaceValueTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"), 1, TimeUnit.SECONDS);
Thread.sleep(1000);
SimpleValue res = map.replace(new SimpleKey("1"), new SimpleValue("3"));
assertThat(res).isNull();
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1).isNull();
map.destroy();
}
@Test
public void testScheduler() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple3");
Assert.assertNull(map.get(new SimpleKey("33")));
map.put(new SimpleKey("33"), new SimpleValue("44"), 5, TimeUnit.SECONDS);
map.put(new SimpleKey("10"), new SimpleValue("32"), 5, TimeUnit.SECONDS, 2, TimeUnit.SECONDS);
map.put(new SimpleKey("01"), new SimpleValue("92"), 0, null, 2, TimeUnit.SECONDS);
Assert.assertEquals(3, map.size());
Thread.sleep(11000);
Assert.assertEquals(0, map.size());
map.destroy();
}
@Test
public void testPutGetTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple04");
Assert.assertNull(map.get(new SimpleKey("33")));
map.put(new SimpleKey("33"), new SimpleValue("44"), 2, TimeUnit.SECONDS);
SimpleValue val1 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val1.getValue());
Thread.sleep(1000);
Assert.assertEquals(1, map.size());
SimpleValue val2 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val2.getValue());
Assert.assertEquals(1, map.size());
Thread.sleep(1000);
Assert.assertNull(map.get(new SimpleKey("33")));
map.destroy();
}
@Test
public void testPutAllGetTTL() throws InterruptedException {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple06");
Assert.assertNull(map.get(new SimpleKey("33")));
Assert.assertNull(map.get(new SimpleKey("55")));
Map<SimpleKey, SimpleValue> entries = new HashMap<>();
entries.put(new SimpleKey("33"), new SimpleValue("44"));
entries.put(new SimpleKey("55"), new SimpleValue("66"));
map.putAll(entries, 2, TimeUnit.SECONDS);
SimpleValue val1 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val1.getValue());
SimpleValue val2 = map.get(new SimpleKey("55"));
Assert.assertEquals("66", val2.getValue());
Thread.sleep(1000);
Assert.assertEquals(2, map.size());
SimpleValue val3 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val3.getValue());
SimpleValue val4 = map.get(new SimpleKey("55"));
Assert.assertEquals("66", val4.getValue());
Assert.assertEquals(2, map.size());
Thread.sleep(1000);
Assert.assertNull(map.get(new SimpleKey("33")));
Assert.assertNull(map.get(new SimpleKey("55")));
map.destroy();
}
@Test
public void testPutIfAbsentTTL() throws Exception {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.put(key, value);
Assert.assertEquals(value, map.putIfAbsent(key, new SimpleValue("3"), 1, TimeUnit.SECONDS));
Assert.assertEquals(value, map.get(key));
map.putIfAbsent(new SimpleKey("4"), new SimpleValue("4"), 1, TimeUnit.SECONDS);
Assert.assertEquals(new SimpleValue("4"), map.get(new SimpleKey("4")));
Thread.sleep(1000);
Assert.assertNull(map.get(new SimpleKey("4")));
// this should be passed
map.putIfAbsent(new SimpleKey("4"), new SimpleValue("4"), 1, TimeUnit.SECONDS);
Assert.assertEquals(new SimpleValue("4"), map.get(new SimpleKey("4")));
SimpleKey key1 = new SimpleKey("2");
SimpleValue value1 = new SimpleValue("4");
Assert.assertNull(map.putIfAbsent(key1, value1, 2, TimeUnit.SECONDS));
Assert.assertEquals(value1, map.get(key1));
map.destroy();
}
@Test
public void testFastPutIfAbsentTTL() throws Exception {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.put(key, value);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("3"))).isFalse();
assertThat(map.get(key)).isEqualTo(value);
SimpleKey key1 = new SimpleKey("2");
SimpleValue value1 = new SimpleValue("4");
assertThat(map.fastPutIfAbsent(key1, value1)).isTrue();
assertThat(map.get(key1)).isEqualTo(value1);
SimpleKey key2 = new SimpleKey("3");
map.put(key2, new SimpleValue("31"), 500, TimeUnit.MILLISECONDS);
assertThat(map.fastPutIfAbsent(key2, new SimpleValue("32"))).isFalse();
Thread.sleep(500);
assertThat(map.fastPutIfAbsent(key2, new SimpleValue("32"))).isTrue();
assertThat(map.get(key2)).isEqualTo(new SimpleValue("32"));
map.destroy();
}
@Test
public void testCreatedListener() {
RMapCache<Integer, Integer> map = redisson.getMapCache("simple");
checkCreatedListener(map, 1, 2, () -> map.put(1, 2));
checkCreatedListener(map, 10, 2, () -> map.put(10, 2, 2, TimeUnit.SECONDS));
checkCreatedListener(map, 2, 5, () -> map.fastPut(2, 5));
checkCreatedListener(map, 13, 2, () -> map.fastPut(13, 2, 2, TimeUnit.SECONDS));
checkCreatedListener(map, 3, 2, () -> map.putIfAbsent(3, 2));
checkCreatedListener(map, 14, 2, () -> map.putIfAbsent(14, 2, 2, TimeUnit.SECONDS));
checkCreatedListener(map, 4, 1, () -> map.fastPutIfAbsent(4, 1));
checkCreatedListener(map, 15, 2, () -> map.fastPutIfAbsent(15, 2, 2, TimeUnit.SECONDS));
map.destroy();
RMapCache<Integer, Integer> map2 = redisson.getMapCache("simple3", new CompositeCodec(redisson.getConfig().getCodec(), IntegerCodec.INSTANCE));
checkCreatedListener(map2, 5, 10, () -> map2.addAndGet(5, 10));
map2.destroy();
}
private void checkCreatedListener(RMapCache<Integer, Integer> map, Integer key, Integer value, Runnable runnable) {
AtomicBoolean ref = new AtomicBoolean();
int createListener1 = map.addListener(new EntryCreatedListener<Integer, Integer>() {
@Override
public void onCreated(EntryEvent<Integer, Integer> event) {
try {
assertThat(event.getKey()).isEqualTo(key);
assertThat(event.getValue()).isEqualTo(value);
if (!ref.compareAndSet(false, true)) {
Assert.fail();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
runnable.run();
await().atMost(Duration.ONE_SECOND).untilTrue(ref);
map.removeListener(createListener1);
map.destroy();
}
@Test
public void testUpdatedListener() {
RMapCache<Integer, Integer> map = redisson.getMapCache("simple");
map.put(1, 1);
checkUpdatedListener(map, 1, 3, 1, () -> map.put(1, 3));
map.put(10, 1);
checkUpdatedListener(map, 10, 2, 1, () -> map.put(10, 2, 2, TimeUnit.SECONDS));
map.put(2, 1);
checkUpdatedListener(map, 2, 5, 1, () -> map.fastPut(2, 5));
map.put(13, 1);
checkUpdatedListener(map, 13, 2, 1, () -> map.fastPut(13, 2, 2, TimeUnit.SECONDS));
map.put(14, 1);
checkUpdatedListener(map, 14, 2, 1, () -> map.replace(14, 2));
checkUpdatedListener(map, 14, 3, 2, () -> map.replace(14, 2, 3));
map.destroy();
RMapCache<Integer, Integer> map2 = redisson.getMapCache("simple2", new CompositeCodec(redisson.getConfig().getCodec(), IntegerCodec.INSTANCE));
map2.put(5, 1);
checkUpdatedListener(map2, 5, 4, 1, () -> map2.addAndGet(5, 3));
map2.destroy();
}
@Test
public void testExpiredListener() {
RMapCache<Integer, Integer> map = redisson.getMapCache("simple");
checkExpiredListener(map, 10, 2, () -> map.put(10, 2, 2, TimeUnit.SECONDS));
checkExpiredListener(map, 13, 2, () -> map.fastPut(13, 2, 2, TimeUnit.SECONDS));
checkExpiredListener(map, 14, 2, () -> map.putIfAbsent(14, 2, 2, TimeUnit.SECONDS));
checkExpiredListener(map, 15, 2, () -> map.fastPutIfAbsent(15, 2, 2, TimeUnit.SECONDS));
map.destroy();
}
private void checkExpiredListener(RMapCache<Integer, Integer> map, Integer key, Integer value, Runnable runnable) {
AtomicBoolean ref = new AtomicBoolean();
int createListener1 = map.addListener(new EntryExpiredListener<Integer, Integer>() {
@Override
public void onExpired(EntryEvent<Integer, Integer> event) {
assertThat(event.getKey()).isEqualTo(key);
assertThat(event.getValue()).isEqualTo(value);
if (!ref.compareAndSet(false, true)) {
Assert.fail();
}
}
});
runnable.run();
await().atMost(Duration.ONE_MINUTE).untilTrue(ref);
map.removeListener(createListener1);
}
private void checkUpdatedListener(RMapCache<Integer, Integer> map, Integer key, Integer value, Integer oldValue, Runnable runnable) {
AtomicBoolean ref = new AtomicBoolean();
int createListener1 = map.addListener(new EntryUpdatedListener<Integer, Integer>() {
@Override
public void onUpdated(EntryEvent<Integer, Integer> event) {
assertThat(event.getKey()).isEqualTo(key);
assertThat(event.getValue()).isEqualTo(value);
assertThat(event.getOldValue()).isEqualTo(oldValue);
if (!ref.compareAndSet(false, true)) {
Assert.fail();
}
}
});
runnable.run();
await().atMost(Duration.ONE_SECOND).untilTrue(ref);
map.removeListener(createListener1);
}
@Test
public void testRemovedListener() {
RMapCache<Integer, Integer> map = redisson.getMapCache("simple");
map.put(1, 1);
checkRemovedListener(map, 1, 1, () -> map.remove(1, 1));
map.put(10, 1);
checkRemovedListener(map, 10, 1, () -> map.remove(10));
map.put(2, 1);
checkRemovedListener(map, 2, 1, () -> map.fastRemove(2));
map.destroy();
}
private void checkRemovedListener(RMapCache<Integer, Integer> map, Integer key, Integer value, Runnable runnable) {
AtomicBoolean ref = new AtomicBoolean();
int createListener1 = map.addListener(new EntryRemovedListener<Integer, Integer>() {
@Override
public void onRemoved(EntryEvent<Integer, Integer> event) {
assertThat(event.getKey()).isEqualTo(key);
assertThat(event.getValue()).isEqualTo(value);
if (!ref.compareAndSet(false, true)) {
Assert.fail();
}
}
});
runnable.run();
await().atMost(Duration.ONE_SECOND).untilTrue(ref);
map.removeListener(createListener1);
}
@Test
public void testIdle() throws InterruptedException {
testIdleExpiration(map -> {
map.put("12", 1, 0, null, 1, TimeUnit.SECONDS);
map.put("14", 2, 0, null, 2, TimeUnit.SECONDS);
map.put("15", 3, 0, null, 3, TimeUnit.SECONDS);
});
testIdleExpiration(map -> {
map.fastPut("12", 1, 0, null, 1, TimeUnit.SECONDS);
map.fastPut("14", 2, 0, null, 2, TimeUnit.SECONDS);
map.fastPut("15", 3, 0, null, 3, TimeUnit.SECONDS);
});
testIdleExpiration(map -> {
map.putIfAbsent("12", 1, 0, null, 1, TimeUnit.SECONDS);
map.putIfAbsent("14", 2, 0, null, 2, TimeUnit.SECONDS);
map.putIfAbsent("15", 3, 0, null, 3, TimeUnit.SECONDS);
});
testIdleExpiration(map -> {
map.fastPutIfAbsent("12", 1, 0, null, 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("14", 2, 0, null, 2, TimeUnit.SECONDS);
map.fastPutIfAbsent("15", 3, 0, null, 3, TimeUnit.SECONDS);
});
}
@Test
public void testTTL() throws InterruptedException {
testTTLExpiration(map -> {
map.put("12", 1, 1, TimeUnit.SECONDS);
map.put("14", 2, 2, TimeUnit.SECONDS);
map.put("15", 3, 3, TimeUnit.SECONDS);
});
testTTLExpiration(map -> {
map.fastPut("12", 1, 1, TimeUnit.SECONDS);
map.fastPut("14", 2, 2, TimeUnit.SECONDS);
map.fastPut("15", 3, 3, TimeUnit.SECONDS);
});
testTTLExpiration(map -> {
map.putIfAbsent("12", 1, 1, TimeUnit.SECONDS);
map.putIfAbsent("14", 2, 2, TimeUnit.SECONDS);
map.putIfAbsent("15", 3, 3, TimeUnit.SECONDS);
});
testTTLExpiration(map -> {
map.fastPutIfAbsent("12", 1, 1, TimeUnit.SECONDS);
map.fastPutIfAbsent("14", 2, 2, TimeUnit.SECONDS);
map.fastPutIfAbsent("15", 3, 3, TimeUnit.SECONDS);
});
}
protected void testIdleExpiration(Consumer<RMapCache<String, Integer>> callback) throws InterruptedException {
RMapCache<String, Integer> map = redisson.getMapCache("simple");
callback.accept(map);
Thread.sleep(1000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isEqualTo(2);
assertThat(map.get("15")).isEqualTo(3);
Thread.sleep(2000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isNull();
assertThat(map.get("15")).isEqualTo(3);
Thread.sleep(3000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isNull();
assertThat(map.get("15")).isNull();
map.clear();
map.destroy();
}
protected void testTTLExpiration(Consumer<RMapCache<String, Integer>> callback) throws InterruptedException {
RMapCache<String, Integer> map = redisson.getMapCache("simple");
callback.accept(map);
Thread.sleep(1000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isEqualTo(2);
assertThat(map.get("15")).isEqualTo(3);
Thread.sleep(1000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isNull();
assertThat(map.get("15")).isEqualTo(3);
Thread.sleep(1000);
assertThat(map.get("12")).isNull();
assertThat(map.get("14")).isNull();
assertThat(map.get("15")).isNull();
map.clear();
map.destroy();
}
@Test
public void testExpireOverwrite() throws InterruptedException, ExecutionException {
RMapCache<String, Integer> map = redisson.getMapCache("simple");
map.put("123", 3, 1, TimeUnit.SECONDS);
Thread.sleep(800);
map.put("123", 3, 1, TimeUnit.SECONDS);
Thread.sleep(800);
Assert.assertEquals(3, (int)map.get("123"));
Thread.sleep(200);
Assert.assertFalse(map.containsKey("123"));
map.destroy();
}
@Test
public void testRMapCacheValues() {
final RMapCache<String, String> map = redisson.getMapCache("testRMapCacheValues");
map.put("1234", "5678", 1, TimeUnit.MINUTES, 60, TimeUnit.MINUTES);
assertThat(map.values()).containsOnly("5678");
map.destroy();
}
@Test
public void testReadAllEntrySet() throws InterruptedException {
RMapCache<Integer, String> map = redisson.getMapCache("simple12");
map.put(1, "12");
map.put(2, "33", 10, TimeUnit.MINUTES, 60, TimeUnit.MINUTES);
map.put(3, "43");
assertThat(map.readAllEntrySet()).isEqualTo(map.entrySet());
map.destroy();
}
@Test
public void testReadAllValuesTTL() {
final RMapCache<String, String> map = redisson.getMapCache("testRMapCacheAllValues");
map.put("1234", "5678", 1, TimeUnit.MINUTES, 60, TimeUnit.MINUTES);
assertThat(map.readAllValues()).containsOnly("5678");
map.destroy();
}
@Test
public void testAddAndGetTTL() {
RMapCache<String, Object> mapCache = redisson.getMapCache("test_put_if_absent", LongCodec.INSTANCE);
assertThat(mapCache.putIfAbsent("4", 0L, 10000L, TimeUnit.SECONDS)).isNull();
assertThat(mapCache.addAndGet("4", 1L)).isEqualTo(1L);
assertThat(mapCache.putIfAbsent("4", 0L)).isEqualTo(1L);
Assert.assertEquals(1L, mapCache.get("4"));
mapCache.destroy();
mapCache = redisson.getMapCache("test_put_if_absent_1", LongCodec.INSTANCE);
mapCache.putIfAbsent("4", 0L);
mapCache.addAndGet("4", 1L);
mapCache.putIfAbsent("4", 0L);
Assert.assertEquals(1L, mapCache.get("4"));
RMap map = redisson.getMap("test_put_if_absent_2", LongCodec.INSTANCE);
map.putIfAbsent("4", 0L);
map.addAndGet("4", 1L);
map.putIfAbsent("4", 0L);
Assert.assertEquals(1L, map.get("4"));
RMapCache<String, Object> mapCache1 = redisson.getMapCache("test_put_if_absent_3", DoubleCodec.INSTANCE);
mapCache1.putIfAbsent("4", 1.23, 10000L, TimeUnit.SECONDS);
mapCache1.addAndGet("4", 1D);
Assert.assertEquals(2.23, mapCache1.get("4"));
mapCache.destroy();
mapCache1.destroy();
}
@Test
public void testFastPutIfAbsentWithTTL() throws Exception {
RMapCache<SimpleKey, SimpleValue> map = redisson.getMapCache("simpleTTL");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.fastPutIfAbsent(key, value, 1, TimeUnit.SECONDS);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("3"), 1, TimeUnit.SECONDS)).isFalse();
assertThat(map.get(key)).isEqualTo(value);
Thread.sleep(1100);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("3"), 1, TimeUnit.SECONDS)).isTrue();
assertThat(map.get(key)).isEqualTo(new SimpleValue("3"));
assertThat(map.fastPutIfAbsent(key, new SimpleValue("4"), 1, TimeUnit.SECONDS)).isFalse();
assertThat(map.get(key)).isEqualTo(new SimpleValue("3"));
Thread.sleep(1100);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("4"), 1, TimeUnit.SECONDS, 500, TimeUnit.MILLISECONDS)).isTrue();
Thread.sleep(550);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("5"), 1, TimeUnit.SECONDS, 500, TimeUnit.MILLISECONDS)).isTrue();
map.destroy();
}
}
|
package com.listenergao.customview;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* Activity基类
*
* @author ListenerGao
* @date 2019-04-19
*/
public class BaseActivitty extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void startActivity(@NonNull final Class<? extends Activity> clz) {
startActivity(null, clz);
}
public void startActivity(Bundle extras, @NonNull final Class<? extends Activity> clz) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (extras != null) {
intent.putExtras(extras);
}
intent.setComponent(new ComponentName(this.getPackageName(), clz.getName()));
startActivity(intent);
}
}
|
package net.glowstone.net.codec.play.player;
import com.flowpowered.network.Codec;
import com.flowpowered.network.util.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import net.glowstone.net.message.play.player.ResourcePackSendMessage;
public final class ResourcePackSendCodec implements Codec<ResourcePackSendMessage> {
@Override
public ResourcePackSendMessage decode(ByteBuf buffer) throws IOException {
String url = ByteBufUtils.readUTF8(buffer);
String hash = ByteBufUtils.readUTF8(buffer);
return new ResourcePackSendMessage(url, hash);
}
@Override
public ByteBuf encode(ByteBuf buf, ResourcePackSendMessage message) throws IOException {
ByteBufUtils.writeUTF8(buf, message.getUrl());
ByteBufUtils.writeUTF8(buf, message.getHash());
return buf;
}
}
|
package com.commercetools.api.models.cart;
import java.time.*;
import java.util.*;
import com.commercetools.api.models.common.ReferenceTypeId;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.*;
import io.vrap.rmf.base.client.utils.Generated;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
public final class CartResourceIdentifierImpl implements CartResourceIdentifier {
private com.commercetools.api.models.common.ReferenceTypeId typeId;
private String id;
private String key;
@JsonCreator
CartResourceIdentifierImpl(@JsonProperty("id") final String id, @JsonProperty("key") final String key) {
this.id = id;
this.key = key;
this.typeId = ReferenceTypeId.findEnum("cart");
}
public CartResourceIdentifierImpl() {
this.typeId = ReferenceTypeId.findEnum("cart");
}
public com.commercetools.api.models.common.ReferenceTypeId getTypeId() {
return this.typeId;
}
public String getId() {
return this.id;
}
public String getKey() {
return this.key;
}
public void setId(final String id) {
this.id = id;
}
public void setKey(final String key) {
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CartResourceIdentifierImpl that = (CartResourceIdentifierImpl) o;
return new EqualsBuilder().append(typeId, that.typeId).append(id, that.id).append(key, that.key).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37).append(typeId).append(id).append(key).toHashCode();
}
}
|
/*
* Copyright 2019 Antonio Sorrentini
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package me.as.lib.core.io.extra;
import me.as.lib.core.lang.ArrayExtras;
import me.as.lib.core.lang.StringExtras;
import java.io.*;
import static me.as.lib.core.lang.ByteExtras.javaByteToUnsignedByte;
public class SpeedBytesWrapper extends BytesRoomHandler
{
private byte content[];
private int offset=0;
// similar to setContent(byte bytes[]) but the bytes are not copied but used directly.
// This will work only for in memory implementation, all the others will revert to
// setContent(byte bytes[]).
// This is useful to avoid compying and recopying of buffers
public void mountContent(byte bytes[]) throws me.as.lib.core.io.IOException
{
offset=0;
setContent(bytes);
}
// similar to getContent() but the bytes returned are not copied but are the real internal buffer.
// after this method has executed currentPosition will reset to 0 and size will be 0
// This will work only for in memory implementation, all the others will revert to
// getContent() with the addition that internal data is deleted and currentPosition will reset to 0 and size will be 0
// This is useful to avoid compying and recopying of buffers
public byte[] unmountContent() throws me.as.lib.core.io.IOException
{
byte res[]=content;
content=null;
position=0;
offset=0;
return res;
}
public synchronized void setContent(byte bytes[], int offset)
{
this.offset=offset;
content=bytes;
position=0;
}
public synchronized void setContent(byte bytes[]) throws me.as.lib.core.io.IOException
{
content=bytes;
position=0;
offset=0;
}
public long getSize()
{
return ArrayExtras.length(content)-offset;
}
public boolean setSize(long newSize)
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
public boolean flush()
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
public boolean open(String mode) throws me.as.lib.core.io.IOException
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
public boolean close()
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
public int read() throws me.as.lib.core.io.IOException
{
int res=-1;
int pos=(int)position+offset;
if (pos<content.length)
{
res=javaByteToUnsignedByte(content[pos]);
position++;
}
return res;
/*
int res=ByteExtras.javaByteToUnsignedByte(content[(int)position+offset]);
position++;
return res;
*/
}
public int read(byte b[], int off, int len) throws me.as.lib.core.io.IOException
{
try
{
System.arraycopy(content, (int)position+offset, b, off, len);
position+=len;
return len;
}
catch (Throwable tr)
{
throw new me.as.lib.core.io.IOException(tr);
}
}
public void write(int b) throws me.as.lib.core.io.IOException
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
protected void writeBytes(byte b[], int off, int len) throws me.as.lib.core.io.IOException
{
throw new me.as.lib.core.io.IOException("This method is not supported!");
}
// this is not needed, it's just to speed it
public String readLine() throws me.as.lib.core.io.IOException
{
try
{
String res="";
char ch;
int start=(int)(position+offset);
int end=start-1;
boolean goon=(start<content.length);
while (goon)
{
++end;
ch=(char)(content[end] & 0xFF);
position++;
goon=(position<content.length && ch!='\n');
if (!goon)
{
while (end>start)
{
ch=(char)(content[end-1] & 0xFF);
if (ch=='\r') end--;
else
break;
}
if (end>start)
{
res=new String(content, start, end-start);
}
}
}
if (position>=content.length && StringExtras.length(res)==0) throw new IOException("EOF");
return res;
}
catch (Throwable tr)
{
throw new me.as.lib.core.io.IOException(tr);
}
}
}
|
/*
* Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*
*/
package com.sun.j3d.utils.scenegraph.io;
import java.io.File;
import java.io.IOException;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.SceneGraphObject;
import com.sun.j3d.utils.scenegraph.io.retained.RandomAccessFileControl;
import com.sun.j3d.utils.universe.SimpleUniverse;
/**
* Write a (set) of Java3D BranchGraphs and/or Universe to a file. The BranchGraphs
* are stored in the order in which they are written, they can be read in any order
* using SceneGraphFileReader.
*
* The API handles Nodes and NodeComponents that are shared between seperate
* graphs. It will handle all Java3D 1.3 core classes and any user
* subclass of a Node or NodeComponent that implements the SceneGraphIO
* interface.
*/
public class SceneGraphFileWriter extends java.lang.Object {
private RandomAccessFileControl fileControl;
private File file;
/** Creates new SceneGraphFileWriter and opens the file for writing.
*
* <P>Writes the
* Java3D Universe structure to the file. This includes the number and position of
* the Locales, PlatformGeometry, ViewerAvatar, and the MultitransformGroup between
* the ViewingPlatform and the View. However this
* call does not write the content of the branch graphs unless writeUniverseContent is true.
* <code>universe</code> may be null.
* This call will overwrite any existing universe, fileDescription and
* userData in the file.</P>
*
* <P>close() MUST be called when IO is complete. If close() is not called
* the file contents will be undefined.</P>
*
* @param file The file to write the data to
* @param universe The SimpleUniverse to write
* @param writeUniverseContent If true, the content of the Locales will be written.
* Otherwise just the universe configuration data will be written.
* @param fileDescription A description of the file's content
* @param fileUserData User defined object
*
* @exception IOException Thrown if there are any IO errors
* @exception UnsupportedUniverseException Thrown if <code>universe</code> is not
* a supported universe class. Currently SimpleUniverse and ConfiguredUniverse
* are supported.
*/
public SceneGraphFileWriter( java.io.File file,
SimpleUniverse universe,
boolean writeUniverseContent,
String fileDescription,
java.io.Serializable fileUserData) throws IOException, UnsupportedUniverseException {
fileControl = new RandomAccessFileControl();
this.file = file;
file.createNewFile();
if (!file.canWrite())
throw new IOException( "Can not Write to File" );
fileControl.createFile( file, universe, writeUniverseContent, fileDescription, fileUserData );
}
/**
* Write the graph to the end of the file.
*
* close() MUST be called when IO is complete. If close() is not called
* the file contents will be undefined.
*/
public void writeBranchGraph( BranchGroup graph ) throws IOException {
writeBranchGraph( graph, null );
}
/**
* Write a branch graph and some user associated data to the
* end of the file.
*
* close() MUST be called when IO is complete. If close() is not called
* the file contents will be undefined.
*/
public void writeBranchGraph( BranchGroup graph,
java.io.Serializable data ) throws IOException {
fileControl.writeBranchGraph( graph, data );
}
/**
* Add a named reference to a SceneGraphObject in the file.
*
* <code>object</code> must have been written to the file before this method is
* called. If the object is not in the file a NamedObjectException will be thrown.
*
* Adding duplicate names will result in the old name being overwritten.
* Different names can reference the same object
*/
public void addObjectName( String name, SceneGraphObject object ) throws NamedObjectException {
fileControl.addNamedObject( name, object );
}
/**
* Close the file and cleanup internal data structures.
*/
public void close() throws IOException {
fileControl.close();
}
}
|
package com.led.led;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Switch;
import com.rarepebble.colorpicker.ColorPickerView;
public class patternControl extends ActionBarActivity {
BluetoothProtocol proto;
Spinner patternListSpinner;
Switch reverseSwitch, oppositeSwitch, halfSwitch;
Spinner chaseNumberSpinner, strobeModeSpinner;
Button btnApply;
BluetoothProtocol.Patterns currentSelectedPattern;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pattern_control);
proto = (BluetoothProtocol)getIntent().getSerializableExtra("BluetoothProtocol");
patternListSpinner = (Spinner)findViewById(R.id.spinner2);
reverseSwitch = (Switch)findViewById(R.id.switchReverse);
oppositeSwitch = (Switch)findViewById(R.id.switchOpposite);
halfSwitch = (Switch)findViewById(R.id.switchHalf);
chaseNumberSpinner = (Spinner)findViewById(R.id.spinnerChaseNumber);
strobeModeSpinner = (Spinner)findViewById(R.id.spinnerStrobeMode);
btnApply = (Button)findViewById(R.id.buttonApply);
patternListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: //Strobe
currentSelectedPattern = BluetoothProtocol.Patterns.STROBE;
DisplayUiStrobe();
break;
case 1: //Chase
currentSelectedPattern = BluetoothProtocol.Patterns.CHASE;
DisplayUiChase();
break;
case 2: //Loading
currentSelectedPattern = BluetoothProtocol.Patterns.LOADING;
DisplayUiLoading();
break;
case 3: //Random
currentSelectedPattern = BluetoothProtocol.Patterns.RANDOM;
DisplayUiRandom();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnApply.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
applyPattern();
}
});
}
private void resetUi() {
reverseSwitch.setVisibility(View.INVISIBLE);
oppositeSwitch.setVisibility(View.INVISIBLE);
halfSwitch.setVisibility(View.INVISIBLE);
chaseNumberSpinner.setVisibility(View.INVISIBLE);
strobeModeSpinner.setVisibility(View.INVISIBLE);
}
private void DisplayUiStrobe() {
resetUi();
strobeModeSpinner.setVisibility(View.VISIBLE);
}
private void DisplayUiChase() {
resetUi();
reverseSwitch.setVisibility(View.VISIBLE);
oppositeSwitch.setVisibility(View.VISIBLE);
chaseNumberSpinner.setVisibility(View.VISIBLE);
}
private void DisplayUiLoading() {
resetUi();
reverseSwitch.setVisibility(View.VISIBLE);
oppositeSwitch.setVisibility(View.VISIBLE);
halfSwitch.setVisibility(View.VISIBLE);
}
private void DisplayUiRandom() {
resetUi();
}
private void applyPattern() {
switch (currentSelectedPattern) {
case STROBE:
proto.SetPatternStrobe(strobeModeSpinner.getSelectedItem().toString());
break;
case CHASE:
proto.SetPatternChase(chaseNumberSpinner.getSelectedItem().toString(), reverseSwitch.isChecked(), oppositeSwitch.isChecked());
break;
case LOADING:
proto.SetPatternLoading(reverseSwitch.isChecked(), oppositeSwitch.isChecked(), halfSwitch.isChecked());
break;
case RANDOM:
proto.SetPatternRandom();
break;
}
}
}
|
package or.kosta.mvc.dao;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import or.kosta.mvc.vo.Bbs1CommVo;
import or.kosta.mvc.vo.Bbs1Vo;
@Repository
public class Bbs1Dao {
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
// Spring에서 제공하는 Template를 사용하면 commit , close를 자동으로 해준다.
public void insertBbs1(Bbs1Vo vo){
sqlSessionTemplate.insert("bbs1.ins", vo);
}
public List<Bbs1Vo> getList(HashMap<String,Object> data){
return sqlSessionTemplate.selectList("bbs1.list",data);
}
public int Cnt(){
return sqlSessionTemplate.selectOne("bbs1.cnt");
}
public Bbs1Vo getDetail(int num){
return sqlSessionTemplate.selectOne("bbs1.detail",num);
}
public void insertComm(Bbs1CommVo vo){
sqlSessionTemplate.insert("bbs1.commIn", vo);
}
public List<Bbs1CommVo> getCommList(int kcode){
return sqlSessionTemplate.selectList("bbs1.commList",kcode);
}
public List<Bbs1Vo> getSearchList(HashMap<String,Object> data){
return sqlSessionTemplate.selectList("bbs1.searchlist", data);
}
public List<Bbs1Vo> searchDown(HashMap<String,Object> data){
return sqlSessionTemplate.selectList("bbs1.searchDown", data);
}
public int searchCnt(HashMap<String,Object> data){
return sqlSessionTemplate.selectOne("bbs1.searchcnt", data);
}
}
|
package com.hebin.yys.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.ImageView;
import com.hebin.yys.R;
import java.util.Random;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class WelcomeActivity extends AppCompatActivity {
@InjectView(R.id.iv_main)
ImageView ivMain;
private CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_welcome);
ButterKnife.inject(this);
int a = new Random().nextInt(23);
switch (a) {
case 0:
ivMain.setImageResource(R.mipmap.ic_welcome_01);
break;
case 1:
ivMain.setImageResource(R.mipmap.ic_welcome_02);
break;
case 2:
ivMain.setImageResource(R.mipmap.ic_welcome_03);
break;
case 3:
ivMain.setImageResource(R.mipmap.ic_welcome_04);
break;
case 4:
ivMain.setImageResource(R.mipmap.ic_welcome_05);
break;
case 5:
ivMain.setImageResource(R.mipmap.ic_welcome_06);
break;
case 6:
ivMain.setImageResource(R.mipmap.ic_welcome_07);
break;
case 7:
ivMain.setImageResource(R.mipmap.ic_welcome_08);
break;
case 8:
ivMain.setImageResource(R.mipmap.ic_welcome_09);
break;
case 9:
ivMain.setImageResource(R.mipmap.ic_welcome_10);
break;
case 10:
ivMain.setImageResource(R.mipmap.ic_welcome_11);
break;
case 11:
ivMain.setImageResource(R.mipmap.ic_welcome_12);
break;
case 12:
ivMain.setImageResource(R.mipmap.ic_welcome_13);
break;
case 13:
ivMain.setImageResource(R.mipmap.ic_welcome_14);
break;
case 14:
ivMain.setImageResource(R.mipmap.ic_welcome_15);
break;
case 15:
ivMain.setImageResource(R.mipmap.ic_welcome_16);
break;
case 16:
ivMain.setImageResource(R.mipmap.ic_welcome_17);
break;
case 17:
ivMain.setImageResource(R.mipmap.ic_welcome_18);
break;
case 18:
ivMain.setImageResource(R.mipmap.ic_welcome_19);
break;
case 19:
ivMain.setImageResource(R.mipmap.ic_welcome_20);
break;
case 20:
ivMain.setImageResource(R.mipmap.ic_welcome_21);
break;
case 21:
ivMain.setImageResource(R.mipmap.ic_welcome_22);
break;
default:
break;
}
setTime();
}
@Override
protected void onDestroy() {
countDownTimer.cancel();
super.onDestroy();
}
private void setTime() {
countDownTimer = new CountDownTimer(1500, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
finish();
}
}.start();
}
}
|
/*
* Copyright (c) 2005-2021 Radiance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.api.renderer;
import org.pushingpixels.substance.api.ComponentState;
import org.pushingpixels.substance.api.SubstanceCortex;
import org.pushingpixels.substance.api.SubstanceSlices;
import org.pushingpixels.substance.api.SubstanceSlices.ColorSchemeAssociationKind;
import org.pushingpixels.substance.api.colorscheme.SubstanceColorScheme;
import org.pushingpixels.substance.internal.animation.StateTransitionTracker;
import org.pushingpixels.substance.internal.animation.StateTransitionTracker.StateContributionInfo;
import org.pushingpixels.substance.internal.ui.SubstanceTreeUI;
import org.pushingpixels.substance.internal.ui.SubstanceTreeUI.TreePathId;
import org.pushingpixels.substance.internal.utils.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
import java.util.Map;
/**
* Default renderer for tree cells. Note that this does not extend {@link DefaultTreeCellRenderer}
* as other default renderers since that class overrides {@link Component#setBackground(Color)} and
* prevents the pass-through of {@link UIResource} colors that Substance sets for odd-even row
* striping.
*
* @author Kirill Grouchnikov
*/
@SubstanceRenderer
public class SubstanceDefaultTreeCellRenderer extends JLabel implements TreeCellRenderer,
ThemedIconAwareRenderer {
/**
* Last tree the renderer was painted in.
*/
private JTree tree;
/**
* Is the value currently selected.
*/
protected boolean selected;
/**
* True if has focus.
*/
protected boolean hasFocus;
private float rolloverArmAmount;
/**
* Returns a new instance of SubstanceDefaultTreeCellRenderer. Alignment is set to start
* aligned. Icons and text color are determined from the UIManager.
*/
public SubstanceDefaultTreeCellRenderer() {
this.setHorizontalAlignment(SwingConstants.LEADING);
SubstanceCortex.ComponentOrParentChainScope.setColorizationFactor(this, 1.0);
}
/**
* Returns the default icon that is used to represent non-leaf nodes that are expanded.
*
* @return The default icon for non-leaf expanded nodes.
*/
private Icon getDefaultOpenIcon() {
return UIManager.getIcon("Tree.openIcon");
}
/**
* Returns the default icon that is used to represent non-leaf nodes that are not expanded.
*
* @return The default icon for non-leaf non-expanded nodes.
*/
private Icon getDefaultClosedIcon() {
return UIManager.getIcon("Tree.closedIcon");
}
/**
* Returns the default icon that is used to represent leaf nodes.
*
* @return The default icon for leaf nodes.
*/
private Icon getDefaultLeafIcon() {
return UIManager.getIcon("Tree.leafIcon");
}
/**
* Subclassed to map <code>FontUIResource</code>s to null. If <code>font</code> is null, or a
* <code>FontUIResource</code>, this has the effect of letting the font of the JTree show
* through. On the other hand, if <code>font</code> is non-null, and not a
* <code>FontUIResource</code>, the font becomes <code>font</code>.
*/
@Override
public void setFont(Font font) {
if (font instanceof FontUIResource) {
font = null;
}
super.setFont(font);
}
/**
* Gets the font of this component.
*
* @return this component's font; if a font has not been set for this component, the font of its
* parent is returned
*/
@Override
public Font getFont() {
Font font = super.getFont();
if ((font == null) && (this.tree != null)) {
// Strive to return a non-null value, otherwise the html support
// will typically pick up the wrong font in certain situations.
font = this.tree.getFont();
}
return font;
}
/**
* Configures the renderer based on the passed in components. The value is set from messaging
* the tree with <code>convertValueToText</code>, which ultimately invokes <code>toString</code>
* on <code>value</code>. The foreground color is set based on the selection and the icon is set
* based on on leaf and expanded.
*/
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
String stringValue = tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus);
this.tree = tree;
this.hasFocus = hasFocus;
this.setText(stringValue);
this.rolloverArmAmount = 0.0f;
TreeUI treeUI = tree.getUI();
if (treeUI instanceof SubstanceTreeUI) {
SubstanceTreeUI ui = (SubstanceTreeUI) treeUI;
TreePathId pathId = new TreePathId(tree.getPathForRow(row));
StateTransitionTracker.ModelStateInfo modelStateInfo = ui.getModelStateInfo(pathId);
ComponentState currState = ui.getPathState(pathId);
// special case for drop location
JTree.DropLocation dropLocation = tree.getDropLocation();
boolean isDropLocation = (dropLocation != null)
&& (dropLocation.getChildIndex() == -1)
&& (tree.getRowForPath(dropLocation.getPath()) == row);
if (!isDropLocation && (modelStateInfo != null)) {
Map<ComponentState, StateContributionInfo> activeStates = modelStateInfo
.getStateContributionMap();
SubstanceColorScheme colorScheme = getColorSchemeForState(tree, ui, currState);
if (currState.isDisabled() || (activeStates == null)
|| (activeStates.size() == 1)) {
super.setForeground(new ColorUIResource(colorScheme.getForegroundColor()));
this.rolloverArmAmount = 0.0f;
} else {
float aggrRed = 0;
float aggrGreen = 0;
float aggrBlue = 0;
for (Map.Entry<ComponentState, StateTransitionTracker.StateContributionInfo> activeEntry :
modelStateInfo.getStateContributionMap().entrySet()) {
ComponentState activeState = activeEntry.getKey();
SubstanceColorScheme scheme = getColorSchemeForState(tree, ui, activeState);
Color schemeFg = scheme.getForegroundColor();
float contribution = activeEntry.getValue().getContribution();
if (activeState.isFacetActive(
SubstanceSlices.ComponentStateFacet.ROLLOVER) ||
activeState.isFacetActive(
SubstanceSlices.ComponentStateFacet.ARM)) {
this.rolloverArmAmount = Math.max(this.rolloverArmAmount, contribution);
}
aggrRed += schemeFg.getRed() * contribution;
aggrGreen += schemeFg.getGreen() * contribution;
aggrBlue += schemeFg.getBlue() * contribution;
}
super.setForeground(new ColorUIResource(
new Color((int) aggrRed, (int) aggrGreen, (int) aggrBlue)));
}
} else {
SubstanceColorScheme scheme = getColorSchemeForState(tree, ui, currState);
if (isDropLocation) {
scheme = SubstanceColorSchemeUtilities.getColorScheme(tree,
ColorSchemeAssociationKind.HIGHLIGHT, currState);
}
if (scheme != null) {
super.setForeground(new ColorUIResource(scheme.getForegroundColor()));
}
boolean isActive = currState.isFacetActive(SubstanceSlices.ComponentStateFacet.ROLLOVER)
|| currState.isFacetActive(SubstanceSlices.ComponentStateFacet.SELECTION)
|| currState.isFacetActive(SubstanceSlices.ComponentStateFacet.ARM);
this.rolloverArmAmount = isActive ? 1.0f : 0.0f;
}
} else {
if (sel) {
this.setForeground(UIManager.getColor("Tree.selectionForeground"));
} else {
this.setForeground(UIManager.getColor("Tree.textForeground"));
}
}
if (SubstanceCoreUtilities.isCurrentLookAndFeel()) {
SubstanceStripingUtils.applyStripedBackground(tree, row, this);
}
// There needs to be a way to specify disabled icons.
if (!tree.isEnabled()) {
this.setEnabled(false);
if (leaf) {
this.setDisabledIcon(SubstanceImageCreator.toGrayscale(
SubstanceImageCreator.withAlpha(tree, this.getDefaultLeafIcon(), 0.5)));
} else if (expanded) {
this.setDisabledIcon(SubstanceImageCreator.toGrayscale(
SubstanceImageCreator.withAlpha(tree, this.getDefaultOpenIcon(), 0.5)));
} else {
this.setDisabledIcon(SubstanceImageCreator.toGrayscale(
SubstanceImageCreator.withAlpha(tree, this.getDefaultClosedIcon(), 0.5)));
}
} else {
this.setEnabled(true);
if (leaf) {
this.setIcon(this.getDefaultLeafIcon());
} else if (expanded) {
this.setIcon(this.getDefaultOpenIcon());
} else {
this.setIcon(this.getDefaultClosedIcon());
}
}
this.setComponentOrientation(tree.getComponentOrientation());
this.setOpaque(false);
this.selected = sel;
if (treeUI instanceof SubstanceTreeUI) {
SubstanceTreeUI ui = (SubstanceTreeUI) treeUI;
Insets regInsets = ui.getCellRendererInsets();
this.setBorder(new BorderUIResource.EmptyBorderUIResource(regInsets));
}
return this;
}
@Override
public float getRolloverArmAmount() {
return this.rolloverArmAmount;
}
private SubstanceColorScheme getColorSchemeForState(JTree tree, SubstanceTreeUI ui,
ComponentState activeState) {
SubstanceColorScheme scheme = (activeState == ComponentState.ENABLED)
? ui.getDefaultColorScheme()
: SubstanceColorSchemeUtilities.getColorScheme(tree,
ColorSchemeAssociationKind.HIGHLIGHT, activeState);
if (scheme == null) {
scheme = SubstanceColorSchemeUtilities.getColorScheme(tree,
ColorSchemeAssociationKind.HIGHLIGHT, activeState);
}
return scheme;
}
/**
* Overrides <code>JComponent.getPreferredSize</code> to return slightly wider preferred size
* value.
*/
@Override
public Dimension getPreferredSize() {
Dimension retDimension = super.getPreferredSize();
if (retDimension != null) {
retDimension = new Dimension(retDimension.width + 3, retDimension.height);
}
return retDimension;
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void validate() {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void invalidate() {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void revalidate() {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void repaint(long tm, int x, int y, int width, int height) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void repaint(Rectangle r) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void repaint() {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if ("text".equals(propertyName))
super.firePropertyChange(propertyName, oldValue, newValue);
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, char oldValue, char newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, short oldValue, short newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, int oldValue, int newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, long oldValue, long newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, float oldValue, float newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, double oldValue, double newValue) {
}
/**
* Overridden for performance reasons. See the <a href="#override">Implementation Note</a> for
* more information.
*/
@Override
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
}
@Override
public final void paint(Graphics g) {
super.paint(g);
}
@Override
protected final void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
|
package io.jenkins.plugins.analysis.warnings;
import java.util.Collection;
import edu.hm.hafner.analysis.IssueParser;
import edu.hm.hafner.analysis.parser.SonarQubeDiffParser;
import edu.hm.hafner.analysis.parser.SonarQubeIssuesParser;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.kohsuke.stapler.DataBoundConstructor;
import org.jenkinsci.Symbol;
import hudson.Extension;
import io.jenkins.plugins.analysis.core.model.IconLabelProvider;
import io.jenkins.plugins.analysis.core.model.ReportScanningToolSuite;
import io.jenkins.plugins.analysis.core.model.StaticAnalysisLabelProvider;
/**
* Provides parsers and customized messages for SonarQube.
*
* @author Ullrich Hafner
*/
public class SonarQube extends ReportScanningToolSuite {
private static final long serialVersionUID = 2677209865301252855L;
static final String ID = "sonar";
/** Creates a new instance of {@link SonarQube}. */
@DataBoundConstructor
public SonarQube() {
super();
// empty constructor required for stapler
}
@Override
protected Collection<? extends IssueParser> getParsers() {
return asList(new SonarQubeIssuesParser(), new SonarQubeDiffParser());
}
/** Descriptor for this static analysis tool. */
@Symbol("sonarQube")
@Extension
public static class Descriptor extends ReportScanningToolDescriptor {
/** Creates the descriptor instance. */
public Descriptor() {
super(ID);
}
@NonNull
@Override
public String getDisplayName() {
return Messages.Warnings_SonarQube_ParserName();
}
@Override
public StaticAnalysisLabelProvider getLabelProvider() {
return new IconLabelProvider(getId(), getDisplayName());
}
@Override
public String getPattern() {
return "**/sonar-report.json";
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.test.stateless;
/**
* [1] Should be run as the first test suite of the BasicStatelessTestClients
*
* @version $Rev$ $Date$
*/
public class StatelessJndiTests extends BasicStatelessTestClient {
public StatelessJndiTests() {
super("JNDI.");
}
public void test01_initialContext() {
try {
assertNotNull("The InitialContext reference is null.", initialContext);
} catch (final Exception e) {
fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
}
public void test02_Jndi_lookupHome() {
try {
final Object obj = initialContext.lookup("client/tests/stateless/BasicStatelessHome");
ejbHome = (BasicStatelessHome) obj;
assertNotNull("The EJBHome is null", ejbHome);
} catch (final Exception e) {
fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
}
/* TO DO:
* public void test00_enterpriseBeanAccess()
* public void test00_jndiAccessToJavaCompEnv()
* public void test00_resourceManagerAccess()
*/
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.portfolio.transfer.data;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
import org.apache.fineract.infrastructure.core.exception.InvalidJsonException;
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.portfolio.client.api.ClientApiConstants;
import org.apache.fineract.portfolio.group.api.GroupingTypesApiConstants;
import org.apache.fineract.portfolio.transfer.api.TransferApiConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
@Component
public final class TransfersDataValidator {
private final FromJsonHelper fromApiJsonHelper;
@Autowired
public TransfersDataValidator(final FromJsonHelper fromApiJsonHelper) {
this.fromApiJsonHelper = fromApiJsonHelper;
}
private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
public void validateForClientsTransferBetweenGroups(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
TransferApiConstants.TRANSFER_CLIENTS_BETWEEN_GROUPS_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME);
final Long destinationGroupId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.destinationGroupIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.destinationGroupIdParamName).value(destinationGroupId).notNull()
.integerGreaterThanZero();
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.newStaffIdParamName, element)) {
final Long newStaffId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.newStaffIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.newStaffIdParamName).value(newStaffId).notNull()
.integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.inheritDestinationGroupLoanOfficer, element)) {
final Boolean inheritDestinationGroupLoanOfficer = this.fromApiJsonHelper.extractBooleanNamed(
TransferApiConstants.inheritDestinationGroupLoanOfficer, element);
baseDataValidator.reset().parameter(TransferApiConstants.inheritDestinationGroupLoanOfficer)
.value(inheritDestinationGroupLoanOfficer).notNull();
}
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateForProposeClientTransfer(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, TransferApiConstants.PROPOSE_CLIENT_TRANSFER_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final Long destinationOfficeId = this.fromApiJsonHelper
.extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.destinationOfficeIdParamName).value(destinationOfficeId).notNull()
.integerGreaterThanZero();
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateForAcceptClientTransfer(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, TransferApiConstants.ACCEPT_CLIENT_TRANSFER_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.newStaffIdParamName, element)) {
final Long newStaffId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.newStaffIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.newStaffIdParamName).value(newStaffId).notNull()
.integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.destinationGroupIdParamName, element)) {
final Long destinationGroupId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.destinationGroupIdParamName,
element);
baseDataValidator.reset().parameter(TransferApiConstants.destinationGroupIdParamName).value(destinationGroupId).notNull()
.integerGreaterThanZero();
}
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateTransferLoanOfficerToGroup(final String json){
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
TransferApiConstants.TRANSFER_LOAN_OFFICER_OF_GROUP);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final JsonElement element = this.fromApiJsonHelper.parse(json);
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME);
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.newStaffIdParamName, element)) {
final Long newStaffId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.newStaffIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.newStaffIdParamName).value(newStaffId).notNull()
.integerGreaterThanZero();
}
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateForProposeAndAcceptClientTransfer(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
TransferApiConstants.PROPOSE_AND_ACCEPT_CLIENT_TRANSFER_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final Long destinationOfficeId = this.fromApiJsonHelper
.extractLongNamed(TransferApiConstants.destinationOfficeIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.destinationOfficeIdParamName).value(destinationOfficeId).notNull()
.integerGreaterThanZero();
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.newStaffIdParamName, element)) {
final Long newStaffId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.newStaffIdParamName, element);
baseDataValidator.reset().parameter(TransferApiConstants.newStaffIdParamName).value(newStaffId).notNull()
.integerGreaterThanZero();
}
if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.destinationGroupIdParamName, element)) {
final Long destinationGroupId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.destinationGroupIdParamName,
element);
baseDataValidator.reset().parameter(TransferApiConstants.destinationGroupIdParamName).value(destinationGroupId).notNull()
.integerGreaterThanZero();
}
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateForRejectClientTransfer(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, TransferApiConstants.REJECT_CLIENT_TRANSFER_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
public void validateForWithdrawClientTransfer(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper
.checkForUnsupportedParameters(typeOfMap, json, TransferApiConstants.WITHDRAW_CLIENT_TRANSFER_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
validateNote(baseDataValidator, element);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
private void validateNote(final DataValidatorBuilder baseDataValidator, final JsonElement element) {
final String note = this.fromApiJsonHelper.extractStringNamed(TransferApiConstants.note, element);
baseDataValidator.reset().parameter(TransferApiConstants.note).value(note).notExceedingLengthOf(1000);
}
}
|
package com.ruoyi.mtms.service.Impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.mtms.domain.Morisky;
import com.ruoyi.mtms.mapper.MoriskyMapper;
import com.ruoyi.mtms.service.MoriskyService;
import org.springframework.stereotype.Service;
/**
* ${TODO}
*
* @author KING
* @version V1.0
* @date 2020/9/9 15:12
*/
@Service
public class MoriskyServiceImpl extends ServiceImpl<MoriskyMapper, Morisky> implements MoriskyService {
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.chat;
import com.azure.android.communication.chat.handwritten.models.AddChatParticipantsOptions;
import com.azure.android.communication.chat.handwritten.models.ChatMessage;
import com.azure.android.communication.chat.handwritten.models.ChatThread;
import com.azure.android.communication.chat.handwritten.models.ChatParticipant;
import com.azure.android.communication.chat.handwritten.models.ChatMessageReadReceipt;
import com.azure.android.communication.chat.handwritten.models.CreateChatThreadOptions;
import com.azure.android.communication.chat.handwritten.models.CreateChatThreadResult;
import com.azure.android.communication.chat.handwritten.models.SendChatMessageOptions;
import com.azure.android.communication.chat.handwritten.models.UpdateChatMessageOptions;
import com.azure.android.communication.common.CommunicationUserIdentifier;
import com.azure.android.communication.common.CommunicationTokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;
import com.azure.core.http.rest.PagedIterable;
import java.util.ArrayList;
import java.util.List;
/**
* WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS
* ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING
* LINE NUMBERS OF EXISTING CODE SAMPLES.
*
* Class containing code snippets that will be injected to README.md.
*/
public class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https://<RESOURCE_NAME>.communcationservices.azure.com";
// Create an HttpClient builder of your choice and customize it
// Use com.azure.core.http.netty.NettyAsyncHttpClientBuilder if that suits your needs
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
// Your user access token retrieved from your trusted service
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
// Initialize the chat client
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
public void getChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
}
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
String chatMessageId = chatThreadClient.sendMessage(sendChatMessageOptions).getId();
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessages = chatThreadClient.listMessages();
chatMessages.forEach(chatMessage -> {
// You code to handle single chatMessage
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipants = chatThreadClient.listParticipants();
chatParticipants.forEach(chatParticipant -> {
// You code to handle single chatParticipant
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier identifier = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(identifier);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceipts = chatThreadClient.listReadReceipts();
readReceipts.forEach(readReceipt -> {
// You code to handle single readReceipt
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
}
|
package jetbrains.mps.lang.editor.findUsages;
/*Generated by MPS */
import jetbrains.mps.ide.findusages.findalgorithm.finders.GeneratedFinder;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import java.util.Objects;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.editor.behavior.IMenu_Concept__BehaviorDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.module.SearchScope;
import jetbrains.mps.ide.findusages.findalgorithm.finders.IFinder;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import java.util.List;
import jetbrains.mps.ide.findusages.view.FindUtils;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.model.SNodeReference;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SReferenceLink;
public class TMDefaultMenuReferences_Finder extends GeneratedFinder {
public TMDefaultMenuReferences_Finder() {
}
@Override
public boolean isUsedByDefault(SNode node) {
return true;
}
@Override
public String getDescription() {
return "Default Menu References";
}
@Override
public String getLongDescription() {
return "";
}
@Override
public SAbstractConcept getSConcept() {
return CONCEPTS.TransformationMenu$bn;
}
@Override
public boolean isApplicable(SNode node) {
return !((Objects.equals(SNodeOperations.getConcept(node), CONCEPTS.TransformationMenu_Default$TY))) && (boolean) IMenu_Concept__BehaviorDescriptor.isDefault_id5N_GIFFh1P5.invoke(node);
}
@Override
protected void doFind0(@NotNull SNode node, SearchScope scope, IFinder.FindCallback callback, ProgressMonitor monitor) {
try {
monitor.start("All default menu references", 2);
try {
List<SNode> allReferences = (List<SNode>) FindUtils.executeFinder("jetbrains.mps.lang.structure.findUsages.ConceptInstances_Finder", SNodeOperations.getNode("r:00000000-0000-4000-0000-011c8959029e(jetbrains.mps.lang.editor.structure)", "6718020819487620876"), scope, monitor.subTask(1));
for (SNode ref : ListSequence.fromList(allReferences)) {
if (SLinkOperations.getTarget(ref, LINKS.concept$kjNG) == SLinkOperations.getTarget(node, LINKS.conceptDeclaration$h3E)) {
callback.onUsageFound(createSingleResult(ref));
}
}
} finally {
monitor.done();
}
} finally {
monitor.done();
}
}
@Override
public String getNodeCategory(SNode node) {
return "Default Menu References";
}
@Nullable
@Override
public SNodeReference getDeclarationNode() {
return buildNodePointer(FindUsagesDescriptor.DECLARING_MODEL, "5219382839346759760");
}
private static final class CONCEPTS {
/*package*/ static final SConcept TransformationMenu$bn = MetaAdapterFactory.getConcept(0x18bc659203a64e29L, 0xa83a7ff23bde13baL, 0x4e0f93d8a0ac3ebaL, "jetbrains.mps.lang.editor.structure.TransformationMenu");
/*package*/ static final SConcept TransformationMenu_Default$TY = MetaAdapterFactory.getConcept(0x18bc659203a64e29L, 0xa83a7ff23bde13baL, 0x16be955f384efce1L, "jetbrains.mps.lang.editor.structure.TransformationMenu_Default");
}
private static final class LINKS {
/*package*/ static final SReferenceLink conceptDeclaration$h3E = MetaAdapterFactory.getReferenceLink(0x18bc659203a64e29L, 0xa83a7ff23bde13baL, 0x169efbc9a9048c53L, 0x5b7b4c4d511049b4L, "conceptDeclaration");
/*package*/ static final SReferenceLink concept$kjNG = MetaAdapterFactory.getReferenceLink(0x18bc659203a64e29L, 0xa83a7ff23bde13baL, 0x169efbc9a90a41c1L, 0x169efbc9a91440deL, "concept");
}
}
|
/* *****************************************************************************
*
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.examples.advanced.features.transferlearning.editlastlayer.presave;
import org.deeplearning4j.examples.advanced.features.transferlearning.iterators.FlowerDataSetIteratorFeaturized;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.nn.transferlearning.FineTuneConfiguration;
import org.deeplearning4j.nn.transferlearning.TransferLearning;
import org.deeplearning4j.nn.transferlearning.TransferLearningHelper;
import org.deeplearning4j.zoo.ZooModel;
import org.deeplearning4j.zoo.model.VGG16;
import org.nd4j.evaluation.classification.Evaluation;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.learning.config.Nesterovs;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.slf4j.Logger;
import java.io.IOException;
/**
* @author susaneraly on 3/10/17.
*
* Important:
* Run the class "FeaturizePreSave" before attempting to run this. The outputs at the boundary of the frozen and unfrozen
* vertices of a model are saved. These are referred to as "featurized" datasets in this description.
* On a dataset of about 3000 images which is what is downloaded this can take "a while"
*
* Here we see how the transfer learning helper can be used to fit from a featurized datasets.
* We attempt to train the same model architecture as the one in "EditLastLayerOthersFrozen".
* Since the helper avoids the forward pass through the frozen layers we save on computation time when running multiple epochs.
* In this manner, users can iterate quickly tweaking learning rates, weight initialization etc` to settle on a model that gives good results.
*/
@SuppressWarnings("DuplicatedCode")
public class FitFromFeaturized {
private static final Logger log = org.slf4j.LoggerFactory.getLogger(FitFromFeaturized.class);
private static final String featureExtractionLayer = FeaturizedPreSave.featurizeExtractionLayer;
protected static final long seed = 12345;
protected static final int numClasses = 5;
protected static final int nEpochs = 3;
public static void main(String [] args) throws IOException {
//Import vgg
//Note that the model imported does not have an output layer (check printed summary)
// nor any training related configs (model from keras was imported with only weights and json)
log.info("\n\nLoading org.deeplearning4j.transferlearning.vgg16...\n\n");
ZooModel zooModel = VGG16.builder().build();
ComputationGraph vgg16 = (ComputationGraph) zooModel.initPretrained();
log.info(vgg16.summary());
//Decide on a fine tune configuration to use.
//In cases where there already exists a setting the fine tune setting will
// override the setting for all layers that are not "frozen".
FineTuneConfiguration fineTuneConf = new FineTuneConfiguration.Builder()
.updater(new Nesterovs(3e-5, 0.9))
.seed(seed)
.build();
//Construct a new model with the intended architecture and print summary
ComputationGraph vgg16Transfer = new TransferLearning.GraphBuilder(vgg16)
.fineTuneConfiguration(fineTuneConf)
.setFeatureExtractor(featureExtractionLayer) //the specified layer and below are "frozen"
.removeVertexKeepConnections("predictions") //replace the functionality of the final vertex
.addLayer("predictions",
new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nIn(4096).nOut(numClasses)
.weightInit(new NormalDistribution(0,0.2*(2.0/(4096+numClasses)))) //This weight init dist gave better results than Xavier
.activation(Activation.SOFTMAX).build(),
"fc2")
.build();
log.info(vgg16Transfer.summary());
DataSetIterator trainIter = FlowerDataSetIteratorFeaturized.trainIterator();
DataSetIterator testIter = FlowerDataSetIteratorFeaturized.testIterator();
//Instantiate the transfer learning helper to fit and output from the featurized dataset
//The .unfrozenGraph() is the unfrozen subset of the computation graph passed in.
//If using with a UI or a listener attach them directly to the unfrozenGraph instance
//With each iteration updated params from unfrozenGraph are copied over to the original model
TransferLearningHelper transferLearningHelper = new TransferLearningHelper(vgg16Transfer);
log.info(transferLearningHelper.unfrozenGraph().summary());
for (int epoch = 0; epoch < nEpochs; epoch++) {
if (epoch == 0) {
Evaluation eval = transferLearningHelper.unfrozenGraph().evaluate(testIter);
log.info("Eval stats BEFORE fit.....");
log.info(eval.stats()+"\n");
testIter.reset();
}
int iter = 0;
while (trainIter.hasNext()) {
transferLearningHelper.fitFeaturized(trainIter.next());
if (iter % 10 == 0) {
log.info("Evaluate model at iter " + iter + " ....");
Evaluation eval = transferLearningHelper.unfrozenGraph().evaluate(testIter);
log.info(eval.stats());
testIter.reset();
}
iter++;
}
trainIter.reset();
log.info("Epoch #"+epoch+" complete");
}
log.info("Model build complete");
}
}
|
package ca.ualberta.cs.travelexpensetracker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
public class Claim {
private int startDate;
private int endDate;
String status;
String description;
String name;
ArrayList<Expense> expenseList;
static final String IN_PROGRESS = "In Progress";
static final String SUBMITTED = "Submitted";
static final String RETURNED = "Returned";
static final String APPROVED = "Approved";
public Claim(int startDate, int endDate,String description,String name){
this.startDate = startDate;
this.endDate = endDate;
this.description = description;
this.expenseList = new ArrayList<Expense>();
this.status = IN_PROGRESS;
this.name = name;
}
public void editClaim(int startDate, int endDate,String description,String name){
this.startDate = startDate;
this.endDate = endDate;
this.description = description;
this.name= name;
}
public ArrayList<Expense> getExpenseList(){
return this.expenseList;
}
public void addExpense(Expense expense){
this.expenseList.add(expense);
Collections.sort(expenseList, new Comparator<Expense>() {
@Override
public int compare(Expense expense1, Expense expense2){
if (expense1.getDate()<expense2.getDate()){
return -1;
}
if (expense1.getDate()>expense2.getDate()){
return 1;
}
return 0;
}
});
}
public void removeExpense(Expense expense){
this.expenseList.remove(expense);
}
public String toString(){
return "["+this.status+"] "+name+" From: "+
Integer.toString(this.startDate).substring(0, 4)+"/"+
Integer.toString(this.startDate).substring(4, 6)+"/"+
Integer.toString(this.startDate).substring(6, 8)+
" - To: "+
Integer.toString(this.endDate).substring(0, 4)+"/"+
Integer.toString(this.endDate).substring(4, 6)+"/"+
Integer.toString(this.endDate).substring(6, 8);
}
public String getStatus() {
return this.status;
}
public int getStartDate() {
return this.startDate;
}
public int getEndDate() {
return this.endDate;
}
public String getDescription(){
return this.description;
}
public boolean isLocked(){
if (status.equals(SUBMITTED)){
return true;
}
if (status.equals(APPROVED)){
return true;
}
return false;
}
public void submit() {
this.status = SUBMITTED;
}
public void approve(){
this.status = APPROVED;
}
public void returnClaim(){
this.status = RETURNED;
}
public String getName() {
return name;
}
}
|
package com.bizzan.bitrade.controller;
import static com.bizzan.bitrade.constant.SysConstant.SESSION_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import com.bizzan.bitrade.entity.MiningOrder;
import com.bizzan.bitrade.entity.MiningOrderDetail;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.service.MiningOrderDetailService;
import com.bizzan.bitrade.service.MiningOrderService;
import com.bizzan.bitrade.util.DateUtil;
import com.bizzan.bitrade.util.MessageResult;
@RestController
@RequestMapping("miningorder")
public class MiningOrderController extends BaseController {
@Autowired
private MiningOrderService miningOrderService;
@Autowired
private MiningOrderDetailService miningOrderDetailService;
/**
* 我的矿机列表
* @param member
* @param pageNo
* @param pageSize
* @return
*/
@RequestMapping("my-minings")
public MessageResult page(@SessionAttribute(SESSION_MEMBER) AuthMember member, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
Assert.notNull(member, "The login timeout!");
MessageResult mr = new MessageResult();
Page<MiningOrder> all = miningOrderService.findAllByMemberIdPage(member.getId(), pageNo, pageSize);
long currentTime = DateUtil.getCurrentDate().getTime();
for(int i = 0; i < all.getContent().size(); i++) {
// 已超时
if(currentTime > all.getContent().get(i).getEndTime().getTime()) {
all.getContent().get(i).setMiningStatus(2); // 已结束
}
// 超出天数
if(all.getContent().get(i).getMiningedDays() >= all.getContent().get(i).getMiningDays()) {
all.getContent().get(i).setMiningStatus(2); // 已结束
}
}
mr.setCode(0);
mr.setData(all);
return mr;
}
/**
* 获取指定矿机详情
* @param member
* @param miningId
* @return
*/
@RequestMapping("my-mining-detail")
public MessageResult miningDetail(@SessionAttribute(SESSION_MEMBER) AuthMember member, Long miningId) {
Assert.notNull(member, "The login timeout!");
Assert.notNull(miningId, "矿机不存在!");
MiningOrder mo = miningOrderService.findOne(miningId);
if(mo != null) {
if(mo.getMemberId().longValue() != member.getId()) {
return error("非法访问");
}
long currentTime = DateUtil.getCurrentDate().getTime();
if(currentTime > mo.getEndTime().getTime()) {
mo.setMiningStatus(2);
}
if(mo.getMiningedDays() >= mo.getMiningDays()) {
mo.setMiningStatus(2);
}
return success(mo);
}else {
return error("矿机不存在");
}
}
/**
* 矿机产出明细
* @param member
* @param miningId
* @param pageNo
* @param pageSize
* @return
*/
@RequestMapping("mining-detail")
public MessageResult miningDetail(@SessionAttribute(SESSION_MEMBER) AuthMember member,
@RequestParam(value = "miningId", defaultValue = "1") Long miningId,
@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
Assert.notNull(member, "The login timeout!");
Assert.notNull(miningId, "矿机不存在!");
MiningOrder mining = miningOrderService.findOne(miningId);
Assert.notNull(mining, "矿机不存在!");
if(mining.getMemberId().longValue() != member.getId()) {
return error("非法访问");
}
Page<MiningOrderDetail> all = miningOrderDetailService.findAllByMiningOrderId(miningId, pageNo, pageSize);
return success(all);
}
}
|
// This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
// SPDX-FileCopyrightText: 2014-2017 Université Grenoble Alpes
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.cpachecker.cpa.policyiteration;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.cpachecker.util.Pair;
import org.sosy_lab.cpachecker.util.predicates.smt.BooleanFormulaManagerView.BooleanFormulaTransformationVisitor;
import org.sosy_lab.cpachecker.util.predicates.smt.FormulaManagerView;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.Model.ValueAssignment;
import org.sosy_lab.java_smt.api.Tactic;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
public class FormulaLinearizationManager {
private final BooleanFormulaManager bfmgr;
private final FormulaManagerView fmgr;
private final PolicyIterationStatistics statistics;
private static final String CHOICE_VAR_NAME = "__POLICY_CHOICE_";
private final UniqueIdGenerator choiceVarCounter = new UniqueIdGenerator();
public FormulaLinearizationManager(
FormulaManagerView pFmgr,
PolicyIterationStatistics pStatistics) {
bfmgr = pFmgr.getBooleanFormulaManager();
fmgr = pFmgr;
statistics = pStatistics;
}
/**
* Convert non-concave statements into disjunctions.
*
* At the moment handles:
*
* x NOT(EQ(A, B)) => (A > B) \/ (A < B)
*/
public BooleanFormula linearize(BooleanFormula input) {
return bfmgr.transformRecursively(input, new BooleanFormulaTransformationVisitor(fmgr) {
@Override
public BooleanFormula visitNot(BooleanFormula pOperand) {
List<BooleanFormula> split = fmgr.splitNumeralEqualityIfPossible(pOperand);
// Pattern matching on (NOT (= A B)).
if (split.size() == 2) {
return bfmgr.or(
bfmgr.not(split.get(0)), bfmgr.not(split.get(1))
);
}
return super.visitNot(pOperand);
}
});
}
/**
* Annotate disjunctions with choice variables.
*/
public BooleanFormula annotateDisjunctions(BooleanFormula input)
throws InterruptedException {
input = fmgr.applyTactic(input, Tactic.NNF);
return bfmgr.transformRecursively(
input, new BooleanFormulaTransformationVisitor(fmgr) {
@Override
public BooleanFormula visitOr(List<BooleanFormula> processedOperands) {
return annotateDisjunction(processedOperands);
}
});
}
private BooleanFormula annotateDisjunction(List<BooleanFormula> args) {
assert !args.isEmpty();
if (args.size() == 1) {
return args.get(0);
} else {
BooleanFormula choiceVar = bfmgr.makeVariable(getFreshVarName());
int pivot = args.size() / 2;
return bfmgr.or(
bfmgr.and(
choiceVar,
annotateDisjunction(args.subList(0, pivot))
),
bfmgr.and(
bfmgr.not(choiceVar),
annotateDisjunction(args.subList(pivot, args.size()))
)
);
}
}
private String getFreshVarName() {
return CHOICE_VAR_NAME + choiceVarCounter.getFreshId();
}
/**
* Removes disjunctions from the {@code input} formula, by replacing them
* with arguments which were used to generate the {@code model}.
*/
public BooleanFormula enforceChoice(
final BooleanFormula input,
final Model model
) throws InterruptedException {
// TODO: more efficient to call #evaluate() on the subset of variables
// which we actually use.
// These models can be huge.
Map<Formula, Formula> mapping = new HashMap<>();
for (ValueAssignment entry : model) {
String termName = entry.getName();
if (termName.contains(CHOICE_VAR_NAME)) {
mapping.put(
bfmgr.makeVariable(termName),
bfmgr.makeBoolean((boolean) entry.getValue()));
}
}
BooleanFormula pathSelected = fmgr.substitute(input, mapping);
pathSelected = fmgr.simplify(pathSelected);
return pathSelected;
}
/**
* Removes UFs and ITEs from the formula, effectively making it's semantics
* "concave".
*/
public BooleanFormula convertToPolicy(BooleanFormula f,
Model pModel) throws InterruptedException {
statistics.ackermannizationTimer.start();
f = fmgr.applyTactic(f, Tactic.NNF);
// Get rid of UFs.
BooleanFormula out = processUFs(f, pModel);
statistics.ackermannizationTimer.stop();
return out;
}
/**
* Ackermannization:
* Requires a fixpoint computation as UFs can take other UFs as arguments.
* First removes UFs with no arguments, etc.
*/
private BooleanFormula processUFs(BooleanFormula f, Model model) {
Multimap<String, Pair<Formula, List<Formula>>> UFs = findUFs(f);
Map<Formula, Formula> substitution = new HashMap<>();
List<BooleanFormula> extraConstraints = new ArrayList<>();
for (String funcName : UFs.keySet()) {
List<Pair<Formula, List<Formula>>> ufList = new ArrayList<>(UFs.get(funcName));
for (int idx1=0; idx1<ufList.size(); idx1++) {
Pair<Formula, List<Formula>> p = ufList.get(idx1);
Formula uf = p.getFirst();
List<Formula> args = p.getSecondNotNull();
Formula freshVar = fmgr.makeVariable(fmgr.getFormulaType(uf),
freshUFName(idx1));
substitution.put(uf, freshVar);
for (int idx2=idx1+1; idx2<ufList.size(); idx2++) {
Pair<Formula, List<Formula>> p2 = ufList.get(idx2);
List<Formula> otherArgs = p2.getSecondNotNull();
Formula otherUF = p2.getFirst();
// If UFs are equal under the given model, force them to be equal in
// the resulting policy bound.
Preconditions.checkState(args.size() == otherArgs.size());
boolean argsEqual = true;
for (int i = 0; i<args.size(); i++) {
Object evalA = model.evaluate(args.get(i));
Object evalB = model.evaluate(otherArgs.get(i));
if (evalA != null && evalB != null && !evalA.equals(evalB)) {
argsEqual = false;
}
}
if (argsEqual) {
Formula otherFreshVar = fmgr.makeVariable(
fmgr.getFormulaType(otherUF),
freshUFName(idx2)
);
extraConstraints.add(fmgr.makeEqual(freshVar, otherFreshVar));
}
}
}
}
// Get rid of UFs.
BooleanFormula formulaNoUFs = fmgr.substitute(f, substitution);
return bfmgr.and(
formulaNoUFs, bfmgr.and(extraConstraints)
);
}
private Multimap<String, Pair<Formula, List<Formula>>> findUFs(Formula f) {
final Multimap<String, Pair<Formula, List<Formula>>> UFs = HashMultimap.create();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<TraversalProcess>() {
@Override
protected TraversalProcess visitDefault(Formula pFormula) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula pFormula, List<Formula> args, FunctionDeclaration<?> decl) {
if (decl.getKind() == FunctionDeclarationKind.UF) {
UFs.put(decl.getName(), Pair.of(pFormula, args));
}
return TraversalProcess.CONTINUE;
}
});
return UFs;
}
private String freshUFName(int idx) {
return "__UF_fresh_" + idx;
}
}
|
package com.andela.app.animationchallenge.view;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.andela.app.animationchallenge.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO: Check if the user is already connected
if(false) {
// TODO: Switch to SignInActivity
}
}
}
|
/**
* Copyright 2018 大法医开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.renren.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.entity.UserEntity;
import io.renren.form.LoginForm;
import java.util.Map;
/**
* 用户
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017-03-23 15:22:06
*/
public interface UserService extends IService<UserEntity> {
UserEntity queryByMobile(String mobile);
/**
* 用户登录
* @param form 登录表单
* @return 返回登录信息
*/
Map<String, Object> login(LoginForm form);
}
|
package e.a.a.a;
import e.a.a.a.y0.b.f0;
import e.a.a.a.y0.b.i0;
import e.a.a.a.y0.b.s;
import e.a.a.a.y0.b.w0;
import e.a.a.a.y0.f.d;
import e.a.a.a.y0.i.c;
import e.a.a.a.y0.m.d0;
import e.t.g;
import e.x.b.l;
import e.x.c.i;
import e.x.c.k;
import java.util.List;
public final class r0 {
public static final c a = c.a;
/* renamed from: b reason: collision with root package name */
public static final r0 f7577b = null;
public static final class a extends k implements l<w0, CharSequence> {
/* renamed from: h reason: collision with root package name */
public static final a f7578h = new a();
public a() {
super(1);
}
public Object invoke(Object obj) {
w0 w0Var = (w0) obj;
r0 r0Var = r0.f7577b;
i.d(w0Var, "it");
d0 d = w0Var.d();
i.d(d, "it.type");
return r0.e(d);
}
}
public static final void a(StringBuilder sb, i0 i0Var) {
if (i0Var != null) {
d0 d = i0Var.d();
i.d(d, "receiver.type");
sb.append(e(d));
sb.append(".");
}
}
public static final void b(StringBuilder sb, e.a.a.a.y0.b.a aVar) {
i0 g2 = v0.g(aVar);
i0 U = aVar.U();
a(sb, g2);
boolean z = (g2 == null || U == null) ? false : true;
if (z) {
sb.append("(");
}
a(sb, U);
if (z) {
sb.append(")");
}
}
public static final String c(s sVar) {
i.e(sVar, "descriptor");
StringBuilder sb = new StringBuilder();
sb.append("fun ");
b(sb, sVar);
c cVar = a;
d name = sVar.getName();
i.d(name, "descriptor.name");
sb.append(cVar.v(name, true));
List<w0> n2 = sVar.n();
i.d(n2, "descriptor.valueParameters");
g.v(n2, sb, ", ", "(", ")", 0, (CharSequence) null, a.f7578h, 48);
sb.append(": ");
d0 f = sVar.f();
i.c(f);
i.d(f, "descriptor.returnType!!");
sb.append(e(f));
String sb2 = sb.toString();
i.d(sb2, "StringBuilder().apply(builderAction).toString()");
return sb2;
}
public static final String d(f0 f0Var) {
i.e(f0Var, "descriptor");
StringBuilder sb = new StringBuilder();
sb.append(f0Var.Q() ? "var " : "val ");
b(sb, f0Var);
c cVar = a;
d name = f0Var.getName();
i.d(name, "descriptor.name");
sb.append(cVar.v(name, true));
sb.append(": ");
d0 d = f0Var.d();
i.d(d, "descriptor.type");
sb.append(e(d));
String sb2 = sb.toString();
i.d(sb2, "StringBuilder().apply(builderAction).toString()");
return sb2;
}
public static final String e(d0 d0Var) {
i.e(d0Var, "type");
return a.w(d0Var);
}
}
|
package com.softmax.eurekaribbon;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EurekaRibbonApplicationTests {
@Test
public void contextLoads() {
}
}
|
/**
* Find Security Bugs
* Copyright (c) Philippe Arteau, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package com.h3xstream.findsecbugs.injection.sql;
import com.h3xstream.findsecbugs.injection.BasicInjectionDetector;
import com.h3xstream.findsecbugs.taintanalysis.Taint;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Priorities;
public class SqlInjectionDetector extends BasicInjectionDetector {
public SqlInjectionDetector(BugReporter bugReporter) {
super(bugReporter);
loadConfiguredSinks("sql-hibernate.txt", "SQL_INJECTION_HIBERNATE");
loadConfiguredSinks("sql-jdo.txt", "SQL_INJECTION_JDO");
loadConfiguredSinks("sql-jpa.txt", "SQL_INJECTION_JPA");
loadConfiguredSinks("sql-jdbc.txt", "SQL_INJECTION_JDBC");
loadConfiguredSinks("sql-spring.txt", "SQL_INJECTION_SPRING_JDBC");
loadConfiguredSinks("sql-scala-slick.txt", "SCALA_SQL_INJECTION_SLICK");
loadConfiguredSinks("sql-scala-anorm.txt", "SCALA_SQL_INJECTION_ANORM");
loadConfiguredSinks("sql-turbine.txt", "SQL_INJECTION_TURBINE");
//TODO : Add org.springframework.jdbc.core.simple.SimpleJdbcTemplate (Spring < 3.2.1)
}
@Override
protected int getPriority(Taint taint) {
if (!taint.isSafe() && taint.hasTag(Taint.Tag.SQL_INJECTION_SAFE)) {
return Priorities.IGNORE_PRIORITY;
} else if (!taint.isSafe() && taint.hasTag(Taint.Tag.APOSTROPHE_ENCODED)) {
return Priorities.LOW_PRIORITY;
} else {
return super.getPriority(taint);
}
}
}
|
package com.example.app.domains.remoteconfig.repositories;
import com.example.app.domains.remoteconfig.models.entities.RemoteConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RemoteConfigRepository extends JpaRepository<RemoteConfig, Long> {
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.distributed;
import org.apache.geode.distributed.AbstractLauncher.Status;
import org.apache.geode.distributed.LocatorLauncher.Builder;
import org.apache.geode.distributed.LocatorLauncher.LocatorState;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.*;
import org.apache.geode.internal.net.SocketCreatorFactory;
import org.apache.geode.internal.process.ProcessControllerFactory;
import org.apache.geode.internal.process.ProcessType;
import org.apache.geode.internal.process.ProcessUtils;
import org.apache.geode.internal.security.SecurableCommunicationChannel;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.BindException;
import java.net.InetAddress;
import static org.apache.geode.distributed.ConfigurationProperties.*;
import static org.junit.Assert.*;
/**
* Tests usage of LocatorLauncher as a local API in existing JVM.
*
* @since GemFire 8.0
*/
@Category(IntegrationTest.class)
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
public class LocatorLauncherLocalIntegrationTest
extends AbstractLocatorLauncherIntegrationTestCase {
@Before
public final void setUpLocatorLauncherLocalIntegrationTest() throws Exception {
disconnectFromDS();
System.setProperty(ProcessType.TEST_PREFIX_PROPERTY, getUniqueName() + "-");
}
@After
public final void tearDownLocatorLauncherLocalIntegrationTest() throws Exception {
disconnectFromDS();
}
@Test
public void testBuilderSetProperties() throws Throwable {
this.launcher = new Builder().setForce(true).setMemberName(getUniqueName())
.setPort(this.locatorPort).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory)
.set(DISABLE_AUTO_RECONNECT, "true").set(LOG_LEVEL, "config").set(MCAST_PORT, "0").build();
try {
assertEquals(Status.ONLINE, this.launcher.start().getStatus());
waitForLocatorToStart(this.launcher, true);
final InternalLocator locator = this.launcher.getLocator();
assertNotNull(locator);
final DistributedSystem distributedSystem = locator.getDistributedSystem();
assertNotNull(distributedSystem);
assertEquals("true", distributedSystem.getProperties().getProperty(DISABLE_AUTO_RECONNECT));
assertEquals("0", distributedSystem.getProperties().getProperty(MCAST_PORT));
assertEquals("config", distributedSystem.getProperties().getProperty(LOG_LEVEL));
assertEquals(getUniqueName(), distributedSystem.getProperties().getProperty(NAME));
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
assertNull(this.launcher.getLocator());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testIsAttachAPIFound() throws Exception {
final ProcessControllerFactory factory = new ProcessControllerFactory();
assertTrue(factory.isAttachAPIFound());
}
@Test
public void testStartCreatesPidFile() throws Throwable {
this.launcher = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config")
.build();
try {
this.launcher.start();
waitForLocatorToStart(this.launcher);
assertEquals(Status.ONLINE, this.launcher.status().getStatus());
// validate the pid file and its contents
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue(this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertTrue(ProcessUtils.isProcessAlive(pid));
assertEquals(getPid(), pid);
assertEquals(Status.ONLINE, this.launcher.status().getStatus());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testStartDeletesStaleControlFiles() throws Throwable {
// create existing control files
this.stopRequestFile =
new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getStopRequestFileName());
this.stopRequestFile.createNewFile();
assertTrue(this.stopRequestFile.exists());
this.statusRequestFile =
new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getStatusRequestFileName());
this.statusRequestFile.createNewFile();
assertTrue(this.statusRequestFile.exists());
this.statusFile =
new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getStatusFileName());
this.statusFile.createNewFile();
assertTrue(this.statusFile.exists());
// build and start the locator
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
this.launcher.start();
try {
waitForLocatorToStart(this.launcher);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
// validate the pid file and its contents
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue(this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertTrue(ProcessUtils.isProcessAlive(pid));
assertEquals(getPid(), pid);
// validate stale control files were deleted
assertFalse(stopRequestFile.exists());
assertFalse(statusRequestFile.exists());
assertFalse(statusFile.exists());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testStartOverwritesStalePidFile() throws Throwable {
// create existing pid file
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertFalse("Integer.MAX_VALUE shouldn't be the same as local pid " + Integer.MAX_VALUE,
Integer.MAX_VALUE == ProcessUtils.identifyPid());
writePid(this.pidFile, Integer.MAX_VALUE);
// build and start the locator
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
this.launcher.start();
try {
waitForLocatorToStart(this.launcher);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
// validate the pid file and its contents
assertTrue(this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertTrue(ProcessUtils.isProcessAlive(pid));
assertEquals(getPid(), pid);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
@Ignore("Need to rewrite this without using dunit.Host")
public void testStartUsingForceOverwritesExistingPidFile() throws Throwable {}
/*
* assertTrue(getUniqueName() + " is broken if PID == Integer.MAX_VALUE",
* ProcessUtils.identifyPid() != Integer.MAX_VALUE);
*
* // create existing pid file this.pidFile = new File(ProcessType.LOCATOR.getPidFileName());
* final int realPid = Host.getHost(0).getVM(3).invoke(() -> ProcessUtils.identifyPid());
* assertFalse(realPid == ProcessUtils.identifyPid()); writePid(this.pidFile, realPid);
*
* // build and start the locator final Builder builder = new Builder() .setForce(true)
* .setMemberName(getUniqueName()) .setPort(this.locatorPort) .setRedirectOutput(true)
*
* assertTrue(builder.getForce()); this.launcher = builder.build();
* assertTrue(this.launcher.isForcing()); this.launcher.start();
*
* // collect and throw the FIRST failure Throwable failure = null;
*
* try { waitForLocatorToStart(this.launcher);
*
* // validate the pid file and its contents assertTrue(this.pidFile.exists()); final int pid =
* readPid(this.pidFile); assertTrue(pid > 0); assertTrue(ProcessUtils.isProcessAlive(pid));
* assertIndexDetailsEquals(getPid(), pid);
*
* // validate log file was created final String logFileName = getUniqueName()+".log";
* assertTrue("Log file should exist: " + logFileName, new File(logFileName).exists());
*
* } catch (Throwable e) { logger.error(e); if (failure == null) { failure = e; } }
*
* try { assertIndexDetailsEquals(Status.STOPPED, this.launcher.stop().getStatus());
* waitForFileToDelete(this.pidFile); } catch (Throwable e) { logger.error(e); if (failure ==
* null) { failure = e; } }
*
* if (failure != null) { throw failure; } } // testStartUsingForceOverwritesExistingPidFile
*/
@Test
public void testStartWithDefaultPortInUseFails() throws Throwable {
// Test makes no sense in this case
if (this.locatorPort == 0) {
return;
}
this.socket =
SocketCreatorFactory.getSocketCreatorForComponent(SecurableCommunicationChannel.CLUSTER)
.createServerSocket(this.locatorPort, 50, null, -1);
assertTrue(this.socket.isBound());
assertFalse(this.socket.isClosed());
assertFalse(AvailablePort.isPortAvailable(this.locatorPort, AvailablePort.SOCKET));
assertNotNull(System.getProperty(DistributionLocator.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY));
assertEquals(this.locatorPort,
Integer.valueOf(System.getProperty(DistributionLocator.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY))
.intValue());
assertFalse(AvailablePort.isPortAvailable(this.locatorPort, AvailablePort.SOCKET));
this.launcher = new Builder().setMemberName(getUniqueName()).setRedirectOutput(true)
.setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config")
.build();
assertEquals(this.locatorPort, this.launcher.getPort().intValue());
RuntimeException expected = null;
try {
this.launcher.start();
// why did it not fail like it's supposed to?
final String property =
System.getProperty(DistributionLocator.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY);
assertNotNull(property);
assertEquals(this.locatorPort, Integer.valueOf(property).intValue());
assertFalse(AvailablePort.isPortAvailable(this.locatorPort, AvailablePort.SOCKET));
assertEquals(this.locatorPort, this.launcher.getPort().intValue());
assertEquals(this.locatorPort, this.socket.getLocalPort());
assertTrue(this.socket.isBound());
assertFalse(this.socket.isClosed());
fail("LocatorLauncher start should have thrown RuntimeException caused by BindException");
} catch (RuntimeException e) {
expected = e;
assertNotNull(expected.getMessage());
// BindException text varies by platform
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertNotNull(expected);
final Throwable cause = expected.getCause();
assertNotNull(cause);
assertTrue(cause instanceof BindException);
// BindException string varies by platform
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertFalse("Pid file should not exist: " + this.pidFile, this.pidFile.exists());
// creation of log file seems to be random -- look into why sometime
final String logFileName = getUniqueName() + ".log";
assertFalse("Log file should not exist: " + logFileName,
new File(this.temporaryFolder.getRoot(), logFileName).exists());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
// just in case the launcher started...
LocatorState status = null;
try {
status = this.launcher.stop();
} catch (Throwable t) {
// ignore
}
try {
waitForFileToDelete(this.pidFile);
assertEquals(getExpectedStopStatusForNotRunning(), status.getStatus());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
@Ignore("Need to rewrite this without using dunit.Host")
public void testStartWithExistingPidFileFails()
throws Throwable {}/*
* // create existing pid file final int realPid =
* Host.getHost(0).getVM(3).invoke(() -> ProcessUtils.identifyPid());
* assertFalse("Remote pid shouldn't be the same as local pid " + realPid,
* realPid == ProcessUtils.identifyPid());
*
* this.pidFile = new File(ProcessType.LOCATOR.getPidFileName());
* writePid(this.pidFile, realPid);
*
* // build and start the locator final Builder builder = new Builder()
* .setMemberName(getUniqueName()) .setPort(this.locatorPort)
* .setRedirectOutput(true) .set(logLevel, "config");
*
* assertFalse(builder.getForce()); this.launcher = builder.build();
* assertFalse(this.launcher.isForcing());
*
* // collect and throw the FIRST failure Throwable failure = null;
* RuntimeException expected = null;
*
* try { this.launcher.start();
* fail("LocatorLauncher start should have thrown RuntimeException caused by FileAlreadyExistsException"
* ); } catch (RuntimeException e) { expected = e;
* assertNotNull(expected.getMessage()); assertTrue(expected.getMessage(),
* expected.getMessage().
* contains("A PID file already exists and a Locator may be running in"));
* assertIndexDetailsEquals(RuntimeException.class, expected.getClass()); }
* catch (Throwable e) { logger.error(e); if (failure == null) { failure =
* e; } }
*
* // just in case the launcher started... LocatorState status = null; try
* { status = this.launcher.stop(); } catch (Throwable t) { // ignore }
*
* try { assertNotNull(expected); final Throwable cause =
* expected.getCause(); assertNotNull(cause); assertTrue(cause instanceof
* FileAlreadyExistsException);
* assertTrue(cause.getMessage().contains("Pid file already exists: "));
* assertTrue(cause.getMessage().contains("vf.gf.locator.pid for process "
* + realPid)); } catch (Throwable e) { logger.error(e); if (failure ==
* null) { failure = e; } }
*
* try { delete(this.pidFile); final Status theStatus = status.getStatus();
* assertFalse(theStatus == Status.STARTING); assertFalse(theStatus ==
* Status.ONLINE); } catch (Throwable e) { logger.error(e); if (failure ==
* null) { failure = e; } }
*
* if (failure != null) { throw failure; } } //
* testStartWithExistingPidFileFails
*/
@Test
public void testStartUsingPort() throws Throwable {
// generate one free port and then use it instead of default
final int freeTCPPort = AvailablePortHelper.getRandomAvailableTCPPort();
assertTrue(AvailablePort.isPortAvailable(freeTCPPort, AvailablePort.SOCKET));
this.launcher = new Builder().setMemberName(getUniqueName()).setPort(freeTCPPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config")
.build();
int pid = 0;
try {
// if start succeeds without throwing exception then #47778 is fixed
this.launcher.start();
waitForLocatorToStart(this.launcher);
// validate the pid file and its contents
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue(pidFile.exists());
pid = readPid(pidFile);
assertTrue(pid > 0);
assertTrue(ProcessUtils.isProcessAlive(pid));
assertEquals(getPid(), pid);
// verify locator did not use default port
assertTrue(AvailablePort.isPortAvailable(this.locatorPort, AvailablePort.SOCKET));
final LocatorState status = this.launcher.status();
final String portString = status.getPort();
assertEquals("Port should be \"" + freeTCPPort + "\" instead of " + portString,
String.valueOf(freeTCPPort), portString);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
// stop the locator
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testStartUsingPortInUseFails() throws Throwable {
// Test makes no sense in this case
if (this.locatorPort == 0) {
return;
}
// generate one free port and then use it instead of default
this.socket =
SocketCreatorFactory.getSocketCreatorForComponent(SecurableCommunicationChannel.CLUSTER)
.createServerSocket(this.locatorPort, 50, null, -1);
this.launcher = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config")
.build();
RuntimeException expected = null;
try {
this.launcher.start();
fail("LocatorLauncher start should have thrown RuntimeException caused by BindException");
} catch (RuntimeException e) {
expected = e;
assertNotNull(expected.getMessage());
// BindException string varies by platform
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
assertNotNull(expected);
final Throwable cause = expected.getCause();
assertNotNull(cause);
assertTrue(cause instanceof BindException);
// BindException string varies by platform
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertFalse("Pid file should not exist: " + this.pidFile, this.pidFile.exists());
// creation of log file seems to be random -- look into why sometime
final String logFileName = getUniqueName() + ".log";
assertFalse("Log file should not exist: " + logFileName,
new File(this.temporaryFolder.getRoot(), logFileName).exists());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
// just in case the launcher started...
LocatorState status = null;
try {
status = this.launcher.stop();
} catch (Throwable t) {
// ignore
}
try {
waitForFileToDelete(this.pidFile);
assertEquals(getExpectedStopStatusForNotRunning(), status.getStatus());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testStatusUsingPid() throws Throwable {
// build and start the locator
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
LocatorLauncher pidLauncher = null;
try {
this.launcher.start();
waitForLocatorToStart(this.launcher);
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue("Pid file " + this.pidFile.getCanonicalPath().toString() + " should exist",
this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertEquals(ProcessUtils.identifyPid(), pid);
pidLauncher = new Builder().setPid(pid).build();
assertNotNull(pidLauncher);
assertFalse(pidLauncher.isRunning());
final LocatorState actualStatus = pidLauncher.status();
assertNotNull(actualStatus);
assertEquals(Status.ONLINE, actualStatus.getStatus());
assertEquals(pid, actualStatus.getPid().intValue());
assertTrue(actualStatus.getUptime() > 0);
// getWorkingDirectory returns user.dir instead of rootFolder because test is starting Locator
// in this process (to move logFile and pidFile into temp dir)
assertEquals(ManagementFactory.getRuntimeMXBean().getClassPath(),
actualStatus.getClasspath());
assertEquals(GemFireVersion.getGemFireVersion(), actualStatus.getGemFireVersion());
assertEquals(System.getProperty("java.version"), actualStatus.getJavaVersion());
assertEquals(this.workingDirectory + File.separator + getUniqueName() + ".log",
actualStatus.getLogFile());
assertEquals(InetAddress.getLocalHost().getCanonicalHostName(), actualStatus.getHost());
assertEquals(getUniqueName(), actualStatus.getMemberName());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
if (pidLauncher == null) {
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
} else {
try {
assertEquals(Status.STOPPED, pidLauncher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
}
@Test
public void testStatusUsingWorkingDirectory() throws Throwable {
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
LocatorLauncher dirLauncher = null;
try {
this.launcher.start();
waitForLocatorToStart(this.launcher);
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue("Pid file " + this.pidFile.getCanonicalPath().toString() + " should exist",
this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertEquals(ProcessUtils.identifyPid(), pid);
dirLauncher = new Builder().setWorkingDirectory(this.workingDirectory).build();
assertNotNull(dirLauncher);
assertFalse(dirLauncher.isRunning());
final LocatorState actualStatus = dirLauncher.status();
assertNotNull(actualStatus);
assertEquals(Status.ONLINE, actualStatus.getStatus());
assertEquals(pid, actualStatus.getPid().intValue());
assertTrue(actualStatus.getUptime() > 0);
// getWorkingDirectory returns user.dir instead of rootFolder because test is starting Locator
// in this process (to move logFile and pidFile into temp dir)
assertEquals(ManagementFactory.getRuntimeMXBean().getClassPath(),
actualStatus.getClasspath());
assertEquals(GemFireVersion.getGemFireVersion(), actualStatus.getGemFireVersion());
assertEquals(System.getProperty("java.version"), actualStatus.getJavaVersion());
assertEquals(this.workingDirectory + File.separator + getUniqueName() + ".log",
actualStatus.getLogFile());
assertEquals(InetAddress.getLocalHost().getCanonicalHostName(), actualStatus.getHost());
assertEquals(getUniqueName(), actualStatus.getMemberName());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
if (dirLauncher == null) {
try {
assertEquals(Status.STOPPED, this.launcher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
} else {
try {
assertEquals(Status.STOPPED, dirLauncher.stop().getStatus());
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
}
@Test
public void testStopUsingPid() throws Throwable {
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
LocatorLauncher pidLauncher = null;
try {
this.launcher.start();
waitForLocatorToStart(this.launcher);
// validate the pid file and its contents
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue(this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertEquals(ProcessUtils.identifyPid(), pid);
pidLauncher = new Builder().setPid(pid).build();
assertNotNull(pidLauncher);
assertFalse(pidLauncher.isRunning());
// stop the locator
final LocatorState locatorState = pidLauncher.stop();
assertNotNull(locatorState);
assertEquals(Status.STOPPED, locatorState.getStatus());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
this.launcher.stop();
} catch (Throwable e) {
// ignore
}
try {
// verify the PID file was deleted
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
@Test
public void testStopUsingWorkingDirectory() throws Throwable {
final Builder builder = new Builder().setMemberName(getUniqueName()).setPort(this.locatorPort)
.setRedirectOutput(true).setWorkingDirectory(this.workingDirectory)
.set(CLUSTER_CONFIGURATION_DIR, this.clusterConfigDirectory).set(LOG_LEVEL, "config");
assertFalse(builder.getForce());
this.launcher = builder.build();
assertFalse(this.launcher.isForcing());
LocatorLauncher dirLauncher = null;
try {
this.launcher.start();
waitForLocatorToStart(this.launcher);
// validate the pid file and its contents
this.pidFile = new File(this.temporaryFolder.getRoot(), ProcessType.LOCATOR.getPidFileName());
assertTrue("Pid file " + this.pidFile.getCanonicalPath().toString() + " should exist",
this.pidFile.exists());
final int pid = readPid(this.pidFile);
assertTrue(pid > 0);
assertEquals(ProcessUtils.identifyPid(), pid);
dirLauncher = new Builder().setWorkingDirectory(this.workingDirectory).build();
assertNotNull(dirLauncher);
assertFalse(dirLauncher.isRunning());
// stop the locator
final LocatorState locatorState = dirLauncher.stop();
assertNotNull(locatorState);
assertEquals(Status.STOPPED, locatorState.getStatus());
} catch (Throwable e) {
this.errorCollector.addError(e);
}
try {
this.launcher.stop();
} catch (Throwable e) {
// ignore
}
try {
// verify the PID file was deleted
waitForFileToDelete(this.pidFile);
} catch (Throwable e) {
this.errorCollector.addError(e);
}
}
}
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package uk.ac.lancs.comp.vmlstar.model.vmlstar.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import uk.ac.lancs.comp.vmlstar.model.vmlstar.*;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class VmlstarFactoryImpl extends EFactoryImpl implements VmlstarFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static VmlstarFactory init() {
try
{
VmlstarFactory theVmlstarFactory = (VmlstarFactory)EPackage.Registry.INSTANCE.getEFactory("http://uk.ac.lancs.comp/vmlstar");
if (theVmlstarFactory != null)
{
return theVmlstarFactory;
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
}
return new VmlstarFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VmlstarFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID())
{
case VmlstarPackage.VML_MODEL: return createVmlModel();
case VmlstarPackage.FEATURE_MODEL_REF: return createFeatureModelRef();
case VmlstarPackage.FEATURE: return createFeature();
case VmlstarPackage.CORE_MODEL_REF: return createCoreModelRef();
case VmlstarPackage.CONCERN: return createConcern();
case VmlstarPackage.VARIANT: return createVariant();
case VmlstarPackage.POINT_CUT_REFERENCE: return createPointCutReference();
case VmlstarPackage.POINT_CUT: return createPointCut();
case VmlstarPackage.PCE_AND_OPERATOR: return createPCEAndOperator();
case VmlstarPackage.PCE_OR_OPERATOR: return createPCEOrOperator();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VmlModel createVmlModel() {
VmlModelImpl vmlModel = new VmlModelImpl();
return vmlModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureModelRef createFeatureModelRef() {
FeatureModelRefImpl featureModelRef = new FeatureModelRefImpl();
return featureModelRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Feature createFeature() {
FeatureImpl feature = new FeatureImpl();
return feature;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CoreModelRef createCoreModelRef() {
CoreModelRefImpl coreModelRef = new CoreModelRefImpl();
return coreModelRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Concern createConcern() {
ConcernImpl concern = new ConcernImpl();
return concern;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Variant createVariant() {
VariantImpl variant = new VariantImpl();
return variant;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PointCutReference createPointCutReference() {
PointCutReferenceImpl pointCutReference = new PointCutReferenceImpl();
return pointCutReference;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PointCut createPointCut() {
PointCutImpl pointCut = new PointCutImpl();
return pointCut;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PCEAndOperator createPCEAndOperator() {
PCEAndOperatorImpl pceAndOperator = new PCEAndOperatorImpl();
return pceAndOperator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PCEOrOperator createPCEOrOperator() {
PCEOrOperatorImpl pceOrOperator = new PCEOrOperatorImpl();
return pceOrOperator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VmlstarPackage getVmlstarPackage() {
return (VmlstarPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static VmlstarPackage getPackage() {
return VmlstarPackage.eINSTANCE;
}
} //VmlstarFactoryImpl
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.performancestatistics;
import java.io.File;
import java.util.Collections;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.query.ScanQuery;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.transactions.Transaction;
import org.junit.Test;
import static org.apache.ignite.internal.processors.performancestatistics.AbstractPerformanceStatisticsTest.waitForStatisticsEnabled;
import static org.apache.ignite.internal.processors.performancestatistics.FilePerformanceStatisticsWriter.PERF_STAT_DIR;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests the performance statistics report.
*/
public class PerformanceStatisticsReportSelfTest {
/** @throws Exception If failed. */
@Test
public void testCreateReport() throws Exception {
try (
Ignite srv = Ignition.start(new IgniteConfiguration().setIgniteInstanceName("srv"));
IgniteEx client = (IgniteEx)Ignition.start(new IgniteConfiguration()
.setIgniteInstanceName("client")
.setClientMode(true))
) {
client.context().performanceStatistics().startCollectStatistics();
IgniteCache<Object, Object> cache = client.createCache("cache");
cache.put(1, 1);
cache.get(1);
cache.remove(1);
cache.putAll(Collections.singletonMap(2, 2));
cache.getAll(Collections.singleton(2));
cache.removeAll(Collections.singleton(2));
cache.getAndPut(3, 3);
cache.getAndRemove(3);
client.compute().run(() -> {
// No-op.
});
IgniteCache<Object, Object> txCache = client.createCache(new CacheConfiguration<>("txCache")
.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL));
try (Transaction tx = client.transactions().txStart()) {
txCache.put(1, 1);
tx.commit();
}
try (Transaction tx = client.transactions().txStart()) {
txCache.put(2, 2);
tx.rollback();
}
cache.query(new ScanQuery<>((key, val) -> true)).getAll();
cache.query(new SqlFieldsQuery("select * from sys.tables")).getAll();
client.context().performanceStatistics().stopCollectStatistics();
waitForStatisticsEnabled(false);
File prfDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), PERF_STAT_DIR, false);
assertTrue(prfDir.exists());
PerformanceStatisticsReportBuilder.main(prfDir.getAbsolutePath());
File[] reportDir = prfDir.listFiles((dir, name) -> name.startsWith("report"));
assertEquals(1, reportDir.length);
File report = reportDir[0];
File index = new File(report.getAbsolutePath() + File.separatorChar + "index.html");
File dataDir = new File(report.getAbsolutePath() + File.separatorChar + "data");
File dataJs = new File(dataDir.getAbsolutePath() + File.separatorChar + "data.json.js");
assertTrue(index.exists());
assertTrue(dataDir.exists());
assertTrue(dataJs.exists());
} finally {
U.delete(new File(U.defaultWorkDirectory()));
}
}
}
|
package org.apache.asterix.experiment.builder.suite;
import org.apache.asterix.experiment.builder.AbstractLSMBaseExperimentBuilder;
import org.apache.asterix.experiment.builder.cluster.ICluster1Builder;
import org.apache.asterix.experiment.builder.config.IUniformHistConfigBuilder;
import org.apache.asterix.experiment.builder.counter.IRecordsCounterBuilder;
import org.apache.asterix.experiment.builder.dgen.IDgen2Builder;
import org.apache.asterix.experiment.builder.experiment.IExperiment2ABuilder;
import org.apache.asterix.experiment.builder.ingest.IIngest2Builder;
import org.apache.asterix.experiment.client.LSMExperimentSetRunner.LSMExperimentSetRunnerConfig;
public class StatisticsExperiment2AUniformHistBuilder extends AbstractLSMBaseExperimentBuilder
implements IExperiment2ABuilder, IDgen2Builder, ICluster1Builder, IIngest2Builder, IRecordsCounterBuilder,
IUniformHistConfigBuilder {
public StatisticsExperiment2AUniformHistBuilder(LSMExperimentSetRunnerConfig config) {
super(config);
}
}
|
package com.spider.upms.dao.model;
import java.io.Serializable;
public class UpmsLog implements Serializable {
/**
* 编号
*
* @mbg.generated
*/
private Integer logId;
/**
* 操作描述
*
* @mbg.generated
*/
private String description;
/**
* 操作用户
*
* @mbg.generated
*/
private String username;
/**
* 操作时间
*
* @mbg.generated
*/
private Long startTime;
/**
* 消耗时间
*
* @mbg.generated
*/
private Integer spendTime;
/**
* 根路径
*
* @mbg.generated
*/
private String basePath;
/**
* URI
*
* @mbg.generated
*/
private String uri;
/**
* URL
*
* @mbg.generated
*/
private String url;
/**
* 请求类型
*
* @mbg.generated
*/
private String method;
/**
* 用户标识
*
* @mbg.generated
*/
private String userAgent;
/**
* IP地址
*
* @mbg.generated
*/
private String ip;
/**
* 权限值
*
* @mbg.generated
*/
private String permissions;
private String parameter;
private String result;
private static final long serialVersionUID = 1L;
public Integer getLogId() {
return logId;
}
public void setLogId(Integer logId) {
this.logId = logId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Integer getSpendTime() {
return spendTime;
}
public void setSpendTime(Integer spendTime) {
this.spendTime = spendTime;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", logId=").append(logId);
sb.append(", description=").append(description);
sb.append(", username=").append(username);
sb.append(", startTime=").append(startTime);
sb.append(", spendTime=").append(spendTime);
sb.append(", basePath=").append(basePath);
sb.append(", uri=").append(uri);
sb.append(", url=").append(url);
sb.append(", method=").append(method);
sb.append(", userAgent=").append(userAgent);
sb.append(", ip=").append(ip);
sb.append(", permissions=").append(permissions);
sb.append(", parameter=").append(parameter);
sb.append(", result=").append(result);
sb.append("]");
return sb.toString();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
UpmsLog other = (UpmsLog) that;
return (this.getLogId() == null ? other.getLogId() == null : this.getLogId().equals(other.getLogId()))
&& (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription()))
&& (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
&& (this.getStartTime() == null ? other.getStartTime() == null : this.getStartTime().equals(other.getStartTime()))
&& (this.getSpendTime() == null ? other.getSpendTime() == null : this.getSpendTime().equals(other.getSpendTime()))
&& (this.getBasePath() == null ? other.getBasePath() == null : this.getBasePath().equals(other.getBasePath()))
&& (this.getUri() == null ? other.getUri() == null : this.getUri().equals(other.getUri()))
&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))
&& (this.getMethod() == null ? other.getMethod() == null : this.getMethod().equals(other.getMethod()))
&& (this.getUserAgent() == null ? other.getUserAgent() == null : this.getUserAgent().equals(other.getUserAgent()))
&& (this.getIp() == null ? other.getIp() == null : this.getIp().equals(other.getIp()))
&& (this.getPermissions() == null ? other.getPermissions() == null : this.getPermissions().equals(other.getPermissions()))
&& (this.getParameter() == null ? other.getParameter() == null : this.getParameter().equals(other.getParameter()))
&& (this.getResult() == null ? other.getResult() == null : this.getResult().equals(other.getResult()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getLogId() == null) ? 0 : getLogId().hashCode());
result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode());
result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
result = prime * result + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
result = prime * result + ((getSpendTime() == null) ? 0 : getSpendTime().hashCode());
result = prime * result + ((getBasePath() == null) ? 0 : getBasePath().hashCode());
result = prime * result + ((getUri() == null) ? 0 : getUri().hashCode());
result = prime * result + ((getUrl() == null) ? 0 : getUrl().hashCode());
result = prime * result + ((getMethod() == null) ? 0 : getMethod().hashCode());
result = prime * result + ((getUserAgent() == null) ? 0 : getUserAgent().hashCode());
result = prime * result + ((getIp() == null) ? 0 : getIp().hashCode());
result = prime * result + ((getPermissions() == null) ? 0 : getPermissions().hashCode());
result = prime * result + ((getParameter() == null) ? 0 : getParameter().hashCode());
result = prime * result + ((getResult() == null) ? 0 : getResult().hashCode());
return result;
}
}
|
package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.exceptions.ScriptParseException;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Clan.Authority;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary.CompiledZMask;
import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary.CompiledZMaskEntry;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2022 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class MUDZapper extends StdLibrary implements MaskingLibrary
{
@Override
public String ID()
{
return "MUDZapper";
}
public Map<String,ZapperKey> zapCodes=new Hashtable<String,ZapperKey>();
private static class SavedRace
{
public final String name;
public final String upperName;
public final String racialCategory;
public final String upperCatName;
public final String nameStart;
public final String minusNameStart;
public final String catNameStart;
public final String minusCatNameStart;
public SavedRace(final Race race, final int startChars)
{
name=race.name();
upperName=name.toUpperCase();
nameStart=CMStrings.safeLeft(name.toUpperCase(),startChars);
minusNameStart="-"+nameStart;
racialCategory=race.racialCategory();
upperCatName=racialCategory.toUpperCase();
catNameStart=CMStrings.safeLeft(racialCategory.toUpperCase(),startChars);
minusCatNameStart="-"+catNameStart;
}
}
private static class SavedClass
{
public final String id;
public final String name;
public final String upperName;
public final String baseClass;
public final String nameStart;
public final String plusNameStart;
public final String minusNameStart;
public final String baseClassStart;
public final String plusBaseClassStart;
public SavedClass(final CharClass charClass, final int startChars)
{
name=charClass.name();
id=charClass.ID();
upperName=name.toUpperCase();
nameStart=CMStrings.safeLeft(name.toUpperCase(),startChars);
plusNameStart="+"+nameStart;
minusNameStart="-"+nameStart;
baseClass=charClass.baseClass();
baseClassStart=CMStrings.safeLeft(baseClass.toUpperCase(),startChars);
plusBaseClassStart="+"+baseClassStart;
}
}
public static class CompiledZapperMaskEntryImpl implements CompiledZMaskEntry
{
private final ZapperKey maskType;
private final Object[] parms;
@Override
public ZapperKey maskType()
{
return maskType;
}
@Override
public Object[] parms()
{
return parms;
}
public CompiledZapperMaskEntryImpl(final ZapperKey type, final Object[] parms)
{
maskType = type;
this.parms = parms;
}
}
private enum LocationType
{
OWNED,
CLANOWNED,
PRIV,
ROOMID,
ROOMSTR
}
public static class CompiledZapperMaskImpl implements CompiledZMask
{
private final boolean[] flags;
private final boolean empty;
private final CompiledZMaskEntry[][] entries;
@Override
public boolean[] flags()
{
return flags;
}
@Override
public boolean empty()
{
return empty;
}
@Override
public CompiledZMaskEntry[][] entries()
{
return entries;
}
public CompiledZapperMaskImpl(final boolean[] flags, final CompiledZMaskEntry[][] entries)
{
this.flags = flags;
this.entries = entries;
this.empty = false;
}
public CompiledZapperMaskImpl(final boolean[] flags, final CompiledZMaskEntry[][] entries, final boolean empty)
{
this.flags = flags;
this.entries = entries;
this.empty = empty;
}
}
protected MOB nonCrashingMOB=null;
protected MOB nonCrashingMOB()
{
if(nonCrashingMOB!=null)
return nonCrashingMOB;
nonCrashingMOB=CMClass.getMOB("StdMOB");
return nonCrashingMOB;
}
protected Item nonCrashingItem=null;
protected Item nonCrashingItem(final MOB mob)
{
if(mob.numItems()>0)
{
final Item I = mob.getItem(0);
if(I!=null)
return I;
}
if(nonCrashingItem!=null)
return nonCrashingItem;
nonCrashingItem=CMClass.getItem("StdItem");
return nonCrashingItem;
}
@Override
public String rawMaskHelp()
{
String maskHelp = (String)Resources.getResource("SYSTEM_ZAPPERMASK_HELP");
if(maskHelp == null)
{
final CMFile F = new CMFile(Resources.makeFileResourceName("help/zappermasks.txt"),null,CMFile.FLAG_LOGERRORS);
if((F.exists()) && (F.canRead()))
{
final List<String> lines=Resources.getFileLineVector(F.text());
final StringBuilder str = new StringBuilder("");
for(final String line : lines)
{
str.append(line.trim()).append("<BR>");
}
maskHelp = str.toString();
}
else
maskHelp = "ZAPPERMASK HELP NOT FOUND at /resources/help/zappermasks.txt!";
Resources.submitResource("SYSTEM_ZAPPERMASK_HELP",maskHelp);
}
return maskHelp;
}
protected volatile List<SavedClass> savedCharClasses = new Vector<SavedClass>(1);
protected volatile List<SavedRace> savedRaces = new Vector<SavedRace>(1);
protected volatile long savedClassUpdateTime = 0;
public synchronized void buildSavedClasses()
{
if(savedClassUpdateTime==CMClass.getLastClassUpdatedTime())
return;
final List<SavedClass> tempSavedCharClasses=new LinkedList<SavedClass>();
final List<SavedRace> tempSavedRaces=new LinkedList<SavedRace>();
for(final Enumeration<CharClass> c=CMClass.charClasses();c.hasMoreElements();)
{
final CharClass C=c.nextElement();
tempSavedCharClasses.add(new SavedClass(C,4));
}
for(final Enumeration<Race> r=CMClass.races();r.hasMoreElements();)
{
final Race R=r.nextElement();
tempSavedRaces.add(new SavedRace(R,6));
}
savedCharClasses=tempSavedCharClasses;
savedRaces=tempSavedRaces;
savedClassUpdateTime=CMClass.getLastClassUpdatedTime();
}
public final List<SavedClass> charClasses()
{
if(savedClassUpdateTime!=CMClass.getLastClassUpdatedTime())
buildSavedClasses();
return savedCharClasses;
}
public final List<SavedRace> races()
{
if(savedClassUpdateTime!=CMClass.getLastClassUpdatedTime())
buildSavedClasses();
return savedRaces;
}
@Override
@SuppressWarnings("unchecked")
public CompiledZMask getPreCompiledMask(final String str)
{
Map<String,CompiledZMask> H=(Map<String,CompiledZMask>)Resources.getResource("SYSTEM_HASHED_MASKS");
if(H==null)
{
H=new PrioritizingLimitedMap<String,CompiledZMask>(200, 10*60*1000, Long.MAX_VALUE, 50);
Resources.submitResource("SYSTEM_HASHED_MASKS",H);
}
final String lowerStr=(str==null)?"":str.toLowerCase().trim();
CompiledZMask V=H.get(lowerStr);
if(V==null)
{
V=maskCompile(str);
H.put(lowerStr,V);
}
return V;
}
@Override
public CompiledZMask createEmptyMask()
{
return new CompiledZapperMaskImpl(new boolean[2], new CompiledZMaskEntry[0][0], true);
}
@Override
public Map<String,ZapperKey> getMaskCodes()
{
if(zapCodes.size()==0)
{
for(final ZapperKey Z : ZapperKey.values())
{
for(final String key : Z.keys())
zapCodes.put(key, Z);
}
}
return zapCodes;
}
@Override
public String maskHelp(final String CR, final String word)
{
String copy=rawMaskHelp();
if((CR!=null)&&(!CR.equalsIgnoreCase("<BR>")))
copy=CMStrings.replaceAll(copy,"<BR>",CR);
if((word==null)||(word.length()==0))
copy=CMStrings.replaceAll(copy,"<WORD>","disallow");
else
copy=CMStrings.replaceAll(copy,"<WORD>",word);
return copy;
}
protected Object makeSkillFlagObject(final String str)
{
Object o=null;
final int x=str.indexOf('&');
if(x>=0)
{
final Vector<Object> V=new Vector<Object>();
V.addAll(CMParms.parseAny(str,'&',true));
String s=null;
for(int v=0;v<V.size();v++)
{
s=(String)V.elementAt(v);
if(s.startsWith("!"))
{
V.setElementAt(s.substring(1),v);
V.insertElementAt(Boolean.FALSE,v);
v++;
}
}
final Object[] o2=new Object[V.size()];
for(int v=0;v<V.size();v++)
{
if(V.elementAt(v) instanceof String)
o2[v]=makeSkillFlagObject((String)V.elementAt(v));
else
o2[v]=V.elementAt(v);
}
for(int i=0;i<o2.length;i++)
{
if ((o2[i] != null) && (!(o2[i] instanceof Boolean)))
{
o = o2;
break;
}
}
}
if(o==null)
{
for(int d=0;d<Ability.ACODE_DESCS.length;d++)
{
if(Ability.ACODE_DESCS[d].equals(str))
{
o=Integer.valueOf(d);
break;
}
}
}
if(o==null)
{
for(int d=0;d<Ability.DOMAIN_DESCS.length;d++)
{
if(Ability.DOMAIN_DESCS[d].startsWith(str)||Ability.DOMAIN_DESCS[d].endsWith(str))
{
o=Integer.valueOf(d<<5);
break;
}
}
}
if(o==null)
{
for(int d=0;d<Ability.FLAG_DESCS.length;d++)
{
if(Ability.FLAG_DESCS[d].startsWith(str))
{
o=Long.valueOf(1L<<d);
break;
}
}
}
if(o==null)
{
for(short d=0;d<Ability.QUALITY_DESCS.length;d++)
{
if(Ability.QUALITY_DESCS[d].startsWith(str)||Ability.QUALITY_DESCS[d].endsWith(str))
{
o=new Short(d);
break;
}
}
}
return o;
}
protected boolean checkLocation(final Environmental E, final MOB M, final Room R, final Object o, final Object p)
{
if(!(o instanceof LocationType))
return false;
switch((LocationType)o)
{
case CLANOWNED:
{
if(E instanceof MOB)
{
for(final Pair<Clan,Integer> C : M.clans())
{
if(CMLib.law().doesOwnThisLand(C.first.getName(), R) || CMLib.law().doesOwnThisProperty(C.first.getName(), R))
return true;
}
}
else
{
final String str = CMLib.law().getLandOwnerName(R);
if((str.length()>0)&&(CMLib.clans().getClanAnyHost(str)!=null))
return true;
}
break;
}
case OWNED:
{
if(E instanceof MOB)
return CMLib.law().doesOwnThisLand(M, R) || CMLib.law().doesOwnThisProperty(M, R);
else
return CMLib.law().getLandOwnerName(R).length()>0;
}
case PRIV:
{
return CMLib.law().doesHavePriviledgesHere(M, R);
}
case ROOMID:
{
final String roomID=CMLib.map().getExtendedRoomID(R).toLowerCase();
if((p!=null)&&(roomID.startsWith(p.toString().toLowerCase())))
return true;
break;
}
case ROOMSTR:
{
if(p!=null)
{
final String subStr=p.toString();
if(CMLib.english().containsString(R.displayText(M), subStr))
return true;
if(CMLib.english().containsString(R.description(M), subStr))
return true;
}
break;
}
}
return false;
}
protected boolean evaluateSkillFlagObject(final Object o, final Ability A)
{
if(A!=null)
{
if(o instanceof Object[])
{
final Object[] set=(Object[])o;
for(int i=0;i<set.length;i++)
{
if(set[i] instanceof Boolean)
{
if(evaluateSkillFlagObject(set[i+1],A))
return false;
i++;
}
else
if(!evaluateSkillFlagObject(set[i],A))
return false;
}
return true;
}
else
if(o instanceof Integer)
{
final int val=((Integer)o).intValue();
if(((A.classificationCode()&Ability.ALL_ACODES)==val)
||((A.classificationCode()&Ability.ALL_DOMAINS)==val))
return true;
}
else
if(o instanceof Short)
{
final int val=((Short)o).intValue();
if(A.abstractQuality()==val)
return true;
}
else
if(o instanceof Long)
{
final long val=((Long)o).longValue();
if((A.flags()&val)==val)
return true;
}
}
return false;
}
protected boolean skillFlagCheck(final List<String> V, final char plusMinus, final int fromHere, final MOB mob)
{
for(int v=fromHere;v<V.size();v++)
{
final String str=V.get(v);
if(str.length()==0)
continue;
if(getMaskCodes().containsKey(str))
return false;
final Object o=makeSkillFlagObject(str);
if(o==null)
continue;
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(evaluateSkillFlagObject(o,A))
return true;
}
}
return false;
}
protected CompiledZMaskEntry levelCompiledHelper(final String str, final char c)
{
final ArrayList<Object> parms=new ArrayList<Object>();
ZapperKey entryType=null;
if(str.startsWith(c+">=")&&(CMath.isNumber(str.substring(3).trim())))
{
entryType=getMaskCodes().get("+LVLGE");
parms.add(Integer.valueOf(CMath.s_int(str.substring(3).trim())));
}
else
if(str.startsWith(c+"<=")&&(CMath.isNumber(str.substring(3).trim())))
{
entryType=getMaskCodes().get("+LVLLE");
parms.add(Integer.valueOf(CMath.s_int(str.substring(3).trim())));
}
else
if(str.startsWith(c+">")&&(CMath.isNumber(str.substring(2).trim())))
{
entryType=getMaskCodes().get("+LVLGR");
parms.add(Integer.valueOf(CMath.s_int(str.substring(2).trim())));
}
else
if(str.startsWith(c+"<")&&(CMath.isNumber(str.substring(2).trim())))
{
entryType=getMaskCodes().get("+LVLLT");
parms.add(Integer.valueOf(CMath.s_int(str.substring(2).trim())));
}
else
if(str.startsWith(c+"=")&&(CMath.isNumber(str.substring(2).trim())))
{
entryType=getMaskCodes().get("+LVLEQ");
parms.add(Integer.valueOf(CMath.s_int(str.substring(2).trim())));
}
if((entryType==null)||(parms.size()==0))
return null;
return new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0]));
}
protected StringBuilder levelHelp(final String lvl, final char c, final String append)
{
if(lvl.startsWith(c+">=")&&(CMath.isNumber(lvl.substring(3).trim())))
return new StringBuilder(append+"levels greater than or equal to "+lvl.substring(3).trim()+". ");
else
if(lvl.startsWith(c+"<=")&&(CMath.isNumber(lvl.substring(3).trim())))
return new StringBuilder(append+"levels less than or equal to "+lvl.substring(3).trim()+". ");
else
if(lvl.startsWith(c+">")&&(CMath.isNumber(lvl.substring(2).trim())))
return new StringBuilder(append+"levels greater than "+lvl.substring(2).trim()+". ");
else
if(lvl.startsWith(c+"<")&&(CMath.isNumber(lvl.substring(2).trim())))
return new StringBuilder(append+"levels less than "+lvl.substring(2).trim()+". ");
else
if(lvl.startsWith(c+"=")&&(CMath.isNumber(lvl.substring(2).trim())))
return new StringBuilder(append+"level "+lvl.substring(2).trim()+". ");
return new StringBuilder("");
}
protected int determineSeasonCode(String str)
{
str=str.toUpperCase().trim();
if(str.length()==0)
return -1;
final TimeClock.Season season=(TimeClock.Season)CMath.s_valueOf(TimeClock.Season.class, str);
if(season != null)
return season.ordinal();
for(int i=0;i<TimeClock.Season.values().length;i++)
{
if(TimeClock.Season.values()[i].toString().startsWith(str))
return i;
}
return -1;
}
protected int levelMinHelp(final String lvl, final char c, final int minMinLevel, final boolean reversed)
{
if(lvl.startsWith(c+">=")&&(CMath.isNumber(lvl.substring(3).trim())))
return reversed?minMinLevel:CMath.s_int(lvl.substring(3).trim());
else
if(lvl.startsWith(c+"<=")&&(CMath.isNumber(lvl.substring(3).trim())))
return reversed?CMath.s_int(lvl.substring(3).trim())+1:minMinLevel;
else
if(lvl.startsWith(c+">")&&(CMath.isNumber(lvl.substring(2).trim())))
return reversed?minMinLevel:CMath.s_int(lvl.substring(2).trim())+1;
else
if(lvl.startsWith(c+"<")&&(CMath.isNumber(lvl.substring(2).trim())))
return reversed?CMath.s_int(lvl.substring(2).trim()):minMinLevel;
else
if(lvl.startsWith(c+"=")&&(CMath.isNumber(lvl.substring(2).trim())))
return reversed?minMinLevel:CMath.s_int(lvl.substring(2).trim());
return Integer.MIN_VALUE;
}
protected boolean fromHereEqual(final List<String> V, final char plusMinus, final int fromHere, final String find)
{
for(int v=fromHere;v<V.size();v++)
{
final String str=V.get(v);
if(str.length()==0)
continue;
if(getMaskCodes().containsKey(str))
return false;
if(str.equalsIgnoreCase(plusMinus+find))
return true;
}
return false;
}
protected boolean fromHereStartsWith(final List<String> V, final char plusMinus, final int fromHere, final String find)
{
for(int v=fromHere;v<V.size();v++)
{
final String str=V.get(v);
if(str.length()==0)
continue;
if(getMaskCodes().containsKey(str))
return false;
if(str.startsWith(plusMinus+find))
return true;
}
return false;
}
protected Faction.FRange getRange(final String s)
{
return CMLib.factions().getFactionRangeByCodeName(s);
}
protected boolean fromHereEndsWith(final List<String> V, final char plusMinus, final int fromHere, final String find)
{
for(int v=fromHere;v<V.size();v++)
{
final String str=V.get(v);
if(str.length()==0)
continue;
if(getMaskCodes().containsKey(str))
return false;
if((str.charAt(0)==plusMinus)&&str.endsWith(find))
return true;
}
return false;
}
@Override
public String maskDesc(final String text)
{
return maskDesc(text, false);
}
public int countQuals(final List<String> V, final int v, final String startsWith)
{
int ct=0;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith(startsWith))
ct++;
}
return ct;
}
protected boolean multipleQuals(final List<String> V, final int v, final String startsWith)
{
return countQuals(V,v,startsWith)>1;
}
protected int appendCommaList(final StringBuilder buf, final List<String> V, final int v, final String startChar)
{
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
return v2-1;
if(str2.startsWith(startChar))
buf.append(str2.substring(1).trim()+", ");
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
return v;
}
protected int appendCommaList(final StringBuilder buf, final List<String> V, final int v)
{
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
return v2-1;
if(str2.startsWith("+")||str2.startsWith("-"))
buf.append(CMath.s_int(str2.substring(1).trim())+", ");
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
return v;
}
@Override
public String maskDesc(final String text, final boolean skipFirstWord)
{
if(text.trim().length()==0)
return L("Anyone");
final StringBuilder buf=new StringBuilder("");
final Map<String,ZapperKey> zapCodes=getMaskCodes();
final List<String> V=CMParms.parse(text.toUpperCase());
int val=-1;
for(int v=0;v<V.size();v++)
{
final String str=V.get(v);
val=-1;
if(zapCodes.containsKey(str))
{
final ZapperKey key = zapCodes.get(str);
switch(key)
{
case CLASS: // +class
{
buf.append(L("Disallows the following class"+(multipleQuals(V,v,"-")?"es":"")+": "));
for(final SavedClass C : charClasses())
{
final String cstr=C.minusNameStart;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(str2.length()==0)
continue;
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith(cstr))
buf.append(C.name+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _CLASS: // -class
{
buf.append(L(skipFirstWord?"Only ":"Allows only "));
for(final SavedClass C : charClasses())
{
final String cstr=C.plusNameStart;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(str2.length()==0)
continue;
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith(cstr))
buf.append(C.name+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case BASECLASS: // +baseclass
{
buf.append(L("Disallows the following types"+(multipleQuals(V,v,"-")?"s":"")+": "));
final HashSet<String> seenBase=new HashSet<String>();
for(final SavedClass C : charClasses())
{
if(!seenBase.contains(C.baseClass))
{
seenBase.add(C.baseClass);
if(fromHereStartsWith(V,'-',v+1,C.baseClassStart))
buf.append(C.baseClass+" types, ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _BASECLASS: // -baseclass
{
buf.append(L(skipFirstWord?"Only ":"Allows only "));
final HashSet<String> seenBase=new HashSet<String>();
for(final SavedClass C : charClasses())
{
final String cstr=C.plusBaseClassStart;
if(!seenBase.contains(C.baseClass))
{
seenBase.add(C.baseClass);
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(str2.length()==0)
continue;
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith(cstr))
buf.append(L("@x1 types, ",C.baseClass));
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _RACE: // -Race
{
buf.append(L(skipFirstWord?"Only ":"Allows only "));
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((!cats.contains(R.name)
&&(fromHereStartsWith(V,'+',v+1,R.nameStart))))
cats.add(R.name);
}
for(final String s : cats)
buf.append(s+", ");
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _RACECAT: // -Racecats
{
buf.append(L(skipFirstWord?"Only these racial categor"+(multipleQuals(V,v,"+")?"ies":"y")+" ":"Allows only these racial categor"+(multipleQuals(V,v,"+")?"ies":"y")+" "));
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((!cats.contains(R.racialCategory)
&&(fromHereStartsWith(V,'+',v+1,R.upperCatName))))
cats.add(R.racialCategory);
}
for(final String s : cats)
buf.append(s+", ");
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case ALIGNMENT: // Alignment
{
buf.append(L("Disallows the following alignment"+(multipleQuals(V,v,"-")?"s":"")+": "));
if(fromHereStartsWith(V,'-',v+1,Faction.Align.EVIL.toString().substring(0,3)))
buf.append(L(Faction.Align.EVIL.toString().toLowerCase()+", "));
if(fromHereStartsWith(V,'-',v+1,Faction.Align.GOOD.toString().substring(0,3)))
buf.append(L(Faction.Align.GOOD.toString().toLowerCase()+", "));
if(fromHereStartsWith(V,'-',v+1,Faction.Align.NEUTRAL.toString().substring(0,3)))
buf.append(L(Faction.Align.NEUTRAL.toString().toLowerCase()+", "));
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _ALIGNMENT: // -Alignment
{
buf.append(L(skipFirstWord?"Only ":"Allows only "));
if(fromHereStartsWith(V,'+',v+1,Faction.Align.EVIL.toString().substring(0,3)))
buf.append(L(Faction.Align.EVIL.toString().toLowerCase()+", "));
if(fromHereStartsWith(V,'+',v+1,Faction.Align.GOOD.toString().substring(0,3)))
buf.append(L(Faction.Align.GOOD.toString().toLowerCase()+", "));
if(fromHereStartsWith(V,'+',v+1,Faction.Align.NEUTRAL.toString().substring(0,3)))
buf.append(L(Faction.Align.NEUTRAL.toString().toLowerCase()+", "));
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case GENDER:
{
buf.append(L("Disallows the following gender"+(multipleQuals(V,v,"-")?"s":"")+": "));
if(fromHereStartsWith(V,'-',v+1,"MALE"))
buf.append(L("Male, "));
if(fromHereStartsWith(V,'-',v+1,"FEMALE"))
buf.append(L("Female, "));
if(fromHereStartsWith(V,'-',v+1,"NEUTER"))
buf.append(L("Neuter"));
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _GENDER: // -Gender
{
buf.append(L(skipFirstWord?"Only ":"Allows only "));
if(fromHereStartsWith(V,'+',v+1,"MALE"))
buf.append(L("Male, "));
if(fromHereStartsWith(V,'+',v+1,"FEMALE"))
buf.append(L("Female, "));
if(fromHereStartsWith(V,'+',v+1,"NEUTER"))
buf.append(L("Neuter"));
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _LEVEL: // -Levels
{
for(int v2=v+1;v2<V.size();v2++)
buf.append(levelHelp(V.get(v2),'+',L(skipFirstWord?"Only ":"Allows only ")));
}
break;
case _CLASSLEVEL: // -ClassLevels
{
for(int v2=v+1;v2<V.size();v2++)
buf.append(levelHelp(V.get(v2),'+',L(skipFirstWord?"Only class ":"Allows only class ")));
}
break;
case _MAXCLASSLEVEL: // -MaxclassLevels
{
for(int v2=v+1;v2<V.size();v2++)
buf.append(levelHelp(V.get(v2),'+',L(skipFirstWord?"Only highest class ":"Allows only highest class ")));
}
break;
case _CLASSTYPE: // -classtype
{
buf.append(L((skipFirstWord?"The":"Requires")+" the following type"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case CLASSTYPE: // +classtype
{
buf.append(L("Disallows the following type"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _TATTOO: // -Tattoos
{
buf.append(L((skipFirstWord?"The":"Requires")+" the following tattoo"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case TATTOO: // +Tattoos
{
buf.append(L("Disallows the following tattoo"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _WEAPONAMMO: // -WeaponAmmo
{
buf.append(L((skipFirstWord?"The":"Requires")+" weapons that use: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case WEAPONAMMO: // +weaponsmmo
{
buf.append(L("Disallows weapons that use : "));
v=appendCommaList(buf,V,v,"-");
}
break;
case LOCATION: // +location
{
buf.append(L((skipFirstWord?"":"Disallows")+" being at places like : "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _LOCATION: // -location
{
buf.append(L((skipFirstWord?"":"Requires")+" being at places like : "));
v=appendCommaList(buf,V,v,"+");
}
break;
case _MOOD: // -Mood
{
buf.append(L((skipFirstWord?"The":"Requires")+" the following mood"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case MOOD: // +Mood
{
buf.append(L("Disallows the following mood"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _ACCCHIEVE: // -accchieves
{
buf.append(L((skipFirstWord?"The":"Requires")+" the following account achievement"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final AchievementLibrary.Achievement A=CMLib.achievements().getAchievement(str2.substring(1));
if(A!=null)
buf.append(A.getDisplayStr()+", ");
else
buf.append(str2.substring(1)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case ACCCHIEVE: // +accchieves
{
buf.append(L("Disallows the following account achievement"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final AchievementLibrary.Achievement A=CMLib.achievements().getAchievement(str2.substring(1));
if(A!=null)
buf.append(A.getDisplayStr()+", ");
else
buf.append(str2.substring(1)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _SECURITY: // -Security
{
buf.append(L((skipFirstWord?"The":"Requires")+" following security flag"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case SECURITY: // +security
{
buf.append(L("Disallows the following security flag"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _EXPERTISE: // -expertises
{
buf.append(L((skipFirstWord?"The":"Requires")+" following expertise"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final ExpertiseLibrary.ExpertiseDefinition E=CMLib.expertises().getDefinition(str2.substring(1).toUpperCase().trim());
if(E!=null)
buf.append(E.name()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _OR: // -or
buf.append(L("-OR other than the following: "));
break;
case OR: // -or
buf.append(L("-OR- "));
break;
case EXPERTISE: // +expertises
{
buf.append(L("Disallows the following expertise"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final ExpertiseLibrary.ExpertiseDefinition E=CMLib.expertises().getDefinition(str2.substring(1).toUpperCase().trim());
if(E!=null)
buf.append(E.name()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _SKILLFLAG: // -skillflags
{
buf.append(L((skipFirstWord?"A":"Requires a")+" skill of type: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final List<String> V3=CMParms.parseAny(str2.substring(1),'&',true);
String str3=null;
for(int v3=0;v3<V3.size();v3++)
{
str3=CMStrings.replaceAll(CMStrings.capitalizeAndLower(V3.get(v3)),"_"," ");
if(str3.startsWith("!"))
buf.append("not "+str3.substring(1));
else
buf.append(str3);
if(v3<(V3.size()-1))
buf.append(" and ");
else
buf.append(", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _SKILL: // -skills
{
buf.append(L((skipFirstWord?"O":"Requires o")+"ne of the following skills: "));
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
int prof=0;
str2=str2.substring(1);
final int x=str2.indexOf('(');
if(x>0)
{
if(str2.endsWith(")"))
prof=CMath.s_int(str2.substring(x+1,str2.length()-1));
str2=str2.substring(0,x);
}
final Ability A=CMClass.getAbility(str2);
if(A!=null)
{
if(prof<=0)
buf.append(A.name()+", ");
else
buf.append(L("@x1 at @x2% proficiency, ",A.name(),""+prof));
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case SKILL: // +skills
{
buf.append(L("Disallows the following skill"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
int prof=0;
str2=str2.substring(1);
final int x=str2.indexOf('(');
if(x>0)
{
if(str2.endsWith(")"))
prof=CMath.s_int(str2.substring(x+1,str2.length()-1));
str2=str2.substring(0,x);
}
final Ability A=CMClass.getAbility(str2);
if(A!=null)
{
if(prof<=0)
buf.append(A.name()+", ");
else
buf.append(L("@x1 at more than @x2% proficiency, ",A.name(),""+prof));
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case SKILLFLAG: // +skillflag
{
buf.append(L("Disallows the skill of type: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final List<String> V3=CMParms.parseAny(str2.substring(1),'&',true);
String str3=null;
for(int v3=0;v3<V3.size();v3++)
{
str3=CMStrings.replaceAll(CMStrings.capitalizeAndLower(V3.get(v3)),"_"," ");
if(str3.startsWith("!"))
buf.append("not "+str3.substring(1));
else
buf.append(str3);
if(v3<(V3.size()-1))
buf.append(" and ");
else
buf.append(", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _CLAN: // -Clan
{
buf.append(L((skipFirstWord?"M":"Requires m")+"embership in the following clan"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case CLAN: // +Clan
{
buf.append(L("Disallows the following clan"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _MATERIAL: // -Material
{
buf.append(L((skipFirstWord?"C":"Requires c")+"onstruction from the following material"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final int code=CMLib.materials().getMaterialCode(str2.substring(1),false);
if(code>=0)
buf.append(RawMaterial.Material.findByMask(code).noun()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case MATERIAL: // +Material
{
buf.append(L("Disallows items of the following material"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final int code=CMLib.materials().getMaterialCode(str2.substring(1),false);
if(code>=0)
buf.append(RawMaterial.Material.findByMask(code).noun()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _WORNON: // -wornon
{
buf.append(L((skipFirstWord?"A":"Requires a")+"bility to be worn: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final long code=Wearable.CODES.FIND_endsWith(str2.substring(1));
if(code>=0)
buf.append(Wearable.CODES.NAME(code)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case WORNON: // +wornon
{
buf.append(L("Disallows items capable of being worn: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final long code=Wearable.CODES.FIND_endsWith(str2.substring(1));
if(code>=0)
buf.append(Wearable.CODES.NAME(code)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _SENSES: // -senses
{
buf.append(L((skipFirstWord?"The":"Requires")+" following sense"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final int code=CMLib.flags().getSensesIndex(str2.substring(1));
if(code>=0)
buf.append(PhyStats.CAN_SEE_DESCS[code]+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case SENSES: // +senses
{
buf.append(L("Disallows the following sense"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final int code=CMLib.flags().getSensesIndex(str2.substring(1));
if(code>=0)
buf.append(PhyStats.CAN_SEE_DESCS[code]+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case HOUR: // +HOUR
{
buf.append(L("Disallowed during the following time"+(multipleQuals(V,v,"-")?"s":"")+" of the day: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _HOUR: // -HOUR
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following time"+(multipleQuals(V,v,"+")?"s":"")+" of the day: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case PORT: // +PORT
{
buf.append(L("Disallowed from the following ports: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _PORT: // -PORT
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"from the following ports: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case SEASON: // +season
{
buf.append(L("Disallowed during the following season"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
if(CMath.isInteger(str2.substring(1).trim()))
{
final int season=CMath.s_int(str2.substring(1).trim());
if((season>=0)&&(season<TimeClock.Season.values().length))
buf.append(TimeClock.Season.values()[season].toString()+", ");
}
else
{
final int season=determineSeasonCode(str2.substring(1).trim());
if((season>=0)&&(season<TimeClock.Season.values().length))
buf.append(TimeClock.Season.values()[season].toString()+", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _SEASON: // -season
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following season"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
if(CMath.isInteger(str2.substring(1).trim()))
{
final int season=CMath.s_int(str2.substring(1).trim());
if((season>=0)&&(season<TimeClock.Season.values().length))
buf.append(TimeClock.Season.values()[season].toString()+", ");
}
else
{
final int season=determineSeasonCode(str2.substring(1).trim());
if((season>=0)&&(season<TimeClock.Season.values().length))
buf.append(TimeClock.Season.values()[season].toString()+", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case WEATHER: // +weather
{
buf.append(L("Disallowed during the following weather condition"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
if(CMath.isInteger(str2.substring(1).trim()))
{
final int weather=CMath.s_int(str2.substring(1).trim());
if((weather>=0)&&(weather<Climate.WEATHER_DESCS.length))
buf.append(CMStrings.capitalizeAndLower(Climate.WEATHER_DESCS[weather])+", ");
}
else
{
final int weather=CMParms.indexOf(Climate.WEATHER_DESCS,str2.substring(1).toUpperCase().trim());
if((weather>=0)&&(weather<Climate.WEATHER_DESCS.length))
buf.append(CMStrings.capitalizeAndLower(Climate.WEATHER_DESCS[weather])+", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _WEATHER: // -weather
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following weather condition"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
if(CMath.isInteger(str2.substring(1).trim()))
{
final int weather=CMath.s_int(str2.substring(1).trim());
if((weather>=0)&&(weather<Climate.WEATHER_DESCS.length))
buf.append(CMStrings.capitalizeAndLower(Climate.WEATHER_DESCS[weather])+", ");
}
else
{
final int weather=CMParms.indexOf(Climate.WEATHER_DESCS,str2.substring(1).toUpperCase().trim());
if((weather>=0)&&(weather<Climate.WEATHER_DESCS.length))
buf.append(CMStrings.capitalizeAndLower(Climate.WEATHER_DESCS[weather])+", ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case MONTH: // +month
{
buf.append(L("Disallowed during the following month"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _MONTH: // -month
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following month"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case WEEK: // +week
{
buf.append(L("Disallowed during the following week"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _WEEK: // -week
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following week"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case WEEKOFYEAR: // +weekofyear
{
buf.append(L("Disallowed during the following week"+(multipleQuals(V,v,"-")?"s":"")+" of the year: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _WEEKOFYEAR: // -weekofyear
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following week"+(multipleQuals(V,v,"+")?"s":"")+" of the year: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case YEAR: // +year
{
buf.append(L("Disallowed during the following year"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _YEAR: // -year
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"during the following year"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case DAY: // +day
{
buf.append(L("Disallowed during the following day"+(multipleQuals(V,v,"-")?"s":"")+" of the month: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _DAY: // -day
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"on the following day"+(multipleQuals(V,v,"+")?"s":"")+" of the month: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case DAYOFYEAR: // +dayofyear
{
buf.append(L("Disallowed during the following day"+(multipleQuals(V,v,"-")?"s":"")+" of the year: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _DAYOFYEAR: // -dayofyear
{
buf.append(L((skipFirstWord?"Only ":"Allowed only ")+"on the following day"+(multipleQuals(V,v,"+")?"s":"")+" of the year: "));
v=appendCommaList(buf,V,v,"+");
}
break;
case QUALLVL: // +quallvl
if((v+1)<V.size())
{
final Ability A=CMClass.getAbility(V.get(v+1));
if(A!=null)
{
int adjustment=0;
if(((v+2)<V.size())&&(CMath.isInteger(V.get(v+2))))
adjustment=CMath.s_int(V.get(v+2));
buf.append(A.Name());
if(adjustment!=0)
buf.append(L("Qualifies for @x1",A.Name()));
else
if(adjustment<0)
buf.append(L("@x1 levels before qualifying for @x2",""+(-adjustment),A.Name()));
else
buf.append(L("@x1 levels after qualifying for @x2",""+adjustment,A.Name()));
buf.append(". ");
}
}
break;
case _QUALLVL: // -quallvl
if((v+1)<V.size())
{
final Ability A=CMClass.getAbility(V.get(v+1));
if(A!=null)
{
int adjustment=0;
if(((v+2)<V.size())&&(CMath.isInteger(V.get(v+2))))
adjustment=CMath.s_int(V.get(v+2));
buf.append(A.Name());
if(adjustment!=0)
buf.append(L("Does not qualify for @x1",A.Name()));
else
if(adjustment<0)
buf.append(L("Still prior to @x1 levels before qualifying for @x2",""+(-adjustment),A.Name()));
else
buf.append(L("Still prior to @x1 levels after qualifying for @x2",""+adjustment,A.Name()));
buf.append(". ");
}
}
break;
case _DISPOSITION: // -disposition
{
buf.append(L((skipFirstWord?"The":"Requires")+" following disposition"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final int code=CMLib.flags().getDispositionIndex(str2.substring(1));
if(code>=0)
buf.append(PhyStats.IS_DESCS[code]+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case DISPOSITION: // +disposition
{
buf.append(L("Disallows the following disposition"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final int code=CMLib.flags().getDispositionIndex(str2.substring(1));
if(code>=0)
buf.append(PhyStats.IS_DESCS[code]+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _RESOURCE: // -Resource
{
buf.append(L((skipFirstWord?"C":"Requires c")+"onstruction from the following material"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final int code=CMLib.materials().getResourceCode(str2.substring(1),false);
if(code>=0)
buf.append(CMStrings.capitalizeAndLower(RawMaterial.CODES.NAME(code))+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case RESOURCE: // +Resource
{
buf.append(L("Disallows items of the following material"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final int code=CMLib.materials().getResourceCode(str2.substring(1),false);
if(code>=0)
buf.append(CMStrings.capitalizeAndLower(RawMaterial.CODES.NAME(code))+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _JAVACLASS: // -JavaClass
{
buf.append(L((skipFirstWord?"B":"Requires b")+"eing of the following type"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case JAVACLASS: // +JavaClass
{
buf.append(L("Disallows being of the following type"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _DEITY: // -Deity
{
buf.append(L((skipFirstWord?"W":"Requires w")+"orshipping the following deity"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case DEITY: // +Deity
{
buf.append(L("Disallows the worshippers of: "));
v=appendCommaList(buf,V,v,"-");
}
break;
case NAME: // +Names
{
buf.append(L("Disallows the following mob/player name"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _NAME: // -Names
{
buf.append(L((skipFirstWord?"The":"Requires")+" following name"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case ACCOUNT: // +Account
{
buf.append(L("Disallows the following player account"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _ACCOUNT: // -Account
{
buf.append(L((skipFirstWord?"The":"Requires")+" following player account"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case _QUESTWIN: // -Questwin
{
buf.append(L((skipFirstWord?"Completing":"Requires completing")+" the following quest"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final Quest Q=CMLib.quests().fetchQuest(str2.substring(1));
if(Q==null)
buf.append(str2.substring(1)+", ");
else
if((Q.displayName()!=null)&&(Q.displayName().trim().length()>0))
buf.append(Q.displayName()+", ");
else
buf.append(Q.name()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case QUESTWIN: // +Questwin
{
buf.append(L("Disallows those who`ve won the following quest"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final Quest Q=CMLib.quests().fetchQuest(str2.substring(1));
if(Q==null)
buf.append(str2.substring(1)+", ");
else
if((Q.displayName()!=null)&&(Q.displayName().trim().length()>0))
buf.append(Q.displayName()+", ");
else
buf.append(Q.name()+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _PLAYER: // -Player
buf.append(L("Disallows players. "));
break;
case _NPC: // -MOB
buf.append(L("Disallows mobs/npcs. "));
break;
case RACE: // +races
{
buf.append(L("Disallows the following race"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case RACECAT: // +racecats
{
buf.append(L("Disallows the following racial category"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _ANYCLASSLEVEL: // -anyclasslevel
{
String className = "";
for(int v2=v+1;v2<V.size();v2++)
{
final String s = V.get(v2);
if(getMaskCodes().containsKey(s))
break;
boolean checkForClass = true;
boolean found=false;
if(className.length()>0)
{
final StringBuilder lvlHelp = levelHelp(V.get(v2),'+',L(skipFirstWord?"Only "+className+" ":"Allows only "+className+" "));
if(lvlHelp.length()>0)
{
buf.append(lvlHelp);
checkForClass = false;
found=true;
}
}
if(checkForClass)
{
for(final SavedClass C : charClasses())
{
if(s.startsWith('+'+C.nameStart))
{
className = C.name;
found=true;
break;
}
}
}
if(!found)
break;
}
}
break;
case ANYCLASSLEVEL: // +anyclasslevel
{
String className = "";
for(int v2=v+1;v2<V.size();v2++)
{
final String s = V.get(v2);
if(getMaskCodes().containsKey(s))
{
v=v2-1;
break;
}
boolean checkForClass = true;
boolean found=false;
if(className.length()>0)
{
final StringBuilder lvlHelp = levelHelp(V.get(v2),'-',"Disallows "+className+" ");
if(lvlHelp.length()>0)
{
buf.append(lvlHelp);
checkForClass = false;
found = true;
}
}
if(checkForClass)
{
for(final SavedClass C : charClasses())
{
if(s.startsWith('-'+C.nameStart))
{
className = C.name;
found = true;
break;
}
}
}
if(!found)
{
v=v2-1;
break;
}
else
if(v2==V.size()-1)
{
v=v2;
break;
}
}
}
break;
case _ANYCLASS: // -anyclass
{
buf.append(L((skipFirstWord?"L":"Requires l")+"evels in one of the following: "));
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'+',v+1,C.nameStart))
buf.append(C.name+", ");
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case ANYCLASS: // +anyclass
{
buf.append(L("Disallows any levels in any of the following: "));
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'-',v+1,C.nameStart))
buf.append(C.name+", ");
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case ADJSTRENGTH: // +adjstr
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" strength of at least @x1. ",""+val));
break;
case ADJINTELLIGENCE: // +adjint
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"An":"Requires an")+" intelligence of at least @x1. ",""+val));
break;
case ADJWISDOM: // +adjwis
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" wisdom of at least @x1. ",""+val));
break;
case ADJDEXTERITY: // +adjdex
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" dexterity of at least @x1. ",""+val));
break;
case ADJCONSTITUTION: // -adjcha
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" constitution of at least @x1. ",""+val));
break;
case ADJCHARISMA: // +adjcha
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" charisma of at least @x1. ",""+val));
break;
case _ADJSTRENGTH: // -adjstr
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" strength of at most @x1. ",""+val));
break;
case _ADJINTELLIGENCE: // -adjint
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"An":"Requires an")+" intelligence of at most @x1. ",""+val));
break;
case _ADJWISDOM: // -adjwis
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" wisdom of at most @x1. ",""+val));
break;
case _ADJDEXTERITY: // -adjdex
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" dexterity of at most @x1. ",""+val));
break;
case _ADJCONSTITUTION: // -adjcon
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" constitution of at most @x1. ",""+val));
break;
case _ADJCHARISMA: // -adjcha
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" charisma of at most @x1. ",""+val));
break;
case STRENGTH: // +str
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base strength of at least @x1. ",""+val));
break;
case INTELLIGENCE: // +int
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base intelligence of at least @x1. ",""+val));
break;
case WISDOM: // +wis
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base wisdom of at least @x1. ",""+val));
break;
case DEXTERITY: // +dex
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base dexterity of at least @x1. ",""+val));
break;
case CONSTITUTION: // +con
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base constitution of at least @x1. ",""+val));
break;
case CHARISMA: // +cha
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base charisma of at least @x1. ",""+val));
break;
case _STRENGTH: // -str
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base strength of at most @x1. ",""+val));
break;
case _INTELLIGENCE: // -int
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base intelligence of at most @x1. ",""+val));
break;
case _WISDOM: // -wis
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base wisdom of at most @x1. ",""+val));
break;
case _DEXTERITY: // -dex
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base dexterity of at most @x1. ",""+val));
break;
case _CONSTITUTION: // -con
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base constitution of at most @x1. ",""+val));
break;
case _CHARISMA: // -cha
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" base charisma of at most @x1. ",""+val));
break;
case _CHANCE: // -chance
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"":"Allowed ")+" "+(100-val)+"% of the time. "));
break;
case ABILITY: // +ability
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" magic/ability of at most @x1. ",""+val));
break;
case _ABILITY: // -ability
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" magic/ability of at least @x1. ",""+val));
break;
case VALUE: // +value
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" value of at most @x1. ",""+val));
break;
case _VALUE: // -value
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" value of at least @x1. ",""+val));
break;
case WEIGHT: // +weight
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" weight/encumbrance of at most @x1. ",""+val));
break;
case _WEIGHT: // -weight
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" weight/encumbrance of at least @x1. ",""+val));
break;
case ARMOR: // +armor
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" armor rating of at most @x1. ",""+val));
break;
case _ARMOR: // -armor
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" armor rating of at least @x1. ",""+val));
break;
case DAMAGE: // +damage
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" damage ability of at most @x1. ",""+val));
break;
case _DAMAGE: // -damage
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" damage ability of at least @x1. ",""+val));
break;
case ATTACK: // +attack
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"An":"Requires an")+" attack bonus of at most @x1. ",""+val));
break;
case _ATTACK: // -attack
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"An":"Requires an")+" attack bonus of at least @x1. ",""+val));
break;
case AREA: // +Area
{
buf.append(L("Disallows the following area"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _AREA: // -Area
{
buf.append(L((skipFirstWord?"The":"Requires the")+" following area"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case AREABLURB: // +Areablurb
{
buf.append(L("Disallows the following area blurb"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _AREABLURB: // -Areablurb
{
buf.append(L((skipFirstWord?"The":"Requires the")+" following area blurb"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case ISHOME: // +isHome
buf.append(L("Disallows those who are not in their home area. "));
break;
case _ISHOME: // -isHome
buf.append(L("Disallows those who are in their home area. "));
break;
case AREAINSTANCE: // +areainstance
buf.append(L("Disallows those who are not in an area instance. "));
break;
case _AREAINSTANCE: // -areainstance
buf.append(L("Disallows those who are in an area instance. "));
break;
case HOME: // +Home
{
buf.append(L("Disallows those whose home is the following area"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case PLANE: // +Plane
{
buf.append(L("Disallows those whose are on the following plane"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _HOME: // -Home
{
buf.append(L((skipFirstWord?"From the":"Requires being from the")+" following area"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case _PLANE: // -Plane
{
buf.append(L((skipFirstWord?"On the":"Requires being on the")+" following plane"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case _IFSTAT:
{
buf.append(L("Allows only those with "+(multipleQuals(V,v,"-")?"one of the following values":"the following value")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case IFSTAT:
{
buf.append(L("Disallows those with "+(multipleQuals(V,v,"-")?"one of the following values":"the following value")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case SUBNAME:
{
buf.append(L("Disallows those with the following partial name"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _SUBNAME:
{
buf.append(L("Allows only those with the following partial name"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"+");
}
break;
case ITEM: // +Item
{
buf.append(L("Disallows those with the following item"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case WORN:
{
buf.append(L((skipFirstWord?"The":"Requires the")+" following worn item"+(multipleQuals(V,v,"-")?"s":"")+": "));
v=appendCommaList(buf,V,v,"-");
}
break;
case _ITEM:
{
buf.append(L((skipFirstWord?"H":"Requires h")+"aving the following item"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v);
}
break;
case _WORN: // -Worn
{
buf.append(L((skipFirstWord?"W":"Requires w")+"earing the following item"+(multipleQuals(V,v,"+")?"s":"")+": "));
v=appendCommaList(buf,V,v);
}
break;
case EFFECT: // +Effects
{
buf.append(L("Disallows the following activities/effect"+(multipleQuals(V,v,"-")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final Ability A=CMClass.getAbility(str2.substring(1));
if(A!=null)
buf.append(A.name()+", ");
else
buf.append(str2.substring(1)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _EFFECT: // -Effects
{
buf.append(L((skipFirstWord?"P":"Requires p")+"articipation in the following activities/effect"+(multipleQuals(V,v,"+")?"s":"")+": "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final Ability A=CMClass.getAbility(str2.substring(1));
if(A!=null)
buf.append(A.name()+", ");
else
buf.append(str2.substring(1)+", ");
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case FACTION: // +faction
{
buf.append(L("Disallows the following: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
final Faction.FRange FR=getRange(str2.substring(1).toUpperCase().trim());
if(FR!=null)
{
final String desc=CMLib.factions().rangeDescription(FR,"or ");
if(desc.length()>0)
buf.append(desc+"; ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
if(buf.toString().endsWith("; "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _FACTION: // -faction
{
buf.append(L((skipFirstWord?"The":"Requires the")+" following: "));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final Faction.FRange FR=getRange(str2.substring(1).toUpperCase().trim());
if(FR!=null)
{
final String desc=CMLib.factions().rangeDescription(FR,"or ");
if(desc.length()>0)
buf.append(desc+"; ");
}
}
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
if(buf.toString().endsWith("; "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _WEAPONTYPE: // -weapontype
case WEAPONTYPE: // +weapontype
case _WEAPONCLASS: // -weaponclass
case WEAPONCLASS: // +weaponclass
{
if(key == ZapperKey._WEAPONTYPE )
buf.append(L((skipFirstWord?"The":"Requires the")+" following type of weapon(s): "));
else
buf.append(L((skipFirstWord?"The":"Disallows the")+" following type of weapon(s): "));
final String cw=(key == ZapperKey._WEAPONTYPE )?"+":"-";
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith(cw))
buf.append(str2.substring(1).toUpperCase().trim()).append(" ");
}
if(buf.toString().endsWith(", "))
buf.delete(buf.length()-2, buf.length());
if(buf.toString().endsWith("; "))
buf.delete(buf.length()-2, buf.length());
buf.append(". ");
}
break;
case _GROUPSIZE: // -groupsize
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" group size of at most @x1. ",""+val));
break;
case GROUPSIZE: // +groupsize
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
buf.append(L((skipFirstWord?"A":"Requires a")+" group size of at least @x1. ",""+val));
break;
case _IF: // -if
buf.append(L((skipFirstWord?"n":"Requires n")+"ot meeting the following condition(s):"));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
buf.append(str2).append(" ");
}
break;
case IF: // +if
buf.append(L((skipFirstWord?"m":"Requires m")+"meets the following condition(s):"));
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
buf.append(str2).append(" ");
}
break;
case OFFICER:
buf.append(L((skipFirstWord?"Being":"Requires being")+" an officer of the law "));
break;
case _OFFICER:
buf.append(L((skipFirstWord?"Not":"Disallows being")+" an officer of the law "));
break;
case JUDGE:
buf.append(L((skipFirstWord?"Being":"Requires being")+" a legal judge "));
break;
case _JUDGE:
buf.append(L((skipFirstWord?"Not":"Disallows being")+" a lega judge "));
break;
case SUBOP:
// this line intentionally left blank
break;
case SYSOP:
// this line intentionally left blank
break;
case _SUBOP:
// this line intentionally left blank
break;
case _SYSOP:
// this line intentionally left blank
break;
case LVLEQ:
// this line intentionally left blank
break;
case LVLGE:
// this line intentionally left blank
break;
case LVLGR:
// this line intentionally left blank
break;
case LVLLE:
// this line intentionally left blank
break;
case LVLLT:
// this line intentionally left blank
break;
}
}
else
{
for(final SavedClass C : charClasses())
{
if(str.startsWith("-"+C.nameStart))
buf.append(L("Disallows @x1. ",C.name));
}
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((str.startsWith(R.minusCatNameStart))&&(!cats.contains(R.racialCategory)))
{
cats.add(R.racialCategory);
buf.append(L("Disallows @x1. ",R.racialCategory));
}
}
if(str.startsWith("-"+Faction.Align.EVIL.toString().substring(0,3)))
buf.append(L("Disallows "+Faction.Align.EVIL.toString().toLowerCase()+". "));
if(str.startsWith("-"+Faction.Align.GOOD.toString().substring(0,3)))
buf.append(L("Disallows "+Faction.Align.GOOD.toString().toLowerCase()+". "));
if(str.startsWith("-"+Faction.Align.NEUTRAL.toString().substring(0,3)))
buf.append(L("Disallows "+Faction.Align.NEUTRAL.toString().toLowerCase()+". "));
if(str.startsWith("-MALE"))
buf.append(L("Disallows Males. "));
if(str.startsWith("-FEMALE"))
buf.append(L("Disallows Females. "));
if(str.startsWith("-NEUTER"))
buf.append(L((skipFirstWord?"Only ":"Allows only ")+"Males and Females. "));
buf.append(levelHelp(str,'-',L("Disallows ")));
if(str.startsWith("-"))
{
final Faction.FRange FR=getRange(str.substring(1));
final String desc=CMLib.factions().rangeDescription(FR,"and ");
if(desc.length()>0)
buf.append(L("Disallows ")+desc);
}
}
}
if(buf.length()==0)
buf.append(L("Anyone."));
return buf.toString();
}
protected final boolean isDateMatch(final Object o, final int num)
{
if(o instanceof Integer)
{
if(num==((Integer)o).intValue())
return true;
}
else
if(o instanceof Pair)
{
@SuppressWarnings("unchecked")
final Pair<Integer,Integer> p=(Pair<Integer,Integer>)o;
if((int)Math.round(CMath.floor(CMath.div(num,p.second.intValue())))==p.first.intValue())
return true;
}
else
if(o instanceof Triad)
{
@SuppressWarnings("unchecked")
final Triad<Integer,Integer,String> p=(Triad<Integer,Integer,String>)o;
if((num % p.second.intValue())==p.first.intValue())
return true;
}
return false;
}
@Override
public boolean syntaxCheck(final String mask, final List<String> errorSink)
{
if(mask.trim().length()==0)
return true;
final List<String> V=CMParms.parse(mask.toUpperCase());
for(int v=0;v<V.size();v++)
{
final String str=V.get(v);
final Map<String,ZapperKey> zapCodes=getMaskCodes();
if(zapCodes.containsKey(str))
return true;
for(final SavedClass C : charClasses())
{
if(str.startsWith(C.minusNameStart))
return true;
}
for(final SavedRace R : races())
{
if(str.startsWith(R.minusNameStart))
return true;
if(str.startsWith(R.minusCatNameStart))
return true;
}
if(str.startsWith("-"+Faction.Align.EVIL.toString().substring(0,3)))
return true;
if(str.startsWith("-"+Faction.Align.GOOD.toString().substring(0,3)))
return true;
if(str.startsWith("-"+Faction.Align.NEUTRAL.toString().substring(0,3)))
return true;
if(str.startsWith("-MALE"))
return true;
if(str.startsWith("-FEMALE"))
return true;
if(str.startsWith("-NEUTER"))
return true;
if(levelHelp(str,'-',"").length()>0)
return true;
if((str.startsWith("-"))
&&(CMLib.factions().isRangeCodeName(str.substring(1))))
return true;
}
errorSink.add("No valid zapper codes found.");
return false;
}
@Override
public List<String> getAbilityEduReqs(final String text)
{
final Vector<String> preReqs=new Vector<String>();
if(text.trim().length()==0)
return preReqs;
final Map<String,ZapperKey> zapCodes=getMaskCodes();
final List<String> V=CMParms.parse(text.toUpperCase());
String str2;
for(int v=0;v<V.size();v++)
{
final String str=V.get(v);
if(zapCodes.containsKey(str))
{
switch(zapCodes.get(str))
{
case _MAXCLASSLEVEL: // max class level...
//TODO:?!
break;
case _BASECLASS: // huh?
//TODO:?!
break;
case JAVACLASS: // +JAVACLASS
for(int v2=v+1;v2<V.size();v2++)
{
str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("-"))
{
str2=str2.substring(1);
final int x=str2.indexOf('(');
if(x>0)
str2=str2.substring(0,x);
final Ability A=CMClass.getAbilityPrototype(str2);
if(A!=null)
preReqs.remove(A.ID());
}
}
break;
case _JAVACLASS: // -JAVACLASS
for(int v2=v+1;v2<V.size();v2++)
{
str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
str2=str2.substring(1);
final int x=str2.indexOf('(');
if(x>0)
str2=str2.substring(0,x);
final Ability A=CMClass.getAbilityPrototype(str2);
if((A!=null)&&(!preReqs.contains(A.ID())))
preReqs.addElement(A.ID());
}
}
break;
case _EXPERTISE: // -expertises
{
for(int v2=v+1;v2<V.size();v2++)
{
str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
final ExpertiseLibrary.ExpertiseDefinition E=CMLib.expertises().getDefinition(str2.substring(1).toUpperCase().trim());
if(E!=null)
preReqs.addElement(E.ID());
}
}
}
break;
case _SKILL: // -skills
{
for(int v2=v+1;v2<V.size();v2++)
{
str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
str2=str2.substring(1);
final int x=str2.indexOf('(');
if(x>0)
str2=str2.substring(0,x);
final Ability A=CMClass.getAbilityPrototype(str2);
if((A!=null)&&(!preReqs.contains(A.ID())))
preReqs.addElement(A.ID());
}
}
}
break;
case _SKILLFLAG: // -skillflag
{
final ArrayList<Object> objs=new ArrayList<Object>();
Object o=null;
for(int v2=v+1;v2<V.size();v2++)
{
str2=V.get(v2);
if(zapCodes.containsKey(str2))
break;
if(str2.startsWith("+"))
{
str2=str2.substring(1);
o=this.makeSkillFlagObject(str2);
if(o!=null)
objs.add(o);
}
}
for(final Object O : objs)
{
for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();)
{
final Ability A=e.nextElement();
if((evaluateSkillFlagObject(O,A))
&&(!preReqs.contains(A.ID())))
{
preReqs.addElement(A.ID());
}
}
}
}
break;
default:
break;
}
}
}
return preReqs;
}
@Override
public int minMaskLevel(final String text, final int minMinLevel)
{
int level=minMinLevel;
final CompiledZMask cset=getPreCompiledMask(text);
for(final CompiledZMaskEntry[] entries : cset.entries())
{
for(final CompiledZMaskEntry entry : entries)
{
switch(entry.maskType())
{
case _LEVEL: // -level
{
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
level=((Integer)entry.parms()[v+1]).intValue()+1;
break;
case LVLGE: // +lvlge
level=((Integer)entry.parms()[v+1]).intValue();
break;
case LVLLT: // +lvlt
level=minMinLevel;
break;
case LVLLE: // +lvlle
level=minMinLevel;
break;
case LVLEQ: // +lvleq
level=((Integer)entry.parms()[v+1]).intValue();
break;
default:
break;
}
}
}
break;
case _CLASSLEVEL: // -classlevel
{
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
level=((Integer)entry.parms()[v+1]).intValue()+1;
break;
case LVLGE: // +lvlge
level=((Integer)entry.parms()[v+1]).intValue();
break;
case LVLLT: // +lvlt
level=minMinLevel;
break;
case LVLLE: // +lvlle
level=minMinLevel;
break;
case LVLEQ: // +lvleq
level=((Integer)entry.parms()[v+1]).intValue();
break;
default:
break;
}
}
}
break;
case _MAXCLASSLEVEL: // -maxclasslevel
{
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
level=((Integer)entry.parms()[v+1]).intValue()+1;
break;
case LVLGE: // +lvlge
level=((Integer)entry.parms()[v+1]).intValue();
break;
case LVLLT: // +lvlt
level=minMinLevel;
break;
case LVLLE: // +lvlle
level=minMinLevel;
break;
case LVLEQ: // +lvleq
level=((Integer)entry.parms()[v+1]).intValue();
break;
default:
break;
}
}
}
break;
case LVLGR: // +lvlgr
level=minMinLevel;
break;
case LVLGE: // +lvlge
level=minMinLevel;
break;
case LVLLT: // +lvlt
level=((Integer)entry.parms()[0]).intValue();
break;
case LVLLE: // +lvlle
level=((Integer)entry.parms()[0]).intValue()+1;
break;
case LVLEQ: // +lvleq
level=minMinLevel;
break;
default:
break;
}
}
}
return level;
}
@Override
public CompiledZMask maskCompile(final String text)
{
final ArrayList<ArrayList<CompiledZMaskEntry>> bufs=new ArrayList<ArrayList<CompiledZMaskEntry>>();
if((text==null)||(text.trim().length()==0))
return new CompiledZapperMaskImpl(new boolean[]{false,false},bufs.toArray(new CompiledZMaskEntry[0][0]));
ArrayList<CompiledZMaskEntry> buf=new ArrayList<CompiledZMaskEntry>();
bufs.add(buf);
final Map<String,ZapperKey> zapCodes=getMaskCodes();
final List<String> V=CMParms.parse(text.toUpperCase());
List<String> lV=null;
boolean buildItemFlag=false;
boolean buildRoomFlag=false;
ZapperKey entryType;
for(int v=0;v<V.size();v++)
{
final String str=V.get(v);
int val=-1;
entryType=zapCodes.get(str);
if(entryType!=null)
{
switch(entryType)
{
case _CLASS: // -class
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'+',v+1,C.nameStart))
parms.add(C.name);
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case CLASS: // +class
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'-',v+1,C.nameStart))
parms.add(C.name);
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case CLASSTYPE: // +classtype
case _CLASSTYPE: // -classtype
{
final String swc = (entryType == ZapperKey.CLASSTYPE) ? "-" : "+";
final ArrayList<Object> parms=new ArrayList<Object>();
if(lV==null)
lV=CMParms.parse(text);
for(int v2=v+1;v2<lV.size();v2++)
{
final String str2=lV.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith(swc))
{
final String possClassName = str2.substring(1);
final String ancestorStr = CMClass.findTypeAncestor(possClassName);
Class<?> ancestorC = null;
if((ancestorStr != null)&&(ancestorStr.length()>0))
{
try
{
ancestorC = Class.forName(ancestorStr);
}
catch(final Exception e)
{
}
}
if(ancestorC == null)
{
try
{
ancestorC = Class.forName(possClassName);
}
catch(final Exception e)
{
}
if((ancestorC == null)
&&(possClassName.indexOf('.')<0))
{
final String[] prefixes =
{
"com.planet_ink.coffee_mud.core.interfaces.",
"com.planet_ink.coffee_mud.MOBS.interfaces.",
"com.planet_ink.coffee_mud.MOBS.",
"com.planet_ink.coffee_mud.Items.interfaces.",
"com.planet_ink.coffee_mud.Items.",
"com.planet_ink.coffee_mud.Items.Armor.",
"com.planet_ink.coffee_mud.Items.Basic.",
"com.planet_ink.coffee_mud.Items.BasicTech.",
"com.planet_ink.coffee_mud.Items.CompTech.",
"com.planet_ink.coffee_mud.Items.MiscMagic.",
"com.planet_ink.coffee_mud.Items.Software.",
"com.planet_ink.coffee_mud.Items.Weapons.",
"com.planet_ink.coffee_mud.Locales.interfaces.",
"com.planet_ink.coffee_mud.Locales.",
"com.planet_ink.coffee_mud.Exits.interfaces.",
"com.planet_ink.coffee_mud.Exits.",
"com.planet_ink.coffee_mud.Areas.interfaces.",
"com.planet_ink.coffee_mud.Areas.",
"com.planet_ink.coffee_mud.Abilities.interfaces.",
"com.planet_ink.coffee_mud.Behaviors.interfaces.",
"com.planet_ink.coffee_mud.CharClasses.interfaces.",
"com.planet_ink.coffee_mud.Races.interfaces.",
"com.planet_ink.coffee_mud.Commands.interfaces.",
"com.planet_ink.coffee_mud.Libraries.interfaces.",
};
for(final String prefix : prefixes)
{
try
{
ancestorC = Class.forName(prefix+possClassName);
break;
}
catch(final Throwable e2)
{
}
}
}
}
if(ancestorC != null)
{
parms.add(ancestorC);
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _BASECLASS: // -baseclass
{
final ArrayList<Object> parms=new ArrayList<Object>();
final HashSet<String> seenBase=new HashSet<String>();
for(final SavedClass C : charClasses())
{
if(!seenBase.contains(C.baseClass))
{
seenBase.add(C.baseClass);
if(fromHereStartsWith(V,'+',v+1,C.baseClassStart))
parms.add(C.baseClass);
}
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case BASECLASS: // +baseclass
{
final ArrayList<Object> parms=new ArrayList<Object>();
final HashSet<String> seenBase=new HashSet<String>();
for(final SavedClass C : charClasses())
{
if(!seenBase.contains(C.baseClass))
{
seenBase.add(C.baseClass);
if(fromHereStartsWith(V,'-',v+1,C.baseClassStart))
parms.add(C.baseClass);
}
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case WEAPONTYPE: // +weapontype
case WEAPONCLASS: // +weaponclass
case _WEAPONTYPE: // -weapontype
case _WEAPONCLASS: // -weaponclass
{
final String cw=((entryType == ZapperKey._WEAPONCLASS)
||(entryType == ZapperKey._WEAPONTYPE)) ? "+":"-";
final String[] arr = ((entryType == ZapperKey._WEAPONCLASS)
||(entryType == ZapperKey.WEAPONCLASS)) ? Weapon.CLASS_DESCS : Weapon.TYPE_DESCS;
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith(cw))
{
str2=str2.substring(1).toUpperCase().trim();
final int x=CMParms.indexOf(arr,str2);
if(x >= 0)
parms.add(Integer.valueOf(x));
else
{
v=v2-1;
break;
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _RACE: // -Race
{
final ArrayList<Object> parms=new ArrayList<Object>();
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((!cats.contains(R.name)
&&(fromHereStartsWith(V,'+',v+1,R.nameStart))))
cats.add(R.name);
}
for(final String s : cats)
parms.add(s);
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _RACECAT: // -Racecats
{
final ArrayList<Object> parms=new ArrayList<Object>();
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((!cats.contains(R.racialCategory)
&&(fromHereStartsWith(V,'+',v+1,R.upperCatName))))
cats.add(R.racialCategory);
}
for(final String s : cats)
parms.add(s);
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case RACECAT: // +Racecats
{
final ArrayList<Object> parms=new ArrayList<Object>();
final LinkedList<String> cats=new LinkedList<String>();
for(final SavedRace R : races())
{
if((!cats.contains(R.racialCategory)
&&(fromHereStartsWith(V,'-',v+1,R.upperCatName))))
cats.add(R.racialCategory);
}
for(final String s : cats)
parms.add(s);
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case RACE: // +Race
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(final SavedRace R : races())
{
if(fromHereStartsWith(V,'-',v+1,R.upperName))
parms.add(R.name);
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case ALIGNMENT: // +Alignment
{
final ArrayList<Object> parms=new ArrayList<Object>();
if(fromHereStartsWith(V,'-',v+1,Faction.Align.EVIL.toString().substring(0,3)))
parms.add(Faction.Align.EVIL.toString());
if(fromHereStartsWith(V,'-',v+1,Faction.Align.GOOD.toString().substring(0,3)))
parms.add(Faction.Align.GOOD.toString());
if(fromHereStartsWith(V,'-',v+1,Faction.Align.NEUTRAL.toString().substring(0,3)))
parms.add(Faction.Align.NEUTRAL.toString());
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _ALIGNMENT: // -Alignment
{
final ArrayList<Object> parms=new ArrayList<Object>();
if(fromHereStartsWith(V,'+',v+1,Faction.Align.EVIL.toString().substring(0,3)))
parms.add(Faction.Align.EVIL.toString());
if(fromHereStartsWith(V,'+',v+1,Faction.Align.GOOD.toString().substring(0,3)))
parms.add(Faction.Align.GOOD.toString());
if(fromHereStartsWith(V,'+',v+1,Faction.Align.NEUTRAL.toString().substring(0,3)))
parms.add(Faction.Align.NEUTRAL.toString());
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _GENDER: // -Gender
{
final ArrayList<Object> parms=new ArrayList<Object>();
if(fromHereStartsWith(V,'+',v+1,"MALE"))
parms.add("M");
if(fromHereStartsWith(V,'+',v+1,"FEMALE"))
parms.add("F");
if(fromHereStartsWith(V,'+',v+1,"NEUTER"))
parms.add("N");
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case GENDER: // +Gender
{
final ArrayList<Object> parms=new ArrayList<Object>();
if(fromHereStartsWith(V,'-',v+1,"MALE"))
parms.add("M");
if(fromHereStartsWith(V,'-',v+1,"FEMALE"))
parms.add("F");
if(fromHereStartsWith(V,'-',v+1,"NEUTER"))
parms.add("N");
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _LEVEL: // -Levels
case _CLASSLEVEL: // -ClassLevels
case _MAXCLASSLEVEL: // -MaxclassLevels
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
final CompiledZMaskEntry e = levelCompiledHelper(str2,'+');
if(e!=null)
{
parms.add(e.maskType());
parms.add(e.parms()[0]);
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case ANYCLASSLEVEL: // +anyclasslevel
case _ANYCLASSLEVEL: // -anyclasslevel
{
final char plusMinus = (entryType == ZapperKey.ANYCLASSLEVEL) ? '-' : '+';
SavedClass charClassC = null;
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
boolean checkForClass = true;
boolean found=false;
if(charClassC!=null)
{
final CompiledZMaskEntry e = levelCompiledHelper(str2,plusMinus);
if(e!=null)
{
final CharClass C=CMClass.getCharClass(charClassC.id);
if(C!=null)
{
parms.add(C);
parms.add(e.maskType());
parms.add(e.parms()[0]);
checkForClass = false;
found=true;
}
}
}
if(checkForClass)
{
for(final SavedClass C : charClasses())
{
if(str2.startsWith(plusMinus+C.nameStart))
{
charClassC = C;
found=true;
break;
}
}
}
if(!found)
{
v=v2-1;
break;
}
else
if(v2==V.size()-1)
{
v=v2;
break;
}
}
if(parms.size()>0)
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _EFFECT: // -Effect
case EFFECT: // +Effect
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
str2=str2.substring(1);
CMObject A=CMClass.getAbility(str2);
if(A==null)
A=CMClass.getBehavior(str2);
if(A==null)
A=CMClass.getAbilityByName(str2,true);
if(A==null)
A=CMClass.getBehaviorByName(str2,true);
if(A==null)
A=CMClass.getAbilityByName(str2,false);
if(A==null)
A=CMClass.getBehaviorByName(str2,false);
if(A!=null)
parms.add(A.ID());
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case SECURITY: // +security
case _SECURITY: // -security
{
final String plusMinus=(entryType==ZapperKey._SECURITY)?"+":"-";
final ArrayList<CMSecurity.SecFlag> parms=new ArrayList<CMSecurity.SecFlag>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith(plusMinus))
{
final CMSecurity.SecFlag flag=(CMSecurity.SecFlag)CMath.s_valueOf(CMSecurity.SecFlag.class,str2.substring(1).toUpperCase().trim().replace(' ','_'));
if(flag == null)
Log.errOut("MUDZapper","Illegal security flag '"+str2);
else
parms.add(flag);
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new CMSecurity.SecFlag[0])));
break;
}
case _CLAN: // -Clan
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("+"))
{
int x;
if(((x=str2.lastIndexOf('('))>0)&&(str2.endsWith(")")))
parms.add(new Pair<String,String>(str2.substring(1,x),str2.substring(x+1,str2.length()-1)));
else
parms.add(str2.substring(1));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _SUBNAME:
case _WEAPONAMMO:
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("+"))
parms.add(str2.substring(1).toLowerCase());
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _AREABLURB: // -Areablurb
{
buildRoomFlag=true;
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("+"))
{
String rawParm=str2.substring(1).trim();
final int x=rawParm.indexOf(' ');
final String parmVal;
if(x>1)
{
parmVal=rawParm.substring(x+1);
rawParm=rawParm.substring(0,x);
}
else
parmVal="";
if(rawParm.startsWith("*"))
parms.add(new Triad<Character,String,String>(Character.valueOf('s'),rawParm.substring(1).toUpperCase(),parmVal));
else
if(rawParm.endsWith("*"))
parms.add(new Triad<Character,String,String>(Character.valueOf('e'),rawParm.substring(0,rawParm.length()-1).toUpperCase(),parmVal));
else
parms.add(new Triad<Character,String,String>(Character.valueOf(' '),rawParm.toUpperCase(),parmVal));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _AREA: // -Area
buildRoomFlag=true;
//$FALL-THROUGH$
case _TATTOO: // -Tattoos
case _MOOD: // -Mood
case _ACCCHIEVE: // -Accchieves
case _EXPERTISE: // -expertise
case _DEITY: // -Deity
case _NAME: // -Names
case _ACCOUNT: // -Accounts
case _QUESTWIN: // -Questwin
case _HOME: // -Home
case _PLANE: // -Plane
case _JAVACLASS: // -JavaClass
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("+"))
parms.add(str2.substring(1));
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case FACTION: // +Faction
case _FACTION: // -Faction
{
final String plusMinus=(entryType==ZapperKey._FACTION)?"+":"-";
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith(plusMinus))
{
final String str3=str2.substring(1).toUpperCase().trim();
if(str3.equalsIgnoreCase("EVIL")||str3.equalsIgnoreCase("NEUTRAL")||str3.equalsIgnoreCase("GOOD"))
{
parms.clear();
v=v2-1;
break;
}
else
{
//if(str3.startsWith("AREA_"))
// parms.add(str3);
//else
//final Faction.FRange FR=getRange(str3);
//if(FR==null)
// Log.debugOut("Range not found in MUDZapper: "+str3);
parms.add(str3);
}
}
v=V.size();
}
if(parms.size()>0)
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
case CLAN: // +Clan
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("-"))
{
int x;
if(((x=str2.indexOf('('))>0)&&(str2.endsWith(")")))
parms.add(new Pair<String,String>(str2.substring(1,x),str2.substring(x+1,str2.length()-1)));
else
parms.add(str2.substring(1));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case SUBNAME:
case WEAPONAMMO:
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("-"))
parms.add(str2.substring(1).toLowerCase());
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case LOCATION:
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("-"))
{
str2=str2.substring(1);
final int x=str2.indexOf('(');
String id=str2;
String str2parms="";
if(x>0)
{
id=str2.substring(0,x);
if(str2.endsWith(")"))
str2parms=str2.substring(x+1,str2.length()-1);
else
str2parms=str2.substring(x+1);
}
final LocationType T=(LocationType)CMath.s_valueOf(LocationType.class, id.toUpperCase());
if(T != null)
{
parms.add(T);
parms.add(str2parms);
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _LOCATION:
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("+"))
{
str2=str2.substring(1);
final int x=str2.indexOf('(');
String id=str2;
String str2parms="";
if(x>0)
{
id=str2.substring(0,x);
if(str2.endsWith(")"))
str2parms=str2.substring(x+1,str2.length()-1);
else
str2parms=str2.substring(x+1);
}
final LocationType T=(LocationType)CMath.s_valueOf(LocationType.class, id.toUpperCase());
if(T != null)
{
parms.add(T);
parms.add(str2parms);
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case AREABLURB: // +Areablurb
{
buildRoomFlag=true;
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("-"))
{
String rawParm=str2.substring(1).trim();
final int x=rawParm.indexOf(' ');
final String parmVal;
if(x>1)
{
parmVal=rawParm.substring(x+1);
rawParm=rawParm.substring(0,x);
}
else
parmVal="";
if(rawParm.startsWith("*"))
parms.add(new Triad<Character,String,String>(Character.valueOf('s'),rawParm.substring(1).toUpperCase(),parmVal));
else
if(rawParm.endsWith("*"))
parms.add(new Triad<Character,String,String>(Character.valueOf('e'),rawParm.substring(0,rawParm.length()-1).toUpperCase(),parmVal));
else
parms.add(new Triad<Character,String,String>(Character.valueOf(' '),rawParm.toUpperCase(),parmVal));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case AREA: // +Area
buildRoomFlag=true;
//$FALL-THROUGH$
case TATTOO: // +Tattoos
case MOOD: // +Mood
case ACCCHIEVE: // +Accchieves
case EXPERTISE: // +expertise
case DEITY: // +Deity
case NAME: // +Names
case ACCOUNT: // +Account
case QUESTWIN: // +Questwin
case HOME: // +Home
case PLANE: // +Plane
case JAVACLASS: // +JavaClass
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if(str2.startsWith("-"))
parms.add(str2.substring(1));
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _SKILL: // +skills
case SKILL: // -skills
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
str2=str2.substring(1);
int prof=0;
final int x=str2.indexOf('(');
if(x>0)
{
if(str2.endsWith(")"))
prof=CMath.s_int(str2.substring(x+1,str2.length()-1));
str2=str2.substring(0,x);
}
final Ability A=CMClass.getAbility(str2);
if(A!=null)
{
parms.add(A.ID());
parms.add(Integer.valueOf(prof));
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _SKILLFLAG: // -skillflag
case SKILLFLAG: // +skillflag
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
str2=str2.substring(1).toUpperCase();
final Object o=makeSkillFlagObject(str2);
if(o!=null)
parms.add(o);
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case ITEM: // +Item
case WORN: // +Worn
case _ITEM: // -Item
case _WORN: // -Worn
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("+"))||(str2.startsWith("-")))
parms.add(str2.substring(1));
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case MATERIAL: // +Material
case _MATERIAL: // -Material
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildItemFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final int code=CMLib.materials().getMaterialCode(str2.substring(1),false);
if(code>=0)
parms.add(RawMaterial.Material.findByMask(code&RawMaterial.MATERIAL_MASK).desc());
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case WORNON: // -WornOn
case _WORNON: // +WornOn
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildItemFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final long code=Wearable.CODES.FIND_endsWith(str2.substring(1));
if(code>=0)
parms.add(Long.valueOf(code));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case DISPOSITION: // +Disposition
case _DISPOSITION: // -Disposition
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final int code=CMLib.flags().getDispositionIndex(str2.substring(1));
if(code>=0)
parms.add(Integer.valueOf((int)CMath.pow(2,code)));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case SENSES: // +Senses
case _SENSES: // -Senses
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final int code=CMLib.flags().getSensesIndex(str2.substring(1));
if(code>=0)
parms.add(Integer.valueOf((int)CMath.pow(2,code)));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case SEASON: // +Season
case _SEASON: // -Season
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildRoomFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
if(CMath.isInteger(str2.substring(1).trim()))
parms.add(Integer.valueOf(CMath.s_int(str2.substring(1).trim())));
else
{
final int seasonCode=determineSeasonCode(str2.substring(1).trim());
if(seasonCode>=0)
parms.add(Integer.valueOf(seasonCode));
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case WEATHER: // +weather
case _WEATHER: // -weather
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildRoomFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
if(CMath.isInteger(str2.substring(1).trim()))
parms.add(Integer.valueOf(CMath.s_int(str2.substring(1).trim())));
else
if(CMParms.indexOf(Climate.WEATHER_DESCS,str2.substring(1).trim())>=0)
parms.add(Integer.valueOf(CMParms.indexOf(Climate.WEATHER_DESCS,str2.substring(1).trim())));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case PORT: // +PORT
case _PORT: // -PORT
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildRoomFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
parms.add(Integer.valueOf(CMath.s_int(str2.substring(1).trim())));
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case HOUR: // +HOUR
case _HOUR: // -HOUR
case MONTH: // +MONTH
case _MONTH: // -MONTH
case WEEK: // +WEEK
case _WEEK: // -WEEK
case WEEKOFYEAR: // +WEEKOFYEAR
case _WEEKOFYEAR: // -WEEKOFYEAR
case YEAR: // +YEAR
case _YEAR: // -YEAR
case DAY: // +DAY
case _DAY: // -DAY
case DAYOFYEAR: // +DAYOFYEAR
case _DAYOFYEAR: // -DAY
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildRoomFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final String lstr2=str2.toLowerCase();
final int x=lstr2.indexOf(' ');
if(x>0)
{
final String lstr3=lstr2.substring(1,x).trim();
final String nstr=lstr2.substring(x+1).trim();
if(lstr3.endsWith("st") || lstr3.endsWith("nd")
|| lstr3.endsWith("rd") || lstr3.endsWith("th"))
{
final String str3=lstr3.substring(0,lstr3.length()-2);
final int amt=CMath.s_int(str3.trim());
if(amt > 0)
{
parms.add(new Pair<Integer,Integer>(
Integer.valueOf(amt-1), // because 0 is the first X
Integer.valueOf(CMath.s_int(nstr.trim()))));
}
}
else
if(nstr.startsWith("of"))
{
final int amt=CMath.s_int(nstr.substring(2).trim());
if(amt > 0)
{
parms.add(new Triad<Integer,Integer,String>(
Integer.valueOf(CMath.s_int(lstr3)),
Integer.valueOf(amt-1), // // because 0 is the first in every X
null));
}
}
}
else
parms.add(Integer.valueOf(CMath.s_int(str2.substring(1).trim())));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case QUALLVL: // +quallvl
case _QUALLVL: // -quallvl
if((v+1)<V.size())
{
final Ability A=CMClass.getAbility(V.get(v+1));
if(A!=null)
{
int adjustment=0;
if(((v+2)<V.size())&&(CMath.isInteger(V.get(v+2))))
adjustment=CMath.s_int(V.get(v+2));
final ArrayList<Object> parms=new ArrayList<Object>();
parms.add(A.ID());
parms.add(Integer.valueOf(adjustment));
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
}
break;
case OFFICER: // +officer
case _OFFICER: // -officer
case JUDGE: // +judge
case _JUDGE: // -judge
case SUBOP: // +subop
case _SUBOP: // -subop
case AREAINSTANCE: // +areainstance
case _AREAINSTANCE: // -areainstance-
buildRoomFlag=true;
//$FALL-THROUGH$
case ISHOME: // +ishome
case _ISHOME: // -ishome
case SYSOP: // +sysop
case _SYSOP: // -sysop
{
buf.add(new CompiledZapperMaskEntryImpl(entryType,new Object[0]));
break;
}
case OR: // +or
case _OR: // -or
{
buf=new ArrayList<CompiledZMaskEntry>(1);
buf.add(new CompiledZapperMaskEntryImpl(entryType,new Object[0]));
bufs.add(buf);
buf=new ArrayList<CompiledZMaskEntry>();
bufs.add(buf);
break;
}
case _IFSTAT:
case IFSTAT:
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildItemFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final int x=str2.indexOf('=');
if(x>0)
{
parms.add(str2.toUpperCase().substring(1, x));
parms.add(str2.substring(x+1));
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case RESOURCE: // +Resource
case _RESOURCE: // -Resource
{
final ArrayList<Object> parms=new ArrayList<Object>();
buildItemFlag=true;
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2))
{
v=v2-1;
break;
}
else
if((str2.startsWith("-"))||(str2.startsWith("+")))
{
final int code=CMLib.materials().getResourceCode(str2.substring(1),false);
if(code>=0)
parms.add(RawMaterial.CODES.NAME(code));
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case _PLAYER: // -Player
case _NPC: // -MOB
{
buf.add(new CompiledZapperMaskEntryImpl(entryType,new Object[0]));
break;
}
case _ANYCLASS: // -anyclass
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'+',v+1,C.nameStart))
parms.add(C.name);
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case ANYCLASS: // +anyclass
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(final SavedClass C : charClasses())
{
if(fromHereStartsWith(V,'-',v+1,C.nameStart))
parms.add(C.name);
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
break;
case VALUE: // +value
case _VALUE: // -value
buildItemFlag=true;
//$FALL-THROUGH$
case ADJSTRENGTH: // +adjstr
case ADJINTELLIGENCE: // +adjint
case ADJWISDOM: // +adjwis
case ADJDEXTERITY: // +adjdex
case ADJCONSTITUTION: // -adjcha
case ADJCHARISMA: // +adjcha
case _ADJSTRENGTH: // -adjstr
case _ADJINTELLIGENCE: // -adjint
case _ADJWISDOM: // -adjwis
case _ADJDEXTERITY: // -adjdex
case _ADJCONSTITUTION: // -adjcon
case _ADJCHARISMA: // -adjcha
case STRENGTH: // +str
case INTELLIGENCE: // +int
case WISDOM: // +wis
case DEXTERITY: // +dex
case CONSTITUTION: // +con
case CHARISMA: // +cha
case _STRENGTH: // -str
case _INTELLIGENCE: // -int
case _WISDOM: // -wis
case _DEXTERITY: // -dex
case _CONSTITUTION: // -con
case _CHARISMA: // -cha
case _CHANCE: // -chance
case ABILITY: // +ability
case _ABILITY: // -ability
case WEIGHT: // +weight
case _WEIGHT: // -weight
case ARMOR: // +armor
case _ARMOR: // -armor
case DAMAGE: // +damage
case _DAMAGE: // -damage
case ATTACK: // +attack
case _ATTACK: // -attack
case _GROUPSIZE: // -groupsize
case GROUPSIZE: // +groupsize
{
val=((++v)<V.size())?CMath.s_int(V.get(v)):0;
final ArrayList<Object> parms=new ArrayList<Object>();
parms.add(Integer.valueOf(val));
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
case _IF: // -if
case IF: // +if
{
final ArrayList<Object> parms=new ArrayList<Object>();
for(int v2=v+1;v2<V.size();v2++)
{
final String str2=V.get(v2);
if(zapCodes.containsKey(str2)||(str2.startsWith("+"))||(str2.startsWith("-")))
{
v=v2-1;
break;
}
else
{
final ScriptingEngine SE = (ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine");
SE.setSavable(false);
SE.setVarScope("*");
try
{
final String[] tt = SE.parseEval(str2);
parms.add(SE);
final String[][] EVAL={tt};
parms.add(EVAL); // the compiled eval
final Object[] tmp = new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS];
parms.add(tmp);
}
catch(final ScriptParseException spe)
{
Log.errOut("MUDZapper","Script parse Exception for "+str2);
Log.errOut("MUDZapper",spe);
}
}
v=V.size();
}
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
case LVLEQ:
// intentially left blank
break;
case LVLGE:
// intentially left blank
break;
case LVLGR:
// intentially left blank
break;
case LVLLE:
// intentially left blank
break;
case LVLLT:
// intentially left blank
break;
}
}
else
{
boolean found=false;
if(!found)
{
for(final SavedClass C : charClasses())
{
if(str.equals("-"+C.upperName))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.CLASS;
parms.add(C.name);
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
}
}
if(!found)
{
for(final SavedRace R : races())
{
if(str.equals("-"+R.upperName))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.RACE;
parms.add(R.name);
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
}
}
if((!found)
&&(str.equals("-"+Faction.Align.EVIL.toString())))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.EVIL.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.equals("-"+Faction.Align.GOOD.toString())))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.GOOD.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.equals("-"+Faction.Align.NEUTRAL.toString())))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.NEUTRAL.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)&&(str.equals("-MALE")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("M");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)&&(str.equals("-FEMALE")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("F");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)&&(str.equals("-NEUTER")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("N");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-"))
&&(CMLib.factions().isRangeCodeName(str.substring(1))))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.FACTION;
parms.add(str.substring(1));
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if(!found)
{
for(final SavedClass C : charClasses())
{
if(str.startsWith(C.minusNameStart))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.CLASS;
parms.add(C.name);
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
}
}
if(!found)
{
for(final SavedRace R : races())
{
if(str.startsWith(R.minusNameStart))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.RACE;
parms.add(R.name);
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
break;
}
}
}
if(!found)
{
for(final SavedRace R : races())
{
if(str.startsWith(R.minusCatNameStart))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.RACECAT;
parms.add(R.racialCategory);
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
}
}
if((!found)
&&(str.startsWith("-"+Faction.Align.EVIL.toString().substring(0,3))))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.EVIL.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-"+Faction.Align.GOOD.toString().substring(0,3))))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.GOOD.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-"+Faction.Align.NEUTRAL.toString().substring(0,3))))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.ALIGNMENT;
parms.add(Faction.Align.NEUTRAL.toString());
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-MALE")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("M");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-FEMALE")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("F");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-NEUTER")))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.GENDER;
parms.add("N");
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if((!found)
&&(str.startsWith("-"))
&&(CMLib.factions().isRangeCodeName(str.substring(1))))
{
final ArrayList<Object> parms=new ArrayList<Object>();
entryType=ZapperKey.FACTION;
parms.add(str.substring(1));
found=true;
buf.add(new CompiledZapperMaskEntryImpl(entryType,parms.toArray(new Object[0])));
}
if(!found)
{
final CompiledZMaskEntry entry=levelCompiledHelper(str,'-');
if(entry!=null)
buf.add(entry);
}
}
}
final CompiledZMaskEntry[][] entrieses = new CompiledZMaskEntry[bufs.size()][];
for(int i=0;i<bufs.size();i++)
entrieses[i]=bufs.get(i).toArray(new CompiledZMaskEntry[0]);
return new CompiledZapperMaskImpl(new boolean[]{buildItemFlag,buildRoomFlag},entrieses);
}
protected Room outdoorRoom(final Area A)
{
Room R=null;
for(final Enumeration<Room> e=A.getMetroMap();e.hasMoreElements();)
{
R=e.nextElement();
if((R.domainType()&Room.INDOORS)==0)
return R;
}
return A.getRandomMetroRoom();
}
protected CharStats getBaseCharStats(CharStats base, final MOB mob)
{
if(base==null)
{
base=(CharStats)mob.baseCharStats().copyOf();
base.getMyRace().affectCharStats(mob,base);
}
return base;
}
@Override
public boolean maskCheck(final String text, final Environmental E, final boolean actual)
{
return maskCheck(getPreCompiledMask(text), E, actual);
}
@Override
public boolean maskCheck(final CompiledZMask cset, final Environmental E, final boolean actual)
{
if(E==null)
return true;
if((cset==null)||(cset.entries().length<1))
return true;
getMaskCodes();
final MOB mob=(E instanceof MOB)?(MOB)E:nonCrashingMOB();
final boolean[] flags=cset.flags();
final Item item=flags[0]?((E instanceof Item)?(Item)E:nonCrashingItem(mob)):null;
final Room room = flags[1]?((E instanceof Area)?outdoorRoom((Area)E):CMLib.map().roomLocation(E)):null;
final Physical P = (E instanceof Physical)?(Physical)E:null;
if((mob==null)||(flags[0]&&(item==null)))
return false;
if(E instanceof Area)
{
final int[] areaStats = ((Area)E).getAreaIStats();
mob.addFaction(CMLib.factions().getAlignmentID(), areaStats[Area.Stats.MED_ALIGNMENT.ordinal()]);
}
if(cset.entries().length<3)
return maskCheckSubEntries(cset.entries()[0],E,actual,mob,flags,item,room,P);
else
{
boolean lastValue = false;
boolean lastConnectorNot = false;
for(int i=0;i<cset.entries().length;i+=2)
{
boolean subResult = maskCheckSubEntries(cset.entries()[i],E,actual,mob,flags,item,room,P);
if(lastConnectorNot)
subResult = !subResult;
lastValue = lastValue || subResult;
if(i==cset.entries().length-1)
return lastValue;
final CompiledZMaskEntry entry = cset.entries()[i+1][0];
if(entry.maskType()==MaskingLibrary.ZapperKey._OR)
lastConnectorNot=true;
else
if(entry.maskType()==MaskingLibrary.ZapperKey.OR)
lastConnectorNot=false;
else
Log.errOut("Badly compiled zappermask @ "+E.Name()+"@"+CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E)));
}
return lastValue;
}
}
protected boolean maskCheckSubEntries(final CompiledZMaskEntry[] set, final Environmental E, final boolean actual,
final MOB mob, final boolean[] flags, final Item item, final Room room,
final Physical P)
{
CharStats base=null;
for(final CompiledZMaskEntry entry : set)
{
try
{
switch(entry.maskType())
{
case OR: //+or
case _OR: //-or
Log.errOut("Badly compiled zappermask @ "+E.Name()+"@"+CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E)));
break;
case SYSOP: // +sysop
if(CMSecurity.isASysOp(mob))
return true;
break;
case _SYSOP: // -sysop
if(CMSecurity.isASysOp(mob))
return false;
break;
case SUBOP: // +subop
if(CMSecurity.isASysOp(mob)
||((room!=null)&&(room.getArea().amISubOp(mob.Name()))))
return true;
break;
case _SUBOP: // -subop
if(CMSecurity.isASysOp(mob)
||((room!=null)&&(room.getArea().amISubOp(mob.Name()))))
return false;
break;
case CLASS: // +class
if(CMParms.contains(entry.parms(),actual?mob.baseCharStats().getCurrentClass().name():mob.charStats().displayClassName()))
return false;
break;
case _CLASS: // -class
{
if(!CMParms.contains(entry.parms(),actual?mob.baseCharStats().getCurrentClass().name():mob.charStats().displayClassName()))
return false;
break;
}
case _BASECLASS: // -baseclass
{
String baseClass=mob.baseCharStats().getCurrentClass().baseClass();
if((!actual)
&&(!baseClass.equals(mob.charStats().displayClassName())))
{
final CharClass C=CMClass.getCharClass(mob.charStats().displayClassName());
if(C!=null)
baseClass=C.baseClass();
}
if(!CMParms.contains(entry.parms(),baseClass))
return false;
break;
}
case BASECLASS: // +baseclass
{
String baseClass=mob.baseCharStats().getCurrentClass().baseClass();
if((!actual)
&&(!baseClass.equals(mob.charStats().displayClassName())))
{
final CharClass C=CMClass.getCharClass(mob.charStats().displayClassName());
if(C!=null)
baseClass=C.baseClass();
}
if(CMParms.contains(entry.parms(),baseClass))
return false;
break;
}
case _CLASSTYPE: // -classtype
{
boolean found=false;
final Class<?> eC=E.getClass();
for(final Object o : entry.parms())
{
if(CMClass.checkAncestry(eC, (Class<?>)o))
{
found=true;
break;
}
}
if(!found)
return false;
break;
}
case CLASSTYPE: // +classtype
{
final Class<?> eC=E.getClass();
for(final Object o : entry.parms())
{
if(CMClass.checkAncestry(eC, (Class<?>)o))
return false;
}
break;
}
case _RACE: // -race
if(!CMParms.contains(entry.parms(),actual?mob.baseCharStats().getMyRace().name():mob.charStats().raceName()))
return false;
break;
case _ALIGNMENT: // -alignment
if(!CMParms.contains(entry.parms(),CMLib.flags().getAlignmentName(mob)))
return false;
break;
case _GENDER: // -gender
{
base=getBaseCharStats(base,mob);
if(!CMParms.contains(entry.parms(),actual?(""+((char)base.getStat(CharStats.STAT_GENDER))):(""+(Character.toUpperCase(mob.charStats().genderName().charAt(0))))))
return false;
break;
}
case _LEVEL: // -level
if(P!=null)
{
final int level=actual?P.basePhyStats().level():P.phyStats().level();
boolean found=false;
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
if(level>((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLGE: // +lvlge
if(level>=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLT: // +lvlt
if(level<((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLE: // +lvlle
if(level<=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLEQ: // +lvleq
if(level==((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
default:
break;
}
}
if(!found)
return false;
}
break;
case _CLASSLEVEL: // -classlevel
{
boolean found=false;
final int cl=actual?mob.baseCharStats().getClassLevel(mob.baseCharStats().getCurrentClass())
:mob.charStats().getClassLevel(mob.charStats().getCurrentClass());
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
if(cl>((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLGE: // +lvlge
if(cl>=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLT: // +lvlt
if(cl<((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLE: // +lvlle
if(cl<=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLEQ: // +lvleq
if(cl==((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
default:
break;
}
}
if(!found)
return false;
}
break;
case _ANYCLASSLEVEL: // -anyclasslevel
{
boolean allFound = false;
for(int i=0;i<entry.parms().length;i+=3)
{
boolean found=false;
final CharClass C = (CharClass)entry.parms()[i];
final int cl=actual?mob.baseCharStats().getClassLevel(C)
:mob.charStats().getClassLevel(C);
if(cl < 0)
found = false;
else
switch((ZapperKey)entry.parms()[i+1])
{
case LVLGR: // +lvlgr
if(cl>((Integer)entry.parms()[i+2]).intValue())
found=true;
break;
case LVLGE: // +lvlge
if(cl>=((Integer)entry.parms()[i+2]).intValue())
found=true;
break;
case LVLLT: // +lvlt
if(cl<((Integer)entry.parms()[i+2]).intValue())
found=true;
break;
case LVLLE: // +lvlle
if(cl<=((Integer)entry.parms()[i+2]).intValue())
found=true;
break;
case LVLEQ: // +lvleq
if(cl==((Integer)entry.parms()[i+2]).intValue())
found=true;
break;
default:
break;
}
allFound = allFound || found;
}
if(!allFound)
return false;
}
break;
case ANYCLASSLEVEL: // +classlevel
{
for(int i=0;i<entry.parms().length;i+=3)
{
final CharClass C = (CharClass)entry.parms()[i+0];
final int cl=actual?mob.baseCharStats().getClassLevel(C)
:mob.charStats().getClassLevel(C);
if(cl >= 0)
{
switch((ZapperKey)entry.parms()[i+1])
{
case LVLGR: // lvlgr
if(cl>((Integer)entry.parms()[i+2]).intValue())
return false;
break;
case LVLGE: // lvlge
if(cl>=((Integer)entry.parms()[i+2]).intValue())
return false;
break;
case LVLLT: // lvlt
if(cl<((Integer)entry.parms()[i+2]).intValue())
return false;
break;
case LVLLE: // lvlle
if(cl<=((Integer)entry.parms()[i+2]).intValue())
return false;
break;
case LVLEQ: // +lvleq
if(cl==((Integer)entry.parms()[i+2]).intValue())
return false;
break;
default:
break;
}
}
}
}
break;
case _MAXCLASSLEVEL: // -maxclasslevel
{
boolean found=false;
int cl=0;
int c2=0;
if(actual)
{
cl=mob.baseCharStats().getClassLevel(mob.baseCharStats().getMyClass(0));
for(int v=1;v<mob.baseCharStats().numClasses();v++)
{
c2=mob.baseCharStats().getClassLevel(mob.baseCharStats().getMyClass(v));
if(c2>cl)
cl=c2;
}
}
else
{
cl=mob.charStats().getClassLevel(mob.charStats().getMyClass(0));
for(int v=1;v<mob.charStats().numClasses();v++)
{
c2=mob.charStats().getClassLevel(mob.charStats().getMyClass(v));
if(c2>cl)
cl=c2;
}
}
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
if(cl>((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLGE: // +lvlge
if(cl>=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLT: // +lvlt
if(cl<((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLE: // +lvlle
if(cl<=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLEQ: // +lvleq
if(cl==((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
default:
break;
}
}
if(!found)
return false;
}
break;
case _TATTOO: // -tattoo
{
boolean found=false;
for(final Object o : entry.parms())
{
if((mob.findTattoo((String)o)!=null)
||((room!=null)&&(room.getArea().getBlurbFlag((String)o)!=null)))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case TATTOO: // +tattoo
{
for(final Object o : entry.parms())
{
if((mob.findTattoo((String)o)!=null)
||((room!=null)&&(room.getArea().getBlurbFlag((String)o)!=null)))
return false;
}
}
break;
case WEAPONTYPE: // +weapontype
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if(W instanceof Weapon)
{
if(CMParms.indexOf(entry.parms(), Integer.valueOf(((Weapon)W).weaponDamageType())) >= 0)
return false;
}
}
break;
case _WEAPONTYPE: // -weapontype
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if(W instanceof Weapon)
{
if(CMParms.indexOf(entry.parms(), Integer.valueOf(((Weapon)W).weaponDamageType())) < 0)
return false;
}
else
return false;
}
break;
case WEAPONAMMO: // +weaponammo
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if((W instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)W).requiresAmmunition()))
{
if(CMParms.indexOf(entry.parms(), ((AmmunitionWeapon)W).ammunitionType()) >= 0)
return false;
}
else
{
if(CMParms.indexOf(entry.parms(), "") >= 0)
return false;
}
}
break;
case _WEAPONAMMO: // -weaponammo
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if((W instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)W).requiresAmmunition()))
{
if(CMParms.indexOf(entry.parms(), ((AmmunitionWeapon)W).ammunitionType()) < 0)
return false;
}
else
{
if(CMParms.indexOf(entry.parms(), "") < 0)
return false;
}
}
break;
case LOCATION: // +location
{
final Room R=CMLib.map().roomLocation(E);
for(int i=0;i<entry.parms().length-1;i+=2)
{
if(checkLocation(E, mob, R, entry.parms()[i], entry.parms()[i+1]))
return false;
}
}
break;
case _LOCATION: // -location
{
final Room R=CMLib.map().roomLocation(E);
boolean found=false;
for(int i=0;i<entry.parms().length-1;i+=2)
{
if(checkLocation(E, mob, R, entry.parms()[i], entry.parms()[i+1]))
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case WEAPONCLASS: // +weaponclass
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if(W instanceof Weapon)
{
if(CMParms.indexOf(entry.parms(), Integer.valueOf(((Weapon)W).weaponClassification())) >= 0)
return false;
}
}
break;
case _WEAPONCLASS: // -weaponclass
{
final Environmental W=(E instanceof MOB) ? ((MOB)E).fetchWieldedItem() : E;
if(W instanceof Weapon)
{
if(CMParms.indexOf(entry.parms(), Integer.valueOf(((Weapon)W).weaponClassification())) < 0)
return false;
}
}
break;
case _OFFICER: // -officer
{
if(mob.isMonster())
{
final LegalBehavior B=CMLib.law().getLegalBehavior(mob.getStartRoom());
if((B!=null)
&&(B.isAnyOfficer(CMLib.law().getLegalObject(mob.getStartRoom()), mob)))
return false;
}
}
break;
case OFFICER: //+officer
{
if(!mob.isMonster())
return false;
final LegalBehavior B=CMLib.law().getLegalBehavior(mob.getStartRoom());
if((B!=null)
&&(!B.isAnyOfficer(CMLib.law().getLegalObject(mob.getStartRoom()), mob)))
return false;
}
break;
case _JUDGE: // -judge
{
if(mob.isMonster())
{
final LegalBehavior B=CMLib.law().getLegalBehavior(mob.getStartRoom());
if((B!=null)
&&(B.isJudge(CMLib.law().getLegalObject(mob.getStartRoom()), mob)))
return false;
}
}
break;
case JUDGE: // +judge
{
if(!mob.isMonster())
return false;
final LegalBehavior B=CMLib.law().getLegalBehavior(mob.getStartRoom());
if((B!=null)
&&(!B.isJudge(CMLib.law().getLegalObject(mob.getStartRoom()), mob)))
return false;
}
break;
case _MOOD: // -mood
{
String moodName = "NORMAL";
final Ability A = mob.fetchEffect("Mood");
if((A!=null)&&(A.text().trim().length()>0))
moodName=A.text().toUpperCase().trim();
if(!CMParms.contains(entry.parms(),moodName))
return false;
}
break;
case MOOD: // +mood
{
final String moodName;
final Ability A = mob.fetchEffect("Mood");
if((A!=null)&&(A.text().trim().length()>0))
moodName=A.text().toUpperCase().trim();
else
moodName= "NORMAL";
if(CMParms.contains(entry.parms(),moodName))
return false;
}
break;
case _ACCCHIEVE: // -accchieves
{
boolean found=false;
final PlayerStats playerStats = mob.playerStats();
if((playerStats != null) && (mob.playerStats().getAccount()!=null))
{
final PlayerAccount acct = playerStats.getAccount();
for(final Object o : entry.parms())
{
if((acct.findTattoo((String)o)!=null)
||((room!=null)&&(room.getArea().getBlurbFlag((String)o)!=null)))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case ACCCHIEVE: // +accchieves
{
final PlayerStats playerStats = mob.playerStats();
if((playerStats != null) && (mob.playerStats().getAccount()!=null))
{
final PlayerAccount acct = playerStats.getAccount();
for(final Object o : entry.parms())
{
if((acct.findTattoo((String)o)!=null)
||((room!=null)&&(room.getArea().getBlurbFlag((String)o)!=null)))
return false;
}
}
}
break;
case _EXPERTISE: // -expertise
{
boolean found=false;
for(final Object o : entry.parms())
{
if(mob.fetchExpertise((String)o)!=null)
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case EXPERTISE: // +expertise
{
for(final Object o : entry.parms())
{
if(mob.fetchExpertise((String)o)!=null)
return false;
}
}
break;
case _QUESTWIN: // -questwin
{
boolean found=false;
for(final Object o : entry.parms())
{
final Quest Q=CMLib.quests().fetchQuest((String)o);
if((Q!=null)&&(Q.wasWinner(mob.Name())))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case QUESTWIN: // +questwin
{
for(final Object o : entry.parms())
{
final Quest Q=CMLib.quests().fetchQuest((String)o);
if((Q!=null)&&(Q.wasWinner(mob.Name())))
return false;
}
}
break;
case _SKILL: // -skill
{
boolean found=false;
for(int v=0;v<entry.parms().length-1;v+=2)
{
final Ability A=mob.fetchAbility((String)entry.parms()[v]);
if((A!=null)&&(A.proficiency()>=((Integer)entry.parms()[v+1]).intValue()))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case _SKILLFLAG: // -skillflag
{
boolean found=false;
for(final Object o : entry.parms())
{
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(evaluateSkillFlagObject(o,A))
{
found = true;
break;
}
}
if(found)
break;
}
if(!found)
return false;
}
break;
case SKILL: // +skill
{
for(int v=0;v<entry.parms().length-1;v+=2)
{
final Ability A=mob.fetchAbility((String)entry.parms()[v]);
if((A!=null)&&(A.proficiency()>=((Integer)entry.parms()[v+1]).intValue()))
return false;
}
}
break;
case SKILLFLAG: // +skillflag
{
for(final Object o : entry.parms())
{
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(evaluateSkillFlagObject(o,A))
return false;
}
}
}
break;
case _SECURITY: // -security
{
boolean found=false;
for(final Object o : entry.parms())
{
if(CMSecurity.isAllowed(mob,room,(CMSecurity.SecFlag)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case SECURITY: // +security
{
for(final Object o : entry.parms())
{
if(CMSecurity.isAllowed(mob,room,(CMSecurity.SecFlag)o))
return false;
}
}
break;
case _NAME: // -names
{
boolean found=false;
final String name=actual?E.Name():E.name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case _ACCOUNT: // -accounts
{
boolean found=false;
final String name=((mob.playerStats()!=null)
&&(mob.playerStats().getAccount()!=null))?
mob.playerStats().getAccount().getAccountName():
E.Name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case SUBNAME: // +subname
{
final String name=(actual?E.Name():E.name()).toLowerCase();
for(final Object o : entry.parms())
{
final String s = (String)o; // already lowercased
if(s.startsWith("*"))
{
if(s.endsWith("*"))
{
if(name.indexOf(s.substring(1,s.length()-1))>=0)
{
return false;
}
}
else
if(name.endsWith(s.substring(1)))
{
return false;
}
}
else
if(s.endsWith("*"))
{
if(name.startsWith(s.substring(0,s.length()-1)))
{
return false;
}
}
else
if(name.indexOf(s)>=0)
{
return false;
}
}
}
break;
case _SUBNAME: // -subname
{
boolean found=false;
final String name=(actual?E.Name():E.name()).toLowerCase();
for(final Object o : entry.parms())
{
final String s = (String)o; // already lowercased
if(s.startsWith("*"))
{
if(s.endsWith("*"))
{
if(name.indexOf(s.substring(1,s.length()-1))>=0)
{
found=true;
break;
}
}
else
if(name.endsWith(s.substring(1)))
{
found=true;
break;
}
}
else
if(s.endsWith("*"))
{
if(name.startsWith(s.substring(0,s.length()-1)))
{
found=true;
break;
}
}
else
if(name.indexOf(s)>=0)
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case _PLAYER: // -player
if(!mob.isMonster())
return false;
break;
case _NPC: // -npc
if(mob.isMonster())
return false;
break;
case _RACECAT: // -racecat
{
String raceCat=mob.baseCharStats().getMyRace().racialCategory();
if((!actual)
&&(!mob.baseCharStats().getMyRace().name().equals(mob.charStats().raceName())))
{
final Race R2=CMClass.getRace(mob.charStats().raceName());
if(R2!=null)
raceCat=R2.racialCategory();
}
if(!CMParms.contains(entry.parms(),raceCat))
return false;
break;
}
case RACE: // +race
{
String race=mob.baseCharStats().getMyRace().name();
if((!actual)&&(!mob.baseCharStats().getMyRace().name().equals(mob.charStats().raceName())))
race=mob.charStats().raceName();
if(CMParms.contains(entry.parms(),race))
return false;
break;
}
case RACECAT: // +racecat
{
String raceCat=mob.baseCharStats().getMyRace().racialCategory();
if((!actual)&&(!mob.baseCharStats().getMyRace().name().equals(mob.charStats().raceName())))
{
final Race R2=CMClass.getRace(mob.charStats().raceName());
if(R2!=null)
raceCat=R2.racialCategory();
}
if(CMParms.contains(entry.parms(),raceCat))
return false;
break;
}
case _CLAN: // -clan
{
boolean found=false;
if(E instanceof ClanItem)
{
final String clanID=((ClanItem)E).clanID();
for(final Object o : entry.parms())
{
if(o instanceof String)
{
if((clanID.equalsIgnoreCase((String)o))
||(((String)o).equals("*") && (clanID.length()>0)))
{
found=true;
break;
}
}
else
if(o instanceof Pair)
{
@SuppressWarnings("unchecked")
final Pair<String,String> oP=((Pair<String,String>)o);
if(clanID.equalsIgnoreCase(oP.first)
||((oP.first).equals("*") && (clanID.length()>0)))
{
found=true;
break;
}
}
}
}
else
if(E instanceof MOB)
{
for(final Pair<Clan,Integer> c : ((MOB)E).clans())
{
final String clanID = c.first.clanID();
for(final Object o : entry.parms())
{
if(o instanceof String)
{
if(c.first.clanID().equalsIgnoreCase((String)o)
||(((String)o).equals("*") && (clanID.length()>0)))
{
found=true;
break;
}
}
else
if(o instanceof Pair)
{
@SuppressWarnings("unchecked")
final Pair<String,String> oP=((Pair<String,String>)o);
if(c.first.clanID().equalsIgnoreCase(oP.first)
||((oP.first).equals("*") && (clanID.length()>0)))
{
if((oP.second).equals("*"))
{
found=true;
break;
}
else
{
final ClanPosition cP=c.first.getGovernment().getPosition(oP.second);
if(cP==null)
{
final Clan.Function cf = (Clan.Function)CMath.s_valueOf(Clan.Function.class, oP.second);
if(cf != null)
{
final Authority a = c.first.getAuthority(c.second.intValue(), cf);
if((a!=null)&&(a != Authority.CAN_NOT_DO))
{
found=true;
break;
}
continue;
}
}
if((cP==null)||(cP.getRoleID()==c.second.intValue()))
{
found=true;
break;
}
}
}
}
}
}
}
if(!found)
return false;
}
break;
case CLAN: // +clan
if(E instanceof ClanItem)
{
final String clanID=((ClanItem)E).clanID();
for(final Object o : entry.parms())
{
if(o instanceof String)
{
if((clanID.equalsIgnoreCase((String)o))
||(((String)o).equals("*") && (clanID.length()>0)))
return false;
}
else
if(o instanceof Pair)
{
@SuppressWarnings("unchecked")
final Pair<String,String> oP=((Pair<String,String>)o);
if(clanID.equalsIgnoreCase(oP.first)
||((oP.first).equals("*") && (clanID.length()>0)))
return false;
}
}
}
else
if(E instanceof MOB)
{
for(final Pair<Clan,Integer> c : ((MOB)E).clans())
{
final String clanID = c.first.clanID();
for(final Object o : entry.parms())
{
if(o instanceof String)
{
if(clanID.equalsIgnoreCase((String)o)
||(((String)o).equals("*") && (clanID.length()>0)))
return false;
}
else
if(o instanceof Pair)
{
@SuppressWarnings("unchecked")
final Pair<String,String> oP=((Pair<String,String>)o);
if(clanID.equalsIgnoreCase(oP.first)
||((oP.first).equals("*") && (clanID.length()>0)))
{
if((oP.second).equals("*"))
return false;
else
{
final ClanPosition cP=c.first.getGovernment().getPosition(oP.second);
if(cP==null)
{
final Clan.Function cf = (Clan.Function)CMath.s_valueOf(Clan.Function.class, oP.second);
if(cf != null)
{
final Authority a = c.first.getAuthority(c.second.intValue(), cf);
if((a!=null)&&(a != Authority.CAN_NOT_DO))
return false;
}
}
if((cP!=null)&&(cP.getRoleID()==c.second.intValue()))
return false;
}
}
}
}
}
}
break;
case MATERIAL: // +material
if((item!=null)&&CMParms.contains(entry.parms(),RawMaterial.Material.findByMask(item.material()&RawMaterial.MATERIAL_MASK).desc()))
return false;
break;
case _MATERIAL: // -material
if((item!=null)&&(!CMParms.contains(entry.parms(),RawMaterial.Material.findByMask(item.material()&RawMaterial.MATERIAL_MASK).desc())))
return false;
break;
case WORNON: // +wornOn
if(item!=null)
{
for(final Object o : entry.parms())
{
if((item.rawProperLocationBitmap()&((Long)o).longValue())>0)
return false;
}
}
break;
case _WORNON: // -wornOn
{
boolean found=false;
if(item!=null)
{
for(final Object o : entry.parms())
{
if((item.rawProperLocationBitmap()&((Long)o).longValue())>0)
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case DISPOSITION: // +disposition
if(P!=null)
{
for(final Object o : entry.parms())
{
if((P.phyStats().disposition()&((Integer)o).intValue())>0)
return false;
}
}
break;
case _DISPOSITION: // -disposition
if(P!=null)
{
boolean found=false;
for(final Object o : entry.parms())
{
if((P.phyStats().disposition()&((Integer)o).intValue())>0)
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case SENSES: // +senses
if(P!=null)
{
for(final Object o : entry.parms())
{
if((P.phyStats().sensesMask()&((Integer)o).intValue())>0)
return false;
}
}
break;
case _SENSES: // -senses
if(P!=null)
{
boolean found=false;
for(final Object o : entry.parms())
{
if((P.phyStats().sensesMask()&((Integer)o).intValue())>0)
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case PORT: // +PORT
{
final MudHost host=CMLib.host();
for(final Object o : entry.parms())
{
if(host.getPort()==((Integer)o).intValue())
return false;
}
}
break;
case _PORT: // -PORT
{
final MudHost host=CMLib.host();
boolean found=false;
for(final Object o : entry.parms())
{
if(host.getPort()==((Integer)o).intValue())
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case HOUR: // +HOUR
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getHourOfDay();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _HOUR: // -HOUR
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getHourOfDay();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case YEAR: // +YEAR
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _YEAR: // -YEAR
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case WEEK: // +WEEK
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getWeekOfMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _WEEK: // -WEEK
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getWeekOfMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case SEASON: // +season
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getSeasonCode().ordinal();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _SEASON: // -season
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getSeasonCode().ordinal();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case WEATHER: // +weather
{
if(room!=null)
{
for(final Object o : entry.parms())
{
if(room.getArea().getClimateObj().weatherType(room)==((Integer)o).intValue())
return false;
}
}
}
break;
case _WEATHER: // -weather
{
boolean found=false;
if(room!=null)
{
for(final Object o : entry.parms())
{
if(room.getArea().getClimateObj().weatherType(room)==((Integer)o).intValue())
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case MONTH: // +month
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _MONTH: // -month
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case DAYOFYEAR: // +dayofyear
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getDayOfYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _DAYOFYEAR: // -dayofyear
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getDayOfYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case WEEKOFYEAR: // +weekofyear
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getWeekOfYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _WEEKOFYEAR: // -weekofyear
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getWeekOfYear();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case DAY: // +day
{
if(room!=null)
{
final int num = room.getArea().getTimeObj().getDayOfMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
return false;
}
}
}
break;
case _DAY: // -day
{
boolean found=false;
if(room!=null)
{
final int num = room.getArea().getTimeObj().getDayOfMonth();
for(final Object o : entry.parms())
{
if(isDateMatch(o,num))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case QUALLVL: // +quallvl
if(entry.parms().length>1)
{
final Ability A=CMClass.getAbility((String)entry.parms()[0]);
final int adjustment=((Integer)entry.parms()[1]).intValue();
final int lvl=CMLib.ableMapper().qualifyingClassLevel(mob,A);
final int clvl=CMLib.ableMapper().qualifyingLevel(mob,A)+adjustment;
if(lvl<clvl)
return false;
}
break;
case _QUALLVL: // -quallvl
if(entry.parms().length>1)
{
final Ability A=CMClass.getAbility((String)entry.parms()[0]);
final int adjustment=((Integer)entry.parms()[1]).intValue();
final int lvl=CMLib.ableMapper().qualifyingClassLevel(mob,A);
final int clvl=CMLib.ableMapper().qualifyingLevel(mob,A)+adjustment;
if(lvl>clvl)
return false;
}
break;
case RESOURCE: // +resource
if((item!=null)&&CMParms.contains(entry.parms(),RawMaterial.CODES.NAME(item.material())))
return false;
break;
case _RESOURCE: // -resource
if((item!=null)&&(!CMParms.contains(entry.parms(),RawMaterial.CODES.NAME(item.material()))))
return false;
break;
case _JAVACLASS: // -JavaClass
{
boolean found=false;
for(final Object o : entry.parms())
{
if(E.ID().equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case JAVACLASS: // +JavaClass
for(final Object o : entry.parms())
{
if(E.ID().equalsIgnoreCase((String)o))
return false;
}
break;
case _DEITY: // -deity
{
final String worshipCharID=(actual?mob.charStats():mob.baseCharStats()).getWorshipCharID();
if(worshipCharID.length()==0)
return false;
boolean found=false;
for(final Object o : entry.parms())
{
if(worshipCharID.equalsIgnoreCase((String)o)||((String)o).equals("ANY"))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case DEITY: // +deity
{
final String worshipCharID=(actual?mob.charStats():mob.baseCharStats()).getWorshipCharID();
if(worshipCharID.length()>0)
{
for(final Object o : entry.parms())
{
if(worshipCharID.equalsIgnoreCase((String)o))
return false;
}
}
}
break;
case _EFFECT: // -effects
{
boolean found=false;
if(E instanceof PhysicalAgent)
{
for(final Object o : entry.parms())
{
if(((Physical)E).fetchEffect((String)o)!=null)
{
found = true;
break;
}
}
}
if((!found)&&(E instanceof PhysicalAgent))
{
for(final Object o : entry.parms())
{
if(((PhysicalAgent)E).fetchBehavior((String)o)!=null)
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case _FACTION: // -faction
{
boolean found=false;
for(final Object o : entry.parms())
{
final Faction.FRange FR=getRange((String)o);
if((FR!=null)&&(CMLib.factions().isFactionedThisWay(mob,FR)))
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case FACTION: // +faction
{
for(final Object o : entry.parms())
{
final Faction.FRange FR=getRange((String)o);
if((FR!=null)&&(CMLib.factions().isFactionedThisWay(mob,FR)))
return false;
}
}
break;
case EFFECT: // +effects
{
if(E instanceof Physical)
{
for(final Object o : entry.parms())
{
if(((Physical)E).fetchEffect((String)o)!=null)
return false;
}
}
if(E instanceof PhysicalAgent)
{
for(final Object o : entry.parms())
{
if(((PhysicalAgent)E).fetchBehavior((String)o)!=null)
return false;
}
}
}
break;
case NAME: // +name
{
final String name=actual?E.Name():E.name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
return false;
}
}
break;
case ACCOUNT: // +account
{
final String name=((mob.playerStats()!=null)
&&(mob.playerStats().getAccount()!=null))?
mob.playerStats().getAccount().getAccountName():
E.Name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
return false;
}
}
break;
case _ANYCLASS: // -anyclass
{
boolean found=false;
if(actual)
{
for(final Object o : entry.parms())
{
if(mob.baseCharStats().getClassLevel((String)o)>=0)
{
found = true;
break;
}
}
}
else
{
for(final Object o : entry.parms())
{
if((mob.charStats().getClassLevel((String)o)>=0)
||(mob.charStats().displayClassName().equalsIgnoreCase((String)o)))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case ANYCLASS: // +anyclass
if(actual)
{
for(final Object o : entry.parms())
{
if(mob.baseCharStats().getClassLevel((String)o)>=0)
return false;
}
}
else
{
for(final Object o : entry.parms())
{
if((mob.charStats().getClassLevel((String)o)>=0)
||(mob.charStats().displayClassName().equalsIgnoreCase((String)o)))
return false;
}
}
break;
case ADJSTRENGTH: // +adjstr
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_STRENGTH)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ADJINTELLIGENCE: // +adjint
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ADJWISDOM: // +adjwis
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_WISDOM)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ADJDEXTERITY: // +adjdex
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_DEXTERITY)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ADJCONSTITUTION: // -adjcha
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_CONSTITUTION)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ADJCHARISMA: // +adjcha
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_CHARISMA)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJSTRENGTH: // -adjstr
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_STRENGTH)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJINTELLIGENCE: // -adjint
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJWISDOM: // -adjwis
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_WISDOM)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJDEXTERITY: // -adjdex
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_DEXTERITY)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJCONSTITUTION: // -adjcon
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_CONSTITUTION)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ADJCHARISMA: // -adjcha
if((entry.parms().length>0)&&(mob.charStats().getStat(CharStats.STAT_CHARISMA)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case STRENGTH: // +str
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_STRENGTH)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case INTELLIGENCE: // +int
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_INTELLIGENCE)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case WISDOM: // +wis
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_WISDOM)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case DEXTERITY: // +dex
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_DEXTERITY)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case CONSTITUTION: // +con
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_CONSTITUTION)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case CHARISMA: // +cha
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_CHARISMA)<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _STRENGTH: // -str
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_STRENGTH)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _INTELLIGENCE: // -int
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_INTELLIGENCE)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _WISDOM: // -wis
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_WISDOM)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _DEXTERITY: // -dex
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_DEXTERITY)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _CONSTITUTION: // -con
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)&&(base.getStat(CharStats.STAT_CONSTITUTION)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _CHARISMA: // -cha
base=getBaseCharStats(base,mob);
if((entry.parms().length>0)
&&(base.getStat(CharStats.STAT_CHARISMA)>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _CHANCE: // -chance
if((entry.parms().length>0)
&&(CMLib.dice().rollPercentage()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ABILITY: // +ability
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().ability()>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ABILITY: // -ability
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().ability()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case WEIGHT: // +weight
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().weight()>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _WEIGHT: // -weight
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().weight()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ARMOR: // +armor
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().armor()>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ARMOR: // -armor
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().armor()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case DAMAGE: // +damage
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().damage()>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _DAMAGE: // -damage
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().damage()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case ATTACK: // +attack
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().attackAdjustment()>(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case _ATTACK: // -attack
if((entry.parms().length>0)
&&(P != null)
&&(P.phyStats().attackAdjustment()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case VALUE: // +value
if(E instanceof MOB)
{
if((entry.parms().length>0)
&&(CMLib.beanCounter().getTotalAbsoluteValueAllCurrencies(mob)>(((Integer)entry.parms()[0]).intValue())))
return false;
}
else
{
if((entry.parms().length>0)
&&(item!=null)&&(item.baseGoldValue()>(((Integer)entry.parms()[0]).intValue())))
return false;
}
break;
case _VALUE: // -value
if(E instanceof MOB)
{
if((entry.parms().length>0)
&&(CMLib.beanCounter().getTotalAbsoluteValueAllCurrencies(mob)<(((Integer)entry.parms()[0]).intValue())))
return false;
}
else
{
if((entry.parms().length>0)
&&(item!=null)&&(item.baseGoldValue()<(((Integer)entry.parms()[0]).intValue())))
return false;
}
break;
case _AREA: // -area
{
boolean found=false;
if(room!=null)
{
final Area A=room.getArea();
for(final Object o : entry.parms())
{
if(((String)o).startsWith("*"))
{
if(A.Name().toLowerCase().endsWith(((String)o).substring(1).toLowerCase()))
{
found = true;
break;
}
}
else
if(A.Name().equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case AREA: // +area
{
if(room!=null)
{
final Area A=room.getArea();
for(final Object o : entry.parms())
{
if(((String)o).startsWith("*"))
{
if(A.Name().toLowerCase().endsWith(((String)o).substring(1).toLowerCase()))
return false;
}
else
if(A.Name().equalsIgnoreCase((String)o))
return false;
}
}
break;
}
case _AREAINSTANCE: // -areainstance
if(room!=null)
{
final Area A=room.getArea();
if(CMath.bset(A.flags(), Area.FLAG_INSTANCE_CHILD))
return false;
}
break;
case AREAINSTANCE: // +areainstance
if(room!=null)
{
final Area A=room.getArea();
if(!CMath.bset(A.flags(), Area.FLAG_INSTANCE_CHILD))
return false;
}
break;
case _AREABLURB: // -areablurb
{
boolean found=false;
if(room!=null)
{
final Area A=room.getArea();
for(final Enumeration<String> b = A.areaBlurbFlags(); b.hasMoreElements();)
{
final String areaBlurb = b.nextElement();
for(final Object o : entry.parms())
{
@SuppressWarnings("unchecked")
final Triad<Character,String,String> t =(Triad<Character,String,String>)o;
switch(t.first.charValue())
{
case 's':
if(areaBlurb.endsWith(t.second))
found = true;
break;
case 'e':
if(areaBlurb.startsWith(t.second))
found = true;
break;
case ' ':
if(areaBlurb.equals(t.second))
found = true;
break;
}
if(found)
{
if((t.third.length()>0)
&&(!A.getBlurbFlag(areaBlurb).equalsIgnoreCase(t.third)))
found=false;
else
break;
}
}
}
}
if(!found)
return false;
}
break;
case AREABLURB: // +areablurb
{
if(room!=null)
{
final Area A=room.getArea();
for(final Object o : entry.parms())
{
for(final Enumeration<String> b = A.areaBlurbFlags(); b.hasMoreElements();)
{
final String areaBlurb = b.nextElement();
@SuppressWarnings("unchecked")
final Triad<Character,String,String> t =(Triad<Character,String,String>)o;
switch(t.first.charValue())
{
case 's':
if(areaBlurb.endsWith(t.second))
{
if((t.third.length()==0)
||(A.getBlurbFlag(areaBlurb).equalsIgnoreCase(t.third)))
return false;
}
break;
case 'e':
if(areaBlurb.startsWith(t.second))
{
if((t.third.length()==0)
||(A.getBlurbFlag(areaBlurb).equalsIgnoreCase(t.third)))
return false;
}
break;
case ' ':
if(areaBlurb.equals(t.second))
{
if((t.third.length()==0)
||(A.getBlurbFlag(areaBlurb).equalsIgnoreCase(t.third)))
return false;
}
break;
}
}
}
}
break;
}
case _ISHOME: // -ishome
{
final Area homeA=CMLib.map().getStartArea(E);
final Area isA=CMLib.map().areaLocation(E);
if(homeA == isA)
return false;
break;
}
case ISHOME: // +ishome
{
final Area homeA=CMLib.map().getStartArea(E);
final Area isA=CMLib.map().areaLocation(E);
if(homeA != isA)
return false;
break;
}
case _PLANE: // -plane
{
boolean found=false;
if(E instanceof Physical)
{
String planeName = CMLib.flags().getPlaneOfExistence((Physical)E);
if(planeName == null)
planeName=L("Prime Material");
for(final Object o : entry.parms())
{
if(planeName.equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
}
if(!found)
return false;
break;
}
case PLANE: // +plane
{
if(E instanceof Physical)
{
String planeName = CMLib.flags().getPlaneOfExistence((Physical)E);
if(planeName == null)
planeName=L("Prime Material");
for(final Object o : entry.parms())
{
if(planeName.equalsIgnoreCase((String)o))
return false;
}
}
break;
}
case _HOME: // -home
{
boolean found=false;
final Area A=CMLib.map().getStartArea(E);
if(A!=null)
{
final String planeName=CMLib.flags().getPlaneOfExistence(A);
for(final Object o : entry.parms())
{
if(((String)o).startsWith("*"))
{
if(A.Name().toLowerCase().endsWith(((String)o).substring(1).toLowerCase()))
{
found = true;
break;
}
}
else
if((A.Name().equalsIgnoreCase((String)o))
||(((String)o).equalsIgnoreCase(planeName)))
{
found = true;
break;
}
}
}
if(!found)
return false;
break;
}
case HOME: // +home
{
final Area A=CMLib.map().getStartArea(E);
if(A!=null)
{
final String planeName=CMLib.flags().getPlaneOfExistence(A);
for(final Object o : entry.parms())
{
if(((String)o).startsWith("*"))
{
if(A.Name().toLowerCase().endsWith(((String)o).substring(1).toLowerCase()))
return false;
}
else
if((A.Name().equalsIgnoreCase((String)o))
||(((String)o).equalsIgnoreCase(planeName)))
return false;
}
}
}
break;
case _IFSTAT:
{
boolean found=false;
if(E instanceof Physical)
{
for(int i=0;i<entry.parms().length;i+=2)
{
if(CMLib.coffeeMaker().getAnyGenStat((Physical)E,(String)entry.parms()[i]).equalsIgnoreCase((String)entry.parms()[i+1]))
{
found=true;
break;
}
}
}
else
{
for(int i=0;i<entry.parms().length;i+=2)
{
if(E.getStat((String)entry.parms()[i]).equalsIgnoreCase((String)entry.parms()[i+1]))
{
found=true;
break;
}
}
}
if(!found)
return false;
}
break;
case IFSTAT:
{
if(E instanceof Physical)
{
for(int i=0;i<entry.parms().length;i+=2)
{
if(CMLib.coffeeMaker().getAnyGenStat((Physical)E,(String)entry.parms()[i]).equalsIgnoreCase((String)entry.parms()[i+1]))
return false;
}
}
else
{
for(int i=0;i<entry.parms().length;i+=2)
{
if(E.getStat((String)entry.parms()[i]).equalsIgnoreCase((String)entry.parms()[i+1]))
return false;
}
}
}
break;
case ITEM: // +item
{
for(final Object o : entry.parms())
{
if(mob.findItem((String)o)!=null)
return false;
}
}
break;
case _ITEM: // -item
{
boolean found=false;
for(final Object o : entry.parms())
{
if(mob.findItem((String)o)!=null)
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case WORN: // +worn
{
if(E instanceof MOB)
{
for(final Object o : entry.parms())
{
final Item I = mob.findItem((String)o);
if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY)))
return false;
}
}
else
if(E instanceof Item)
{
if(((Item)E).amWearingAt(Wearable.IN_INVENTORY))
return false;
}
}
break;
case _WORN: // -worn
if(E instanceof MOB)
{
boolean found=false;
for(final Object o : entry.parms())
{
final Item I=mob.findItem((String)o);
if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY)))
{
found = true;
break;
}
}
if(!found)
return false;
}
else
if(E instanceof Item)
{
if(((Item)E).amWearingAt(Wearable.IN_INVENTORY))
return false;
}
break;
case ALIGNMENT: // +alignment
if(CMParms.contains(entry.parms(),CMLib.flags().getAlignmentName(mob)))
return false;
break;
case GENDER: // +gender
base=getBaseCharStats(base,mob);
if(CMParms.contains(entry.parms(),actual?(""+((char)base.getStat(CharStats.STAT_GENDER))):(""+Character.toUpperCase(mob.charStats().genderName().charAt(0)))))
return false;
break;
case LVLGR: // +lvlgr
if((entry.parms().length>0)
&&(P!=null)
&&((actual?P.basePhyStats().level():P.phyStats().level())>((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLGE: // +lvlge
if((entry.parms().length>0)
&&(P!=null)
&&((actual?P.basePhyStats().level():P.phyStats().level())>=((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLLT: // +lvlt
if((entry.parms().length>0)
&&(P!=null)
&&((actual?P.basePhyStats().level():P.phyStats().level())<((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLLE: // +lvlle
if((entry.parms().length>0)
&&(P!=null)
&&((actual?P.basePhyStats().level():P.phyStats().level())<=((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLEQ: // +lvleq
if((entry.parms().length>0)
&&(P!=null)
&&((actual?P.basePhyStats().level():P.phyStats().level())==((Integer)entry.parms()[0]).intValue()))
return false;
break;
case GROUPSIZE: // +groupsize
if(entry.parms().length>0)
{
if(E instanceof Area)
{
final int[] areaStats = ((Area)E).getAreaIStats();
if(areaStats[Area.Stats.POPULATION.ordinal()]<(((Integer)entry.parms()[0]).intValue()))
return false;
}
else
if(mob.getGroupMembers(new HashSet<MOB>(1)).size()<(((Integer)entry.parms()[0]).intValue()))
return false;
}
break;
case _GROUPSIZE: // -groupsize
if(entry.parms().length>0)
{
if(E instanceof Area)
{
final int[] areaStats = ((Area)E).getAreaIStats();
if(areaStats[Area.Stats.POPULATION.ordinal()]>(((Integer)entry.parms()[0]).intValue()))
return false;
}
else
if(mob.getGroupMembers(new HashSet<MOB>(1)).size()>(((Integer)entry.parms()[0]).intValue()))
return false;
}
break;
case _IF: // -if
{
boolean oneIsOK = false;
if(E instanceof PhysicalAgent)
{
for(int v=0;v<entry.parms().length-2;v+=3)
{
final ScriptingEngine SE = (ScriptingEngine)entry.parms()[v];
final String[][] EVAL = (String[][])entry.parms()[v+1];
final Object[] tmp = (Object[])entry.parms()[v+2];
final MOB M = SE.getMakeMOB(E);
final Item defaultItem=(E instanceof Item)?(Item)E:null;
if(SE.eval((PhysicalAgent)E, M, null,M, defaultItem, null, "", tmp, EVAL, 0))
{
oneIsOK = true;
break;
}
}
}
if(!oneIsOK)
return false;
break;
}
case IF: // +if
{
if(E instanceof PhysicalAgent)
{
for(int v=0;v<entry.parms().length-2;v+=3)
{
final ScriptingEngine SE = (ScriptingEngine)entry.parms()[v];
final String[][] EVAL = (String[][])entry.parms()[v+1];
final Object[] tmp = (Object[])entry.parms()[v+2];
final MOB M = SE.getMakeMOB(E);
final Item defaultItem=(E instanceof Item)?(Item)E:null;
if(E instanceof PhysicalAgent)
{
if(SE.eval((PhysicalAgent)E, M, null,M, defaultItem, null, "", tmp, EVAL, 0))
return true;
}
}
}
break;
}
}
}
catch (final NullPointerException n)
{
}
}
return true;
}
@Override
public boolean maskCheck(final String text, final PlayerLibrary.ThinPlayer E)
{
return maskCheck(getPreCompiledMask(text), E);
}
@Override
public boolean maskCheck(final CompiledZMask cset, final PlayerLibrary.ThinPlayer E)
{
if(E==null)
return true;
if((cset==null)||(cset.empty())||(cset.entries().length<1))
return true;
getMaskCodes();
if(cset.entries().length<3)
return maskCheckSubEntries(cset.entries()[0],E);
else
{
boolean lastValue = false;
boolean lastConnectorNot = false;
for(int i=0;i<cset.entries().length;i+=2)
{
boolean subResult = maskCheckSubEntries(cset.entries()[i],E);
if(lastConnectorNot)
subResult = !subResult;
lastValue = lastValue || subResult;
if(i==cset.entries().length-1)
return lastValue;
final CompiledZMaskEntry entry = cset.entries()[i+1][0];
if(entry.maskType()==MaskingLibrary.ZapperKey._OR)
lastConnectorNot=true;
else
if(entry.maskType()==MaskingLibrary.ZapperKey.OR)
lastConnectorNot=false;
else
Log.errOut("Badly compiled zappermask @ "+E.name());
}
return lastValue;
}
}
protected boolean maskCheckSubEntries(final CompiledZMaskEntry set[], final PlayerLibrary.ThinPlayer E)
{
//boolean[] flags=(boolean[])cset.firstElement();
for(final CompiledZMaskEntry entry : set)
{
try
{
switch(entry.maskType())
{
case OR: //+or
case _OR: //-or
Log.errOut("Badly compiled zappermask @ "+E.name());
break;
case SYSOP: // +sysop
if(CMSecurity.isASysOp(E))
return true;
break;
case _SYSOP: // -sysop
if(CMSecurity.isASysOp(E))
return false;
break;
case SUBOP: // +subop
if(CMSecurity.isASysOp(E))
return true;
for(final Enumeration<Area> e=CMLib.map().areas();e.hasMoreElements();)
{
if(e.nextElement().amISubOp(E.name()))
return true;
}
break;
case _SUBOP: // -subop
if(CMSecurity.isASysOp(E))
return false;
for(final Enumeration<Area> e=CMLib.map().areas();e.hasMoreElements();)
{
if(e.nextElement().amISubOp(E.name()))
return false;
}
break;
case _CLASS: // -class
{
final CharClass C=CMClass.getCharClass(E.charClass());
if((C==null)||(!CMParms.contains(entry.parms(),C.name())))
return false;
}
break;
case _BASECLASS: // -baseclass
{
final CharClass C=CMClass.getCharClass(E.charClass());
if((C==null)||(!CMParms.contains(entry.parms(),C.baseClass())))
return false;
}
break;
case BASECLASS: // +baseclass
{
final CharClass C=CMClass.getCharClass(E.charClass());
if((C!=null)&&(CMParms.contains(entry.parms(),C.baseClass())))
return false;
}
break;
case _RACE: // -race
{
final Race R=CMClass.getRace(E.race());
if((R==null)||(!CMParms.contains(entry.parms(),R.name())))
return false;
}
break;
case _DEITY: // -Deity
{
if(E.worship().trim().length()==0)
return false;
boolean found=false;
for(final Object o : entry.parms())
{
if(E.worship().equalsIgnoreCase((String)o)||((String)o).equals("ANY"))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case DEITY: // +Deity
{
if(E.worship().trim().length()>0)
{
for(final Object o : entry.parms())
{
if(E.worship().equalsIgnoreCase((String)o))
return false;
}
}
}
break;
case _LEVEL: // -level
{
final int level=E.level();
boolean found=false;
for(int v=0;v<entry.parms().length-1;v+=2)
{
switch((ZapperKey)entry.parms()[v])
{
case LVLGR: // +lvlgr
if(level>((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLGE: // +lvlge
if(level>=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLT: // +lvlt
if(level<((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLLE: // +lvlle
if(level<=((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
case LVLEQ: // +lvleq
if(level==((Integer)entry.parms()[v+1]).intValue())
found=true;
break;
default:
break;
}
}
if(!found)
return false;
}
break;
case _QUESTWIN: // -questwin
{
boolean found=false;
for(final Object o : entry.parms())
{
final Quest Q=CMLib.quests().fetchQuest((String)o);
if((Q!=null)&&(Q.wasWinner(E.name())))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case QUESTWIN: // +questwin
{
for(final Object o : entry.parms())
{
final Quest Q=CMLib.quests().fetchQuest((String)o);
if((Q!=null)&&(Q.wasWinner(E.name())))
return false;
}
}
break;
case _NAME: // -names
{
boolean found=false;
final String name=E.name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case _NPC: // -npc
break; // always true
case _RACECAT: // -racecat
{
final Race R=CMClass.getRace(E.race());
if((R==null)||(!CMParms.contains(entry.parms(),R.racialCategory())))
return false;
}
break;
case RACE: // +race
{
final Race R=CMClass.getRace(E.race());
if((R!=null)&&(CMParms.contains(entry.parms(),R.name())))
return false;
}
break;
case RACECAT: // +racecat
{
final Race R=CMClass.getRace(E.race());
if((R!=null)&&(CMParms.contains(entry.parms(),R.racialCategory())))
return false;
}
break;
case _JAVACLASS: // -JavaClass
{
boolean found=false;
for(final Object o : entry.parms())
{
if("StdMOB".equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
if(!found)
return false;
}
break;
case JAVACLASS: // +JavaClass
for(final Object o : entry.parms())
{
if("StdMOB".equalsIgnoreCase((String)o))
{
return false;
}
}
break;
case NAME: // +name
{
final String name=E.name();
for(final Object o : entry.parms())
{
if(name.equalsIgnoreCase((String)o))
{
return false;
}
}
}
break;
case SUBNAME: // +subname
{
final String name=E.name().toLowerCase();
for(final Object o : entry.parms())
{
final String s = (String)o; // already lowercased
if(s.startsWith("*"))
{
if(s.endsWith("*"))
{
if(name.indexOf(s.substring(1,s.length()-1))>=0)
{
return false;
}
}
else
if(name.endsWith(s.substring(1)))
{
return false;
}
}
else
if(s.endsWith("*"))
{
if(name.startsWith(s.substring(0,s.length()-1)))
{
return false;
}
}
else
if(name.indexOf(s)>=0)
{
return false;
}
}
}
break;
case _SUBNAME: //-subname
{
boolean found=false;
final String name=E.name().toLowerCase();
for(final Object o : entry.parms())
{
final String s = (String)o; // already lowercased
if(s.startsWith("*"))
{
if(s.endsWith("*"))
{
if(name.indexOf(s.substring(1,s.length()-1))>=0)
{
found=true;
break;
}
}
else
if(name.endsWith(s.substring(1)))
{
found=true;
break;
}
}
else
if(s.endsWith("*"))
{
if(name.startsWith(s.substring(0,s.length()-1)))
{
found=true;
break;
}
}
else
if(name.indexOf(s)>=0)
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case _ANYCLASS: // -anyclass
{
boolean found=false;
final CharClass C=CMClass.getCharClass(E.charClass());
if(C!=null)
{
for(final Object o : entry.parms())
{
if(C.name().equalsIgnoreCase((String)o))
{
found = true;
break;
}
}
}
if(!found)
return false;
}
break;
case ANYCLASS: // +anyclass
{
final CharClass C=CMClass.getCharClass(E.charClass());
if(C!=null)
{
for(final Object o : entry.parms())
{
if(C.name().equalsIgnoreCase((String)o))
{
return false;
}
}
}
}
break;
case ACCOUNT:// +accounts
case _ACCOUNT:// -accounts
case _ALIGNMENT: // -alignment
case _GENDER: // -gender
case _CLASSLEVEL: // -classlevel
case _MAXCLASSLEVEL: // -maxclasslevel
case ANYCLASSLEVEL: // +anyclasslevel
case _ANYCLASSLEVEL: // -anyclasslevel
case _TATTOO: // -tattoo
case TATTOO: // +tattoo
case _MOOD: // -mood
case MOOD: // +mood
case _OFFICER: // -officer
case OFFICER: // +officer
case _JUDGE: // -judge
case JUDGE: // +judge
case _ACCCHIEVE: // -accchieves
case ACCCHIEVE: // +accchieves
case _EXPERTISE: // -expertise
case EXPERTISE: // +expertise
case _SKILL: // -skill
case _SKILLFLAG: // -skillflag
case SKILL: // +skill
case SKILLFLAG: // +skillflag
case _SECURITY: // -security
case SECURITY: // +security
case _PLAYER: // -player
case _CLAN: // -clan
case CLAN: // +clan
case MATERIAL: // +material
case _MATERIAL: // -material
case WORNON: // +wornOn
case _WORNON: // -wornOn
case DISPOSITION: // +disposition
case _DISPOSITION: // -disposition
case SENSES: // +senses
case _SENSES: // -senses
case HOUR: // +HOUR
case _HOUR: // -HOUR
case SEASON: // +season
case _SEASON: // -season
case WEATHER: // +weather
case _WEATHER: // -weather
case MONTH: // +month
case _MONTH: // -month
case WEEK: // +week
case _WEEK: // -week
case WEEKOFYEAR: // +weekofyear
case _WEEKOFYEAR: // -weekofyear
case YEAR: // +year
case _YEAR: // -year
case DAY: // +day
case _DAY: // -day
case DAYOFYEAR: // +dayofyear
case _DAYOFYEAR: // -dayofyear
case QUALLVL: // +quallvl
case _QUALLVL: // -quallvl
case RESOURCE: // +resource
case _RESOURCE: // -resource
case _EFFECT: // -effects
case _FACTION: // -faction
case FACTION: // +faction
case EFFECT: // +effects
case ADJSTRENGTH: // +adjstr
case ADJINTELLIGENCE: // +adjint
case ADJWISDOM: // +adjwis
case ADJDEXTERITY: // +adjdex
case ADJCONSTITUTION: // +adjcon
case ADJCHARISMA: // +adjcha
case _ADJSTRENGTH: // -adjstr
case _ADJINTELLIGENCE: // -adjint
case _ADJWISDOM: // -adjwis
case _ADJDEXTERITY: // -adjdex
case _ADJCONSTITUTION: // -adjcon
case _ADJCHARISMA: // -adjcha
case STRENGTH: // +str
case INTELLIGENCE: // +int
case WISDOM: // +wis
case DEXTERITY: // +dex
case CONSTITUTION: // +con
case CHARISMA: // +cha
case _STRENGTH: // -str
case _INTELLIGENCE: // -int
case _WISDOM: // -wis
case _DEXTERITY: // -dex
case _CONSTITUTION: // -con
case _CHARISMA: // -cha
case ABILITY: // +ability
case _ABILITY: // -ability
case WEIGHT: // +weight
case _WEIGHT: // -weight
case ARMOR: // +armor
case _ARMOR: // -armor
case DAMAGE: // +damage
case _DAMAGE: // -damage
case ATTACK: // +attack
case _ATTACK: // -attack
case VALUE: // +value
case _VALUE: // -value
case _AREA: // -area
case AREA: // +area
case _AREAINSTANCE: // -areainstance
case AREAINSTANCE: // +areainstance
case _AREABLURB: // -areablurb
case AREABLURB: // +areablurb
case _HOME: // -home
case HOME: // +home
case _PLANE: // -plane
case PLANE: // +plane
case _ISHOME: // -ishome
case ISHOME: // +ishome
case _ITEM: // -item
case _WORN: // -worn
case ITEM: // +item
case WORN: // +worn
case ALIGNMENT: // +alignment
case GENDER: // +gender
case GROUPSIZE: // +groupsize
case _GROUPSIZE: // -groupsize
case _IFSTAT: // -ifstat
case IFSTAT: // +ifstat
case _CLASSTYPE: // -classtype
case CLASSTYPE: // +classtype
case WEAPONTYPE: // +weapontype
case WEAPONCLASS: // +weaponclass
case _WEAPONTYPE: // -weapontype
case _WEAPONCLASS: // -weaponclass
case WEAPONAMMO: // +weaponammo
case _WEAPONAMMO: // -weaponammo
case LOCATION: // +location
case _LOCATION: // -location
break;
case _IF: // -if
case IF: // +if
return false;
case LVLGR: // +lvlgr
if((entry.parms().length>0)&&((E.level())>((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLGE: // +lvlge
if((entry.parms().length>0)&&((E.level())>=((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLLT: // +lvlt
if((entry.parms().length>0)&&((E.level())<((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLLE: // +lvlle
if((entry.parms().length>0)&&((E.level())<=((Integer)entry.parms()[0]).intValue()))
return false;
break;
case LVLEQ: // +lvleq
if((entry.parms().length>0)&&((E.level())==((Integer)entry.parms()[0]).intValue()))
return false;
break;
case _CHANCE: // -chance
if((entry.parms().length>0)&&(CMLib.dice().rollPercentage()<(((Integer)entry.parms()[0]).intValue())))
return false;
break;
case PORT: // +PORT
{
final MudHost host=CMLib.host();
for(final Object o : entry.parms())
{
if(host.getPort()==((Integer)o).intValue())
return false;
}
}
break;
case _PORT: // -PORT
{
final MudHost host=CMLib.host();
boolean found=false;
for(final Object o : entry.parms())
{
if(host.getPort()==((Integer)o).intValue())
{
found=true;
break;
}
}
if(!found)
return false;
}
break;
case CLASS: // +class
{
final CharClass C=CMClass.getCharClass(E.charClass());
if(C!=null)
if(CMParms.contains(entry.parms(),C.name()))
return false;
break;
}
}
}
catch (final NullPointerException n)
{
}
}
return true;
}
@Override
public String[] separateMaskStrs(final String newText)
{
final String[] strs=new String[2];
final int maskindex=newText.toUpperCase().indexOf("MASK=");
if(maskindex>0)
{
strs[1]=newText.substring(maskindex+5).trim();
strs[0]=newText.substring(0,maskindex).trim();
}
else
{
strs[0]=newText;
strs[1]="";
}
return strs;
}
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.PrivilegedRole;
import com.microsoft.graph.models.extensions.PrivilegedRoleAssignment;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.http.IHttpRequest;
import com.microsoft.graph.models.extensions.PrivilegedRoleAssignment;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Privileged Role Assignment Collection Reference Request.
*/
public interface IPrivilegedRoleAssignmentCollectionReferenceRequest {
void post(final PrivilegedRoleAssignment newPrivilegedRoleAssignment, final ICallback<? super PrivilegedRoleAssignment> callback);
PrivilegedRoleAssignment post(final PrivilegedRoleAssignment newPrivilegedRoleAssignment) throws ClientException;
IPrivilegedRoleAssignmentCollectionReferenceRequest select(final String value);
IPrivilegedRoleAssignmentCollectionReferenceRequest top(final int value);
}
|
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.web;
import org.springframework.boot.actuate.endpoint.EndpointId;
/**
* Strategy interface used to provide a mapping between an endpoint ID and the root path
* where it will be exposed.
*
* @author Stephane Nicoll
* @author Phillip Webb
* @since 2.0.0
*/
@FunctionalInterface
public interface PathMapper {
/**
* Resolve the root path for the endpoint with the specified {@code endpointId}.
* @param endpointId the id of an endpoint
* @return the path of the endpoint
* @since 2.0.6
*/
default String getRootPath(EndpointId endpointId) {
return getRootPath((endpointId != null) ? endpointId.toString() : null);
}
/**
* Resolve the root path for the endpoint with the specified {@code endpointId}.
* @param endpointId the id of an endpoint
* @return the path of the endpoint
* @deprecated since 2.0.6 in favor of {@link #getRootPath(EndpointId)}
*/
@Deprecated
String getRootPath(String endpointId);
/**
* Returns an {@link PathMapper} that uses the endpoint ID as the path.
* @return an {@link PathMapper} that uses the lowercase endpoint ID as the path
*/
static PathMapper useEndpointId() {
return new PathMapper() {
@Override
@Deprecated
public String getRootPath(String endpointId) {
return getRootPath(EndpointId.of(endpointId));
}
@Override
public String getRootPath(EndpointId endpointId) {
return endpointId.toString();
}
};
}
}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.structuralsearch.plugin.ui;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.codeInsight.template.impl.TemplateEditorUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeTooltip;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.plugin.StructuralReplaceAction;
import com.intellij.structuralsearch.plugin.StructuralSearchAction;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.TooltipWithClickableLinks;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* @author Maxim.Mossienko
*/
public class UIUtil {
private static final String MODIFY_EDITOR_CONTENT = SSRBundle.message("modify.editor.content.command.name");
@NonNls private static final String SS_GROUP = "structuralsearchgroup";
public static final NotificationGroup SSR_NOTIFICATION_GROUP =
NotificationGroup.toolWindowGroup(SSRBundle.message("structural.search.title"), ToolWindowId.FIND);
@NonNls public static final String TEXT = "TEXT";
@NonNls public static final String TEXT_HIERARCHY = "TEXT HIERARCHY";
@NonNls public static final String REFERENCE = "REFERENCE";
@NonNls public static final String TYPE = "TYPE";
@NonNls public static final String EXPECTED_TYPE = "EXPECTED TYPE";
@NonNls public static final String MINIMUM_ZERO = "MINIMUM ZERO";
@NonNls public static final String MAXIMUM_UNLIMITED = "MAXIMUM UNLIMITED";
@NotNull
public static Editor createEditor(Document doc, final Project project, boolean editable, @Nullable TemplateContextType contextType) {
return createEditor(doc, project, editable, false, contextType);
}
@NotNull
public static Editor createEditor(@NotNull Document doc,
final Project project,
boolean editable,
boolean addToolTipForVariableHandler,
@Nullable TemplateContextType contextType) {
final Editor editor =
editable ? EditorFactory.getInstance().createEditor(doc, project) : EditorFactory.getInstance().createViewer(doc, project);
final EditorSettings editorSettings = editor.getSettings();
editorSettings.setVirtualSpace(false);
editorSettings.setLineMarkerAreaShown(false);
editorSettings.setIndentGuidesShown(false);
editorSettings.setLineNumbersShown(false);
editorSettings.setFoldingOutlineShown(false);
editorSettings.setCaretRowShown(false);
if (!editable) {
final EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme();
Color c = globalScheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR);
if (c == null) {
c = globalScheme.getDefaultBackground();
}
((EditorEx)editor).setBackgroundColor(c);
}
else {
((EditorEx)editor).setEmbeddedIntoDialogWrapper(true);
}
TemplateEditorUtil.setHighlighter(editor, contextType);
if (addToolTipForVariableHandler) {
SubstitutionShortInfoHandler.install(editor, null);
}
return editor;
}
public static JComponent createOptionLine(JComponent... options) {
JPanel tmp = new JPanel();
tmp.setLayout(new BoxLayout(tmp, BoxLayout.X_AXIS));
for (int i = 0; i < options.length; i++) {
if (i != 0) {
tmp.add(Box.createHorizontalStrut(com.intellij.util.ui.UIUtil.DEFAULT_HGAP));
}
tmp.add(options[i]);
}
tmp.add(Box.createHorizontalGlue());
return tmp;
}
public static void setContent(final Editor editor, String text) {
final String value = text != null ? text : "";
final Document document = editor.getDocument();
CommandProcessor.getInstance().executeCommand(
editor.getProject(),
() -> ApplicationManager.getApplication().runWriteAction(() -> document.replaceString(0, document.getTextLength(), value)),
MODIFY_EDITOR_CONTENT, SS_GROUP);
}
public static void setContent(final EditorTextField editor, String text) {
final String value = text != null ? text : "";
final Document document = editor.getDocument();
CommandProcessor.getInstance().executeCommand(
editor.getProject(),
() -> ApplicationManager.getApplication().runWriteAction(() -> document.replaceString(0, document.getTextLength(), value)),
MODIFY_EDITOR_CONTENT, SS_GROUP);
}
public static void invokeAction(Configuration config, SearchContext context) {
if (config instanceof SearchConfiguration) {
StructuralSearchAction.triggerAction(config, context);
}
else {
StructuralReplaceAction.triggerAction(config, context);
}
}
public static void updateHighlighter(Editor editor, StructuralSearchProfile profile) {
TemplateEditorUtil.setHighlighter(editor, profile.getTemplateContextType());
}
public static MatchVariableConstraint getOrAddVariableConstraint(String varName, Configuration configuration) {
MatchVariableConstraint varInfo = configuration.getMatchOptions().getVariableConstraint(varName);
if (varInfo == null) {
varInfo = new MatchVariableConstraint();
varInfo.setName(varName);
configuration.getMatchOptions().addVariableConstraint(varInfo);
}
return varInfo;
}
public static boolean isTarget(String varName, MatchOptions matchOptions) {
if (Configuration.CONTEXT_VAR_NAME.equals(varName)) {
// Complete Match is default target
for (String name : matchOptions.getVariableConstraintNames()) {
if (!name.equals(Configuration.CONTEXT_VAR_NAME)) {
if (matchOptions.getVariableConstraint(name).isPartOfSearchResults()) {
return false;
}
}
}
return true;
}
final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(varName);
if (constraint == null) {
return false;
}
return constraint.isPartOfSearchResults();
}
@NotNull
public static JComponent createCompleteMatchInfo(final Supplier<? extends Configuration> configurationProducer) {
return installCompleteMatchInfo(new JLabel(AllIcons.Actions.ListFiles), configurationProducer, null);
}
@NotNull
public static JComponent installCompleteMatchInfo(JLabel completeMatchInfo,
Supplier<? extends Configuration> configurationProducer,
Consumer<String> linkConsumer) {
completeMatchInfo.putClientProperty(IdeTooltip.TOOLTIP_DISMISS_DELAY_KEY, 20000);
completeMatchInfo.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent ignore) {
final Configuration configuration = configurationProducer.get();
if (configuration == null) {
return;
}
final MatchOptions matchOptions = configuration.getMatchOptions();
if (matchOptions.getSearchPattern().isEmpty()) {
return;
}
final MatchVariableConstraint constraint = getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, configuration);
if (isTarget(Configuration.CONTEXT_VAR_NAME, matchOptions)) {
constraint.setPartOfSearchResults(true);
}
final boolean link = linkConsumer != null && !Configuration.CONTEXT_VAR_NAME.equals(configuration.getCurrentVariableName());
final String text = SSRBundle.message("complete.match.variable.tooltip.message",
SubstitutionShortInfoHandler.getShortParamString(constraint, link));
final HyperlinkListener listener = e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && linkConsumer != null) {
linkConsumer.accept(Configuration.CONTEXT_VAR_NAME);
IdeTooltipManager.getInstance().hideCurrentNow(true);
}
};
final IdeTooltip tooltip = new TooltipWithClickableLinks(completeMatchInfo, text, listener);
final Rectangle bounds = completeMatchInfo.getBounds();
tooltip.setHint(true)
.setExplicitClose(true)
.setPreferredPosition(Balloon.Position.below)
.setPoint(new Point(bounds.x + (bounds.width / 2) , bounds.y + bounds.height));
IdeTooltipManager.getInstance().show(tooltip, true);
if (linkConsumer == null) {
configuration.setCurrentVariableName(Configuration.CONTEXT_VAR_NAME);
}
}
});
return completeMatchInfo;
}
public static EditorTextField createTextComponent(String text, Project project) {
return createEditorComponent(text, "1.txt", project);
}
public static EditorTextField createRegexComponent(String text, Project project) {
return createEditorComponent(text, "1.regexp", project);
}
public static EditorTextField createScriptComponent(String text, Project project) {
return createEditorComponent(text, "1.groovy", project);
}
@NotNull
public static EditorTextField createEditorComponent(String text, String fileName, Project project) {
return new EditorTextField(text, project, getFileType(fileName));
}
private static FileType getFileType(final String fileName) {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
if (fileType == FileTypes.UNKNOWN) fileType = FileTypes.PLAIN_TEXT;
return fileType;
}
public static FileType detectFileType(@NotNull SearchContext searchContext) {
final PsiFile file = searchContext.getFile();
PsiElement context = file;
final Editor editor = searchContext.getEditor();
if (editor != null && context != null) {
final int offset = editor.getCaretModel().getOffset();
context = InjectedLanguageManager.getInstance(searchContext.getProject()).findInjectedElementAt(file, offset);
if (context == null) {
context = file.findElementAt(offset);
}
if (context != null) {
context = context.getParent();
}
}
if (context != null) {
final Language language = context.getLanguage();
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language);
if (profile != null) {
final FileType fileType = profile.detectFileType(context);
return fileType != null ? fileType : language.getAssociatedFileType();
}
}
return StructuralSearchUtil.getDefaultFileType();
}
}
|
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.taskrouter.v1.workspace;
import com.twilio.base.Page;
import com.twilio.base.Reader;
import com.twilio.base.ResourceSet;
import com.twilio.converter.DateConverter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import java.time.ZonedDateTime;
public class EventReader extends Reader<Event> {
private final String pathWorkspaceSid;
private ZonedDateTime endDate;
private String eventType;
private Integer minutes;
private String reservationSid;
private ZonedDateTime startDate;
private String taskQueueSid;
private String taskSid;
private String workerSid;
private String workflowSid;
private String taskChannel;
private String sid;
/**
* Construct a new EventReader.
*
* @param pathWorkspaceSid The SID of the Workspace with the Events to read
*/
public EventReader(final String pathWorkspaceSid) {
this.pathWorkspaceSid = pathWorkspaceSid;
}
/**
* Only include Events that occurred on or before this date, specified in GMT as
* an <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> date-time..
*
* @param endDate Only include usage that occurred on or before this date
* @return this
*/
public EventReader setEndDate(final ZonedDateTime endDate) {
this.endDate = endDate;
return this;
}
/**
* The type of Events to read. Returns only Events of the type specified..
*
* @param eventType The type of Events to read
* @return this
*/
public EventReader setEventType(final String eventType) {
this.eventType = eventType;
return this;
}
/**
* The period of events to read in minutes. Returns only Events that occurred
* since this many minutes in the past. The default is `15` minutes. Task
* Attributes for Events occuring more 43,200 minutes ago will be redacted..
*
* @param minutes The period of events to read in minutes
* @return this
*/
public EventReader setMinutes(final Integer minutes) {
this.minutes = minutes;
return this;
}
/**
* The SID of the Reservation with the Events to read. Returns only Events that
* pertain to the specified Reservation..
*
* @param reservationSid The SID of the Reservation with the Events to read
* @return this
*/
public EventReader setReservationSid(final String reservationSid) {
this.reservationSid = reservationSid;
return this;
}
/**
* Only include Events from on or after this date and time, specified in <a
* href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format. Task
* Attributes for Events older than 30 days will be redacted..
*
* @param startDate Only include Events from on or after this date
* @return this
*/
public EventReader setStartDate(final ZonedDateTime startDate) {
this.startDate = startDate;
return this;
}
/**
* The SID of the TaskQueue with the Events to read. Returns only the Events
* that pertain to the specified TaskQueue..
*
* @param taskQueueSid The SID of the TaskQueue with the Events to read
* @return this
*/
public EventReader setTaskQueueSid(final String taskQueueSid) {
this.taskQueueSid = taskQueueSid;
return this;
}
/**
* The SID of the Task with the Events to read. Returns only the Events that
* pertain to the specified Task..
*
* @param taskSid The SID of the Task with the Events to read
* @return this
*/
public EventReader setTaskSid(final String taskSid) {
this.taskSid = taskSid;
return this;
}
/**
* The SID of the Worker with the Events to read. Returns only the Events that
* pertain to the specified Worker..
*
* @param workerSid The SID of the Worker with the Events to read
* @return this
*/
public EventReader setWorkerSid(final String workerSid) {
this.workerSid = workerSid;
return this;
}
/**
* The SID of the Workflow with the Events to read. Returns only the Events that
* pertain to the specified Workflow..
*
* @param workflowSid The SID of the Worker with the Events to read
* @return this
*/
public EventReader setWorkflowSid(final String workflowSid) {
this.workflowSid = workflowSid;
return this;
}
/**
* The TaskChannel with the Events to read. Returns only the Events that pertain
* to the specified TaskChannel..
*
* @param taskChannel The TaskChannel with the Events to read
* @return this
*/
public EventReader setTaskChannel(final String taskChannel) {
this.taskChannel = taskChannel;
return this;
}
/**
* The SID of the Event resource to read..
*
* @param sid The unique string that identifies the resource
* @return this
*/
public EventReader setSid(final String sid) {
this.sid = sid;
return this;
}
/**
* Make the request to the Twilio API to perform the read.
*
* @param client TwilioRestClient with which to make the request
* @return Event ResourceSet
*/
@Override
public ResourceSet<Event> read(final TwilioRestClient client) {
return new ResourceSet<>(this, client, firstPage(client));
}
/**
* Make the request to the Twilio API to perform the read.
*
* @param client TwilioRestClient with which to make the request
* @return Event ResourceSet
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public Page<Event> firstPage(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.TASKROUTER.toString(),
"/v1/Workspaces/" + this.pathWorkspaceSid + "/Events"
);
addQueryParams(request);
return pageForRequest(client, request);
}
/**
* Retrieve the target page from the Twilio API.
*
* @param targetUrl API-generated URL for the requested results page
* @param client TwilioRestClient with which to make the request
* @return Event ResourceSet
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public Page<Event> getPage(final String targetUrl, final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
targetUrl
);
return pageForRequest(client, request);
}
/**
* Retrieve the next page from the Twilio API.
*
* @param page current page
* @param client TwilioRestClient with which to make the request
* @return Next Page
*/
@Override
public Page<Event> nextPage(final Page<Event> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(Domains.TASKROUTER.toString())
);
return pageForRequest(client, request);
}
/**
* Retrieve the previous page from the Twilio API.
*
* @param page current page
* @param client TwilioRestClient with which to make the request
* @return Previous Page
*/
@Override
public Page<Event> previousPage(final Page<Event> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(Domains.TASKROUTER.toString())
);
return pageForRequest(client, request);
}
/**
* Generate a Page of Event Resources for a given request.
*
* @param client TwilioRestClient with which to make the request
* @param request Request to generate a page for
* @return Page for the Request
*/
private Page<Event> pageForRequest(final TwilioRestClient client, final Request request) {
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("Event read failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(restException);
}
return Page.fromJson(
"events",
response.getContent(),
Event.class,
client.getObjectMapper()
);
}
/**
* Add the requested query string arguments to the Request.
*
* @param request Request to add query string arguments to
*/
private void addQueryParams(final Request request) {
if (endDate != null) {
request.addQueryParam("EndDate", endDate.toOffsetDateTime().toString());
}
if (eventType != null) {
request.addQueryParam("EventType", eventType);
}
if (minutes != null) {
request.addQueryParam("Minutes", minutes.toString());
}
if (reservationSid != null) {
request.addQueryParam("ReservationSid", reservationSid);
}
if (startDate != null) {
request.addQueryParam("StartDate", startDate.toOffsetDateTime().toString());
}
if (taskQueueSid != null) {
request.addQueryParam("TaskQueueSid", taskQueueSid);
}
if (taskSid != null) {
request.addQueryParam("TaskSid", taskSid);
}
if (workerSid != null) {
request.addQueryParam("WorkerSid", workerSid);
}
if (workflowSid != null) {
request.addQueryParam("WorkflowSid", workflowSid);
}
if (taskChannel != null) {
request.addQueryParam("TaskChannel", taskChannel);
}
if (sid != null) {
request.addQueryParam("Sid", sid);
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize()));
}
}
}
|
package org.apache.http.client.methods;
import java.net.URI;
@Deprecated
public class HttpPost
extends HttpEntityEnclosingRequestBase
{
public static final String METHOD_NAME = "POST";
public HttpPost()
{
throw new RuntimeException("Stub!");
}
public HttpPost(String paramString)
{
throw new RuntimeException("Stub!");
}
public HttpPost(URI paramURI)
{
throw new RuntimeException("Stub!");
}
public String getMethod()
{
throw new RuntimeException("Stub!");
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/org/apache/http/client/methods/HttpPost.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE129_Improper_Validation_of_Array_Index__File_array_read_check_min_66b.java
Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml
Template File: sources-sinks-66b.tmpl.java
*/
/*
* @description
* CWE: 129 Improper Validation of Array Index
* BadSource: File Read data from file (named c:\data.txt)
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: array_read_check_min
* GoodSink: Read from array after verifying that data is at least 0 and less than array.length
* BadSink : Read from array after verifying that data is at least 0 (but not verifying that data less than array.length)
* Flow Variant: 66 Data flow: data passed in an array from one method to another in different source files in the same package
*
* */
package testcases.CWE129_Improper_Validation_of_Array_Index.s02;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE129_Improper_Validation_of_Array_Index__File_array_read_check_min_66b
{
public void badSink(int dataArray[] ) throws Throwable
{
int data = dataArray[2];
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* POTENTIAL FLAW: Verify that data >= 0, but don't verify that data < array.length, so may be attempting to read out of the array bounds */
if (data >= 0)
{
IO.writeLine(array[data]);
}
else
{
IO.writeLine("Array index out of bounds");
}
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(int dataArray[] ) throws Throwable
{
int data = dataArray[2];
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* POTENTIAL FLAW: Verify that data >= 0, but don't verify that data < array.length, so may be attempting to read out of the array bounds */
if (data >= 0)
{
IO.writeLine(array[data]);
}
else
{
IO.writeLine("Array index out of bounds");
}
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink(int dataArray[] ) throws Throwable
{
int data = dataArray[2];
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* FIX: Fully verify data before reading from array at location data */
if (data >= 0 && data < array.length)
{
IO.writeLine(array[data]);
}
else
{
IO.writeLine("Array index out of bounds");
}
}
}
|
/***
* Copyright (c) 1995-2009 Cycorp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Substantial portions of this code were developed by the Cyc project
* and by Cycorp Inc, whose contribution is gratefully acknowledged.
*/
package com.cyc.cycjava_1.cycl.sbhl;
import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.*;
import static com.cyc.tool.subl.util.SubLFiles.*;
import com.cyc.cycjava.cycl.*;
import com.cyc.tool.subl.jrtl.nativeCode.subLisp.*;
import com.cyc.tool.subl.jrtl.nativeCode.type.core.*;
import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.*;
import com.cyc.tool.subl.util.*;
//dm import com.cyc.cycjava_1.cycl.access_macros;
//dm import com.cyc.cycjava_1.cycl.constant_handles;
//dm import com.cyc.cycjava_1.cycl.mt_relevance_macros;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_link_vars;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_macros;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_marking_utilities;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_marking_vars;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_module_utilities;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_module_vars;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_paranoia;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_search_utilities;
//dm import com.cyc.cycjava_1.cycl.sbhl.sbhl_search_vars;
public final class sbhl_marking_methods extends SubLTranslatedFile {
//// Constructor
private sbhl_marking_methods() {}
public static final SubLFile me = new sbhl_marking_methods();
public static final String myName = "com.cyc.cycjava_1.cycl.sbhl.sbhl_marking_methods";
//// Definitions
/** @Hack assumes sbhl modules are cheaper to search forward */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 1489)
public static final SubLObject sbhl_premark_direction(SubLObject module) {
return sbhl_search_vars.get_sbhl_forward_search_direction();
}
/** Used for initial marking for boolean disjoins searches. Applies @see sbhl-sweep, upon NODE, with current *sbhl-module*, forward direction, true search tv, in @see *sbhl-gather-space*, with map-fn sbhl-check-cutoff. */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 1664)
public static final SubLObject sbhl_premark_gather_nodes(SubLObject node) {
{
final SubLThread thread = SubLProcess.currentSubLThread();
sbhl_search_utilities.sbhl_sweep(sbhl_module_vars.get_sbhl_module(UNPROVIDED), sbhl_module_utilities.sbhl_search_direction_to_link_direction(sbhl_premark_direction(sbhl_module_vars.get_sbhl_module(UNPROVIDED)), sbhl_module_vars.get_sbhl_module(UNPROVIDED)), sbhl_search_vars.sbhl_search_true_tv(), sbhl_marking_vars.$sbhl_gather_space$.getDynamicValue(thread), $sym0$SBHL_CHECK_CUTOFF, node, sbhl_search_vars.sbhl_unmarking_search_p());
return NIL;
}
}
/** Modifier. Marks the forward true closure of NODE in MODULE with relevance determined by MT and TV. performs this marking in current *sbhl-space* and possibly *sbhl-gather-space*, depending on the search behavior that it binds (as determined by @see determine-sbhl-search-behavior). */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 3151)
public static final SubLObject sbhl_mark_all_forward_true_nodes(SubLObject module, SubLObject node, SubLObject mt, SubLObject tv) {
if ((mt == UNPROVIDED)) {
mt = NIL;
}
if ((tv == UNPROVIDED)) {
tv = NIL;
}
{
final SubLThread thread = SubLProcess.currentSubLThread();
checkType(module, $sym5$SBHL_MODULE_P);
{
SubLObject _prev_bind_0 = sbhl_search_vars.$sbhl_search_module$.currentBinding(thread);
SubLObject _prev_bind_1 = sbhl_search_vars.$sbhl_search_module_type$.currentBinding(thread);
SubLObject _prev_bind_2 = sbhl_search_vars.$sbhl_add_node_to_result_test$.currentBinding(thread);
SubLObject _prev_bind_3 = sbhl_search_vars.$genl_inverse_mode_p$.currentBinding(thread);
SubLObject _prev_bind_4 = sbhl_module_vars.$sbhl_module$.currentBinding(thread);
SubLObject _prev_bind_5 = sbhl_marking_vars.$sbhl_suspend_new_spacesP$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_search_module$.bind(module, thread);
sbhl_search_vars.$sbhl_search_module_type$.bind(sbhl_module_utilities.get_sbhl_module_type(module), thread);
sbhl_search_vars.$sbhl_add_node_to_result_test$.bind(sbhl_module_utilities.get_sbhl_add_node_to_result_test(module), thread);
sbhl_search_vars.$genl_inverse_mode_p$.bind(NIL, thread);
sbhl_module_vars.$sbhl_module$.bind(module, thread);
sbhl_marking_vars.$sbhl_suspend_new_spacesP$.bind(T, thread);
{
SubLObject mt_var = mt;
{
SubLObject _prev_bind_0_2 = mt_relevance_macros.$mt$.currentBinding(thread);
SubLObject _prev_bind_1_3 = mt_relevance_macros.$relevant_mt_function$.currentBinding(thread);
SubLObject _prev_bind_2_4 = mt_relevance_macros.$relevant_mts$.currentBinding(thread);
try {
mt_relevance_macros.$mt$.bind(mt_relevance_macros.update_inference_mt_relevance_mt(mt_var), thread);
mt_relevance_macros.$relevant_mt_function$.bind(mt_relevance_macros.update_inference_mt_relevance_function(mt_var), thread);
mt_relevance_macros.$relevant_mts$.bind(mt_relevance_macros.update_inference_mt_relevance_mt_list(mt_var), thread);
{
SubLObject tv_var = tv;
{
SubLObject _prev_bind_0_5 = sbhl_search_vars.$sbhl_tv$.currentBinding(thread);
SubLObject _prev_bind_1_6 = sbhl_search_vars.$relevant_sbhl_tv_function$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_tv$.bind(((NIL != tv_var) ? ((SubLObject) tv_var) : sbhl_search_vars.get_sbhl_true_tv()), thread);
sbhl_search_vars.$relevant_sbhl_tv_function$.bind(((NIL != tv_var) ? ((SubLObject) $sym6$RELEVANT_SBHL_TV_IS_GENERAL_TV) : sbhl_search_vars.$relevant_sbhl_tv_function$.getDynamicValue(thread)), thread);
if ((NIL != tv_var)) {
if ((NIL != sbhl_paranoia.sbhl_object_type_checking_p())) {
if ((NIL == sbhl_search_vars.sbhl_true_tv_p(tv_var))) {
{
SubLObject pcase_var = sbhl_paranoia.$sbhl_type_error_action$.getDynamicValue(thread);
if (pcase_var.eql($kw7$ERROR)) {
sbhl_paranoia.sbhl_error(ONE_INTEGER, $str8$_A_is_not_a__A, tv_var, $sym9$SBHL_TRUE_TV_P, UNPROVIDED, UNPROVIDED, UNPROVIDED);
} else if (pcase_var.eql($kw10$CERROR)) {
Errors
.handleMissingMethodError("This call was replaced for LarKC purposes. Originally a method was called. Refer to number 2196");
} else if (pcase_var.eql($kw12$WARN)) {
Errors.warn($str8$_A_is_not_a__A, tv_var, $sym9$SBHL_TRUE_TV_P);
} else {
Errors.warn($str13$_A_is_not_a_valid__sbhl_type_erro, sbhl_paranoia.$sbhl_type_error_action$.getDynamicValue(thread));
Errors.cerror($str11$continue_anyway, $str8$_A_is_not_a__A, tv_var, $sym9$SBHL_TRUE_TV_P);
}
}
}
}
}
{
SubLObject _prev_bind_0_7 = sbhl_search_vars.$sbhl_search_truth$.currentBinding(thread);
SubLObject _prev_bind_1_8 = sbhl_search_vars.$sbhl_search_direction$.currentBinding(thread);
SubLObject _prev_bind_2_9 = sbhl_link_vars.$sbhl_link_direction$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_search_truth$.bind($const14$True_JustificationTruth, thread);
sbhl_search_vars.$sbhl_search_direction$.bind(sbhl_search_vars.get_sbhl_forward_search_direction(), thread);
sbhl_link_vars.$sbhl_link_direction$.bind(sbhl_module_utilities.get_sbhl_module_forward_direction(sbhl_module_vars.get_sbhl_module(UNPROVIDED)), thread);
{
SubLObject source = sbhl_marking_vars.sbhl_new_space_source();
{
SubLObject _prev_bind_0_10 = sbhl_marking_vars.$sbhl_space$.currentBinding(thread);
try {
sbhl_marking_vars.$sbhl_space$.bind(((source == $kw15$OLD) ? ((SubLObject) sbhl_marking_vars.$sbhl_space$.getDynamicValue(thread)) : sbhl_marking_vars.sbhl_get_new_space(source)), thread);
{
SubLObject _prev_bind_0_11 = sbhl_marking_vars.$sbhl_gather_space$.currentBinding(thread);
try {
sbhl_marking_vars.$sbhl_gather_space$.bind(((source == $kw15$OLD) ? ((SubLObject) sbhl_marking_vars.$sbhl_gather_space$.getDynamicValue(thread)) : sbhl_marking_vars.sbhl_get_new_space(source)), thread);
{
SubLObject _prev_bind_0_12 = sbhl_search_vars.$sbhl_finishedP$.currentBinding(thread);
SubLObject _prev_bind_1_13 = sbhl_search_vars.$sbhl_stop_search_pathP$.currentBinding(thread);
SubLObject _prev_bind_2_14 = sbhl_search_vars.$sbhl_search_parent_marking$.currentBinding(thread);
SubLObject _prev_bind_3_15 = sbhl_search_vars.$sbhl_nodes_previous_marking$.currentBinding(thread);
SubLObject _prev_bind_4_16 = sbhl_search_vars.$genl_inverse_mode_p$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_finishedP$.bind(NIL, thread);
sbhl_search_vars.$sbhl_stop_search_pathP$.bind(NIL, thread);
sbhl_search_vars.$sbhl_search_parent_marking$.bind(NIL, thread);
sbhl_search_vars.$sbhl_nodes_previous_marking$.bind(NIL, thread);
sbhl_search_vars.$genl_inverse_mode_p$.bind(NIL, thread);
{
SubLObject rw_lock_var = sbhl_link_vars.$sbhl_rw_lock$.getGlobalValue();
SubLObject needs_to_releaseP = NIL;
try {
needs_to_releaseP = ReadWriteLocks.rw_lock_seize_read_lock(rw_lock_var);
{
SubLObject _prev_bind_0_17 = sbhl_search_vars.$sbhl_search_behavior$.currentBinding(thread);
SubLObject _prev_bind_1_18 = sbhl_marking_vars.$sbhl_terminating_marking_space$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_search_behavior$.bind(sbhl_search_utilities.determine_sbhl_search_behavior(sbhl_search_vars.get_sbhl_search_module(), sbhl_search_vars.get_sbhl_search_direction(), sbhl_search_vars.get_sbhl_tv()), thread);
sbhl_marking_vars.$sbhl_terminating_marking_space$.bind(sbhl_search_utilities.determine_sbhl_terminating_marking_space(sbhl_search_vars.$sbhl_search_behavior$.getDynamicValue(thread)), thread);
sbhl_mark_closure_as_marked(node);
} finally {
sbhl_marking_vars.$sbhl_terminating_marking_space$.rebind(_prev_bind_1_18, thread);
sbhl_search_vars.$sbhl_search_behavior$.rebind(_prev_bind_0_17, thread);
}
}
} finally {
if ((NIL != needs_to_releaseP)) {
ReadWriteLocks.rw_lock_release_read_lock(rw_lock_var);
}
}
}
} finally {
sbhl_search_vars.$genl_inverse_mode_p$.rebind(_prev_bind_4_16, thread);
sbhl_search_vars.$sbhl_nodes_previous_marking$.rebind(_prev_bind_3_15, thread);
sbhl_search_vars.$sbhl_search_parent_marking$.rebind(_prev_bind_2_14, thread);
sbhl_search_vars.$sbhl_stop_search_pathP$.rebind(_prev_bind_1_13, thread);
sbhl_search_vars.$sbhl_finishedP$.rebind(_prev_bind_0_12, thread);
}
}
if ((source == $kw16$RESOURCE)) {
sbhl_marking_vars.update_sbhl_resourced_spaces(sbhl_marking_vars.$sbhl_gather_space$.getDynamicValue(thread));
}
} finally {
sbhl_marking_vars.$sbhl_gather_space$.rebind(_prev_bind_0_11, thread);
}
}
if ((source == $kw16$RESOURCE)) {
sbhl_marking_vars.update_sbhl_resourced_spaces(sbhl_marking_vars.$sbhl_space$.getDynamicValue(thread));
}
} finally {
sbhl_marking_vars.$sbhl_space$.rebind(_prev_bind_0_10, thread);
}
}
}
} finally {
sbhl_link_vars.$sbhl_link_direction$.rebind(_prev_bind_2_9, thread);
sbhl_search_vars.$sbhl_search_direction$.rebind(_prev_bind_1_8, thread);
sbhl_search_vars.$sbhl_search_truth$.rebind(_prev_bind_0_7, thread);
}
}
} finally {
sbhl_search_vars.$relevant_sbhl_tv_function$.rebind(_prev_bind_1_6, thread);
sbhl_search_vars.$sbhl_tv$.rebind(_prev_bind_0_5, thread);
}
}
}
} finally {
mt_relevance_macros.$relevant_mts$.rebind(_prev_bind_2_4, thread);
mt_relevance_macros.$relevant_mt_function$.rebind(_prev_bind_1_3, thread);
mt_relevance_macros.$mt$.rebind(_prev_bind_0_2, thread);
}
}
}
} finally {
sbhl_marking_vars.$sbhl_suspend_new_spacesP$.rebind(_prev_bind_5, thread);
sbhl_module_vars.$sbhl_module$.rebind(_prev_bind_4, thread);
sbhl_search_vars.$genl_inverse_mode_p$.rebind(_prev_bind_3, thread);
sbhl_search_vars.$sbhl_add_node_to_result_test$.rebind(_prev_bind_2, thread);
sbhl_search_vars.$sbhl_search_module_type$.rebind(_prev_bind_1, thread);
sbhl_search_vars.$sbhl_search_module$.rebind(_prev_bind_0, thread);
}
}
return NIL;
}
}
/** Modifier: marks all nodes accessible to NODE as marked, in the current search space. */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 4461)
public static final SubLObject sbhl_mark_closure_as_marked(SubLObject node) {
{
final SubLThread thread = SubLProcess.currentSubLThread();
if (((NIL != sbhl_paranoia.suspend_sbhl_type_checkingP())
|| (NIL != sbhl_module_utilities.apply_sbhl_module_type_test(node, sbhl_module_vars.get_sbhl_module(UNPROVIDED))))) {
{
SubLObject _prev_bind_0 = sbhl_search_vars.$sbhl_consider_node_fn$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_consider_node_fn$.bind($sym0$SBHL_CHECK_CUTOFF, thread);
sbhl_search_utilities.apply_sbhl_search_behavior(sbhl_search_vars.get_sbhl_search_behavior(), node);
} finally {
sbhl_search_vars.$sbhl_consider_node_fn$.rebind(_prev_bind_0, thread);
}
}
} else {
sbhl_paranoia.sbhl_warn(TWO_INTEGER, $str17$Node__a_does_not_pass_sbhl_type_t, node, sbhl_module_utilities.get_sbhl_type_test(sbhl_module_vars.get_sbhl_module(UNPROVIDED)), UNPROVIDED, UNPROVIDED, UNPROVIDED);
}
return NIL;
}
}
public static final class $sbhl_mark_closure_as_marked$UnaryFunction extends UnaryFunction {
public $sbhl_mark_closure_as_marked$UnaryFunction() { super(extractFunctionNamed("SBHL-MARK-CLOSURE-AS-MARKED")); }
public SubLObject processItem(SubLObject arg1) { return sbhl_mark_closure_as_marked(arg1); }
}
/** Modifier: Binds *sbhl-space* to SPACE and *sbhl-gather-space* to GATHER-SPACE and performs @see sbhl-mark-all-forward-true-nodes. */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 4905)
public static final SubLObject sbhl_mark_forward_true_nodes_in_space(SubLObject module, SubLObject node, SubLObject space, SubLObject gather_space) {
if ((space == UNPROVIDED)) {
space = sbhl_marking_vars.$sbhl_space$.getDynamicValue();
}
if ((gather_space == UNPROVIDED)) {
gather_space = sbhl_marking_vars.$sbhl_gather_space$.getDynamicValue();
}
{
final SubLThread thread = SubLProcess.currentSubLThread();
checkType(module, $sym5$SBHL_MODULE_P);
{
SubLObject _prev_bind_0 = sbhl_marking_vars.$sbhl_space$.currentBinding(thread);
SubLObject _prev_bind_1 = sbhl_marking_vars.$sbhl_gather_space$.currentBinding(thread);
SubLObject _prev_bind_2 = sbhl_marking_vars.$sbhl_suspend_new_spacesP$.currentBinding(thread);
try {
sbhl_marking_vars.$sbhl_space$.bind(space, thread);
sbhl_marking_vars.$sbhl_gather_space$.bind(gather_space, thread);
sbhl_marking_vars.$sbhl_suspend_new_spacesP$.bind(T, thread);
sbhl_mark_all_forward_true_nodes(module, node, UNPROVIDED, UNPROVIDED);
} finally {
sbhl_marking_vars.$sbhl_suspend_new_spacesP$.rebind(_prev_bind_2, thread);
sbhl_marking_vars.$sbhl_gather_space$.rebind(_prev_bind_1, thread);
sbhl_marking_vars.$sbhl_space$.rebind(_prev_bind_0, thread);
}
}
return NIL;
}
}
/** Modifier: marks all nodes properly accessible to NODE as marked, thereby only marking NODE if it is part of a cycle. */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 6447)
public static final SubLObject sbhl_mark_proper_closure_as_marked(SubLObject node) {
{
final SubLThread thread = SubLProcess.currentSubLThread();
if ((NIL != sbhl_module_utilities.sbhl_transitive_module_p(sbhl_search_vars.get_sbhl_search_module()))) {
sbhl_search_utilities.sbhl_step(sbhl_search_vars.get_sbhl_search_module(), sbhl_link_vars.get_sbhl_link_direction(), sbhl_search_vars.get_sbhl_tv(), sbhl_marking_vars.$sbhl_space$.getDynamicValue(thread), $sym19$SBHL_MARK_CLOSURE_AS_MARKED, node, T, UNPROVIDED);
} else {
sbhl_mark_closure_as_marked(node);
}
return NIL;
}
}
/** Modifier: unmarks all marked nodes accessible to NODE and pushes them onto the result if they pass the test FUNCTION. */
@SubL(source = "cycl/sbhl/sbhl-marking-methods.lisp", position = 10443)
public static final SubLObject sbhl_unmark_marked_closure_and_gather_if(SubLObject node, SubLObject function) {
{
final SubLThread thread = SubLProcess.currentSubLThread();
{
SubLObject _prev_bind_0 = sbhl_search_vars.$sbhl_unmarking_search_p$.currentBinding(thread);
SubLObject _prev_bind_1 = sbhl_search_vars.$sbhl_compose_fn$.currentBinding(thread);
SubLObject _prev_bind_2 = sbhl_search_vars.$sbhl_consider_node_fn$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_unmarking_search_p$.bind(T, thread);
sbhl_search_vars.$sbhl_compose_fn$.bind(function, thread);
sbhl_search_vars.$sbhl_consider_node_fn$.bind($sym23$SBHL_PUSH_ONTO_RESULT_IF, thread);
if ((NIL != sbhl_module_utilities.sbhl_module_indicates_predicate_search_p(sbhl_search_vars.get_sbhl_search_module()))) {
{
SubLObject cdolist_list_var = sbhl_marking_utilities.sbhl_marked_with(node, UNPROVIDED);
SubLObject pred = NIL;
for (pred = cdolist_list_var.first(); (NIL != cdolist_list_var); cdolist_list_var = cdolist_list_var.rest(), pred = cdolist_list_var.first()) {
{
SubLObject _prev_bind_0_105 = sbhl_search_vars.$sbhl_add_unmarked_node_to_result_test$.currentBinding(thread);
SubLObject _prev_bind_1_106 = sbhl_search_vars.$genl_inverse_mode_p$.currentBinding(thread);
try {
sbhl_search_vars.$sbhl_add_unmarked_node_to_result_test$.bind(sbhl_module_utilities.get_sbhl_add_node_to_result_test(sbhl_module_vars.get_sbhl_module(pred)), thread);
sbhl_search_vars.$genl_inverse_mode_p$.bind(Equality.eq(pred, $const1$genlInverse), thread);
sbhl_search_utilities.apply_sbhl_search_behavior(sbhl_search_vars.get_sbhl_search_behavior(), node);
} finally {
sbhl_search_vars.$genl_inverse_mode_p$.rebind(_prev_bind_1_106, thread);
sbhl_search_vars.$sbhl_add_unmarked_node_to_result_test$.rebind(_prev_bind_0_105, thread);
}
}
}
}
} else {
sbhl_search_utilities.apply_sbhl_search_behavior(sbhl_search_vars.get_sbhl_search_behavior(), node);
}
} finally {
sbhl_search_vars.$sbhl_consider_node_fn$.rebind(_prev_bind_2, thread);
sbhl_search_vars.$sbhl_compose_fn$.rebind(_prev_bind_1, thread);
sbhl_search_vars.$sbhl_unmarking_search_p$.rebind(_prev_bind_0, thread);
}
}
return NIL;
}
}
public static final SubLObject declare_sbhl_marking_methods_file() {
//declareFunction("sbhl_premark_goal_nodes", "SBHL-PREMARK-GOAL-NODES", 1, 0, false);
declareFunction("sbhl_premark_direction", "SBHL-PREMARK-DIRECTION", 1, 0, false);
declareFunction("sbhl_premark_gather_nodes", "SBHL-PREMARK-GATHER-NODES", 1, 0, false);
//declareFunction("sbhl_gather_premarked_justifications", "SBHL-GATHER-PREMARKED-JUSTIFICATIONS", 1, 0, false);
declareFunction("sbhl_mark_all_forward_true_nodes", "SBHL-MARK-ALL-FORWARD-TRUE-NODES", 2, 2, false);
//declareFunction("sbhl_mark_all_backward_true_nodes", "SBHL-MARK-ALL-BACKWARD-TRUE-NODES", 2, 2, false);
declareFunction("sbhl_mark_closure_as_marked", "SBHL-MARK-CLOSURE-AS-MARKED", 1, 0, false); new $sbhl_mark_closure_as_marked$UnaryFunction();
//declareFunction("sbhl_mark_closure_in_space", "SBHL-MARK-CLOSURE-IN-SPACE", 2, 0, false);
declareFunction("sbhl_mark_forward_true_nodes_in_space", "SBHL-MARK-FORWARD-TRUE-NODES-IN-SPACE", 2, 2, false);
//declareFunction("sbhl_mark_backward_true_nodes_in_space", "SBHL-MARK-BACKWARD-TRUE-NODES-IN-SPACE", 2, 2, false);
//declareFunction("sbhl_mark_proper_all_forward_true_nodes", "SBHL-MARK-PROPER-ALL-FORWARD-TRUE-NODES", 2, 2, false);
declareFunction("sbhl_mark_proper_closure_as_marked", "SBHL-MARK-PROPER-CLOSURE-AS-MARKED", 1, 0, false);
//declareFunction("sbhl_unmark_all_marked_forward_true_nodes", "SBHL-UNMARK-ALL-MARKED-FORWARD-TRUE-NODES", 2, 2, false);
//declareFunction("sbhl_unmark_all_marked_backward_true_nodes", "SBHL-UNMARK-ALL-MARKED-BACKWARD-TRUE-NODES", 2, 2, false);
//declareFunction("sbhl_unmark_marked_closure", "SBHL-UNMARK-MARKED-CLOSURE", 1, 0, false);
//declareFunction("sbhl_unmark_initialized_marked_closure", "SBHL-UNMARK-INITIALIZED-MARKED-CLOSURE", 1, 0, false);
//declareFunction("sbhl_unmark_proper_marked_closure", "SBHL-UNMARK-PROPER-MARKED-CLOSURE", 1, 0, false);
//declareFunction("sbhl_unmark_all_backward_true_nodes_and_map", "SBHL-UNMARK-ALL-BACKWARD-TRUE-NODES-AND-MAP", 2, 0, false);
//declareFunction("sbhl_unmark_marked_closure_and_gather", "SBHL-UNMARK-MARKED-CLOSURE-AND-GATHER", 1, 0, false);
declareFunction("sbhl_unmark_marked_closure_and_gather_if", "SBHL-UNMARK-MARKED-CLOSURE-AND-GATHER-IF", 2, 0, false);
//declareFunction("sbhl_unmark_marked_closure_and_mark_in_space", "SBHL-UNMARK-MARKED-CLOSURE-AND-MARK-IN-SPACE", 2, 0, false);
//declareFunction("sbhl_unmark_marked_closure_and_unmark_in_space", "SBHL-UNMARK-MARKED-CLOSURE-AND-UNMARK-IN-SPACE", 2, 0, false);
//declareFunction("sbhl_mark_cyclic_closure", "SBHL-MARK-CYCLIC-CLOSURE", 1, 0, false);
//declareFunction("sbhl_unmark_cyclic_closure", "SBHL-UNMARK-CYCLIC-CLOSURE", 1, 0, false);
//declareFunction("sbhl_mark_max_true_disjoins", "SBHL-MARK-MAX-TRUE-DISJOINS", 2, 2, false);
//declareFunction("sbhl_mark_extremal_disjoins", "SBHL-MARK-EXTREMAL-DISJOINS", 1, 0, false);
//declareFunction("sbhl_unmark_max_true_disjoins", "SBHL-UNMARK-MAX-TRUE-DISJOINS", 2, 2, false);
//declareFunction("sbhl_unmark_extremal_disjoins", "SBHL-UNMARK-EXTREMAL-DISJOINS", 1, 0, false);
//declareFunction("determine_sbhl_mark_between_consider_fn", "DETERMINE-SBHL-MARK-BETWEEN-CONSIDER-FN", 0, 0, false);
//declareFunction("sbhl_mark_forward_true_nodes_between_and_all_their_inherited_nodes", "SBHL-MARK-FORWARD-TRUE-NODES-BETWEEN-AND-ALL-THEIR-INHERITED-NODES", 3, 2, false);
//declareFunction("sbhl_unmark_marked_closure_and_target_mark_closure", "SBHL-UNMARK-MARKED-CLOSURE-AND-TARGET-MARK-CLOSURE", 1, 0, false);
//declareFunction("sbhl_mark_closure_in_target_space", "SBHL-MARK-CLOSURE-IN-TARGET-SPACE", 1, 0, false);
//declareFunction("sbhl_mark_node_and_instances_in_target_space", "SBHL-MARK-NODE-AND-INSTANCES-IN-TARGET-SPACE", 1, 0, false);
//declareFunction("sbhl_record_closure", "SBHL-RECORD-CLOSURE", 3, 2, false);
//declareFunction("sbhl_record_all_forward_true_nodes", "SBHL-RECORD-ALL-FORWARD-TRUE-NODES", 2, 2, false);
//declareFunction("sbhl_record_all_backward_true_nodes", "SBHL-RECORD-ALL-BACKWARD-TRUE-NODES", 2, 2, false);
//declareFunction("sbhl_record_max_true_disjoins", "SBHL-RECORD-MAX-TRUE-DISJOINS", 2, 2, false);
//declareFunction("sbhl_unrecord_max_true_disjoins", "SBHL-UNRECORD-MAX-TRUE-DISJOINS", 2, 2, false);
//declareFunction("sbhl_unrecord_all_recorded_forward_true_nodes", "SBHL-UNRECORD-ALL-RECORDED-FORWARD-TRUE-NODES", 2, 2, false);
//declareFunction("unrecord_all_superiors_as_unsearched_ignore_arg2", "UNRECORD-ALL-SUPERIORS-AS-UNSEARCHED-IGNORE-ARG2", 1, 1, false);
//declareFunction("sbhl_record_node", "SBHL-RECORD-NODE", 1, 1, false);
//declareFunction("sbhl_recorded_node_p", "SBHL-RECORDED-NODE-P", 1, 1, false);
//declareFunction("sbhl_unrecorded_node_p", "SBHL-UNRECORDED-NODE-P", 1, 1, false);
//declareFunction("sbhl_record_proper_all_forward_true_nodes", "SBHL-RECORD-PROPER-ALL-FORWARD-TRUE-NODES", 2, 2, false);
return NIL;
}
public static final SubLObject init_sbhl_marking_methods_file() {
return NIL;
}
public static final SubLObject setup_sbhl_marking_methods_file() {
return NIL;
}
//// Internal Constants
public static final SubLSymbol $sym0$SBHL_CHECK_CUTOFF = makeSymbol("SBHL-CHECK-CUTOFF");
public static final SubLObject $const1$genlInverse = constant_handles.reader_make_constant_shell(makeString("genlInverse"));
public static final SubLSymbol $sym2$SBHL_NODE_IS_A_GOAL_NODE = makeSymbol("SBHL-NODE-IS-A-GOAL-NODE");
public static final SubLSymbol $sym3$SBHL_NODE_IS_GOAL_NODE = makeSymbol("SBHL-NODE-IS-GOAL-NODE");
public static final SubLSymbol $sym4$SBHL_CONSIDER_NODE = makeSymbol("SBHL-CONSIDER-NODE");
public static final SubLSymbol $sym5$SBHL_MODULE_P = makeSymbol("SBHL-MODULE-P");
public static final SubLSymbol $sym6$RELEVANT_SBHL_TV_IS_GENERAL_TV = makeSymbol("RELEVANT-SBHL-TV-IS-GENERAL-TV");
public static final SubLSymbol $kw7$ERROR = makeKeyword("ERROR");
public static final SubLString $str8$_A_is_not_a__A = makeString("~A is not a ~A");
public static final SubLSymbol $sym9$SBHL_TRUE_TV_P = makeSymbol("SBHL-TRUE-TV-P");
public static final SubLSymbol $kw10$CERROR = makeKeyword("CERROR");
public static final SubLString $str11$continue_anyway = makeString("continue anyway");
public static final SubLSymbol $kw12$WARN = makeKeyword("WARN");
public static final SubLString $str13$_A_is_not_a_valid__sbhl_type_erro = makeString("~A is not a valid *sbhl-type-error-action* value");
public static final SubLObject $const14$True_JustificationTruth = constant_handles.reader_make_constant_shell(makeString("True-JustificationTruth"));
public static final SubLSymbol $kw15$OLD = makeKeyword("OLD");
public static final SubLSymbol $kw16$RESOURCE = makeKeyword("RESOURCE");
public static final SubLString $str17$Node__a_does_not_pass_sbhl_type_t = makeString("Node ~a does not pass sbhl-type-test ~a~%");
public static final SubLString $str18$marking_space____S__ = makeString("marking-space = ~S~%");
public static final SubLSymbol $sym19$SBHL_MARK_CLOSURE_AS_MARKED = makeSymbol("SBHL-MARK-CLOSURE-AS-MARKED");
public static final SubLSymbol $sym20$SBHL_UNMARK_INITIALIZED_MARKED_CLOSURE = makeSymbol("SBHL-UNMARK-INITIALIZED-MARKED-CLOSURE");
public static final SubLSymbol $sym21$SBHL_APPLY_COMPOSE_FN = makeSymbol("SBHL-APPLY-COMPOSE-FN");
public static final SubLSymbol $sym22$SBHL_PUSH_ONTO_RESULT = makeSymbol("SBHL-PUSH-ONTO-RESULT");
public static final SubLSymbol $sym23$SBHL_PUSH_ONTO_RESULT_IF = makeSymbol("SBHL-PUSH-ONTO-RESULT-IF");
public static final SubLSymbol $sym24$SBHL_APPLY_MARK_IN_SPACE = makeSymbol("SBHL-APPLY-MARK-IN-SPACE");
public static final SubLSymbol $sym25$SBHL_APPLY_UNMARK_IN_SPACE = makeSymbol("SBHL-APPLY-UNMARK-IN-SPACE");
public static final SubLSymbol $sym26$SBHL_MARK_IN_TARGET_SPACE = makeSymbol("SBHL-MARK-IN-TARGET-SPACE");
public static final SubLSymbol $sym27$SBHL_MARK_IN_TARGET_GATHER_SPACE = makeSymbol("SBHL-MARK-IN-TARGET-GATHER-SPACE");
public static final SubLString $str28$invalid_module_type__a = makeString("invalid module type ~a");
public static final SubLSymbol $sym29$SBHL_MARK_CLOSURE_IN_TARGET_SPACE = makeSymbol("SBHL-MARK-CLOSURE-IN-TARGET-SPACE");
public static final SubLSymbol $sym30$SBHL_MARK_NODE_AND_INSTANCES_IN_TARGET_SPACE = makeSymbol("SBHL-MARK-NODE-AND-INSTANCES-IN-TARGET-SPACE");
public static final SubLString $str31$Error_in_direction__a = makeString("Error in direction ~a");
public static final SubLSymbol $sym32$SBHL_PREDICATE_OBJECT_P = makeSymbol("SBHL-PREDICATE-OBJECT-P");
//// Initializers
public void declareFunctions() {
declare_sbhl_marking_methods_file();
}
public void initializeVariables() {
init_sbhl_marking_methods_file();
}
public void runTopLevelForms() {
setup_sbhl_marking_methods_file();
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.coreutils;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int font = 0x7f010003;
public static final int fontProviderAuthority = 0x7f010004;
public static final int fontProviderCerts = 0x7f010005;
public static final int fontProviderFetchStrategy = 0x7f010006;
public static final int fontProviderFetchTimeout = 0x7f010007;
public static final int fontProviderPackage = 0x7f010008;
public static final int fontProviderQuery = 0x7f010009;
public static final int fontStyle = 0x7f01000a;
public static final int fontWeight = 0x7f01000b;
}
public static final class bool {
private bool() {}
public static final int abc_action_bar_embed_tabs = 0x7f020000;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f03000b;
public static final int notification_icon_bg_color = 0x7f03000c;
public static final int ripple_material_light = 0x7f03000f;
public static final int secondary_text_default_material_light = 0x7f030011;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f040000;
public static final int compat_button_inset_vertical_material = 0x7f040001;
public static final int compat_button_padding_horizontal_material = 0x7f040002;
public static final int compat_button_padding_vertical_material = 0x7f040003;
public static final int compat_control_corner_material = 0x7f040004;
public static final int notification_action_icon_size = 0x7f040005;
public static final int notification_action_text_size = 0x7f040006;
public static final int notification_big_circle_margin = 0x7f040007;
public static final int notification_content_margin_start = 0x7f040008;
public static final int notification_large_icon_height = 0x7f040009;
public static final int notification_large_icon_width = 0x7f04000a;
public static final int notification_main_column_padding_top = 0x7f04000b;
public static final int notification_media_narrow_margin = 0x7f04000c;
public static final int notification_right_icon_size = 0x7f04000d;
public static final int notification_right_side_padding_top = 0x7f04000e;
public static final int notification_small_icon_background_padding = 0x7f04000f;
public static final int notification_small_icon_size_as_large = 0x7f040010;
public static final int notification_subtext_size = 0x7f040011;
public static final int notification_top_pad = 0x7f040012;
public static final int notification_top_pad_large_text = 0x7f040013;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f050016;
public static final int notification_bg = 0x7f050017;
public static final int notification_bg_low = 0x7f050018;
public static final int notification_bg_low_normal = 0x7f050019;
public static final int notification_bg_low_pressed = 0x7f05001a;
public static final int notification_bg_normal = 0x7f05001b;
public static final int notification_bg_normal_pressed = 0x7f05001c;
public static final int notification_icon_background = 0x7f05001d;
public static final int notification_template_icon_bg = 0x7f05001e;
public static final int notification_template_icon_low_bg = 0x7f05001f;
public static final int notification_tile_bg = 0x7f050020;
public static final int notify_panel_notification_icon_bg = 0x7f050021;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f060001;
public static final int action_divider = 0x7f060002;
public static final int action_image = 0x7f060003;
public static final int action_text = 0x7f060004;
public static final int actions = 0x7f060005;
public static final int async = 0x7f060008;
public static final int blocking = 0x7f06000a;
public static final int chronometer = 0x7f06000c;
public static final int forever = 0x7f06000f;
public static final int icon = 0x7f060010;
public static final int icon_group = 0x7f060011;
public static final int info = 0x7f060013;
public static final int italic = 0x7f060014;
public static final int line1 = 0x7f060016;
public static final int line3 = 0x7f060017;
public static final int normal = 0x7f06001a;
public static final int notification_background = 0x7f06001b;
public static final int notification_main_column = 0x7f06001c;
public static final int notification_main_column_container = 0x7f06001d;
public static final int right_icon = 0x7f06001e;
public static final int right_side = 0x7f06001f;
public static final int text = 0x7f060022;
public static final int text2 = 0x7f060023;
public static final int time = 0x7f060024;
public static final int title = 0x7f060025;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f070002;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f080000;
public static final int notification_action_tombstone = 0x7f080001;
public static final int notification_template_custom_big = 0x7f080008;
public static final int notification_template_icon_group = 0x7f080009;
public static final int notification_template_part_chronometer = 0x7f08000d;
public static final int notification_template_part_time = 0x7f08000e;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0a001a;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0b0001;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0b0002;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0b0004;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0b0007;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0b0009;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0b000b;
public static final int Widget_Compat_NotificationActionText = 0x7f0b000c;
}
public static final class styleable {
private styleable() {}
public static final int[] FontFamily = { 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x7f010003, 0x7f01000a, 0x7f01000b };
public static final int FontFamilyFont_font = 0;
public static final int FontFamilyFont_fontStyle = 1;
public static final int FontFamilyFont_fontWeight = 2;
}
}
|
/**************************************************************************
* *
* Java Grande Forum Benchmark Suite - MPJ Version 1.0 *
* *
* produced by *
* *
* Java Grande Benchmarking Project *
* *
* at *
* *
* Edinburgh Parallel Computing Centre *
* *
* email: epcc-javagrande@epcc.ed.ac.uk *
* *
* *
* This version copyright (c) The University of Edinburgh, 2001. *
* All rights reserved. *
* *
**************************************************************************/
package jgf_mpj_benchmarks.section1;
import java.io.*;
import jgf_mpj_benchmarks.*;
//import jgfutil.*;
import mpi.*;
public class JGFBcastBench implements JGFSection1{
public static int nprocess;
public static int rank;
private static final int INITSIZE = 1;
private static final int MAXSIZE = 1000000;
private static final double TARGETTIME = 10.0;
private static final int MLOOPSIZE = 25;
private static final int SMAX = 5000000;
private static final int SMIN = 4;
public JGFBcastBench(int rank, int nprocess) {
this.rank = rank;
this.nprocess=nprocess;
}
public void JGFrun() throws MPIException {
int size,i,l,m_size;
double logsize;
double b_time;
b_time = 0.0;
double [] time = new double[1];
m_size = 0;
logsize = Math.log((double) SMAX) - Math.log((double) SMIN);
/* Bcast an array of doubles */
/* Create the timers */
if(rank==0){
JGFInstrumentor.addTimer("Section1:Bcast:Double", "bytes");
JGFInstrumentor.addTimer("Section1:Bcast:Barrier", "barriers");
}
/* loop over no of different message sizes */
for(l=0;l<MLOOPSIZE;l++){
/* Initialize the sending data */
m_size = (int)(Math.exp(Math.log((double)SMIN)+(double) ((double) l/(double) MLOOPSIZE*logsize)));
double [] arr = new double[m_size];
time[0] = 0.0;
size=INITSIZE;
MPI.COMM_WORLD.Barrier();
/* Start the timer */
while (time[0] < TARGETTIME && size < MAXSIZE){
if(rank==0){
JGFInstrumentor.resetTimer("Section1:Bcast:Double");
JGFInstrumentor.startTimer("Section1:Bcast:Double");
}
/* Carryout the broadcast operation */
for (int k=0; k<size; k++){
MPI.COMM_WORLD.Bcast(arr,0,arr.length,MPI.DOUBLE,0);
MPI.COMM_WORLD.Barrier();
}
/* Stop the timer */
if(rank==0){
JGFInstrumentor.stopTimer("Section1:Bcast:Double");
time[0] = JGFInstrumentor.readTimer("Section1:Bcast:Double");
JGFInstrumentor.addOpsToTimer("Section1:Bcast:Double",(double) size*arr.length*8);
}
/* Broadcast time to the other processes */
MPI.COMM_WORLD.Barrier();
MPI.COMM_WORLD.Bcast(time,0,1,MPI.DOUBLE,0);
size *=2;
}
size /=2;
/* determine the cost of the Barrier, subtract the cost and write out the performance time */
MPI.COMM_WORLD.Barrier();
if(rank==0) {
JGFInstrumentor.resetTimer("Section1:Bcast:Barrier");
JGFInstrumentor.startTimer("Section1:Bcast:Barrier");
}
for (int k=0; k<size; k++){
MPI.COMM_WORLD.Barrier();
}
if(rank==0) {
JGFInstrumentor.stopTimer("Section1:Bcast:Barrier");
b_time = JGFInstrumentor.readTimer("Section1:Bcast:Barrier");
JGFInstrumentor.addTimeToTimer("Section1:Bcast:Double", -b_time);
JGFInstrumentor.printperfTimer("Section1:Bcast:Double",arr.length);
}
}
/* Bcast an array of objects containing a double */
/* Create the timer */
if(rank==0){
JGFInstrumentor.addTimer("Section1:Bcast:Object", "objects");
}
/* loop over no of different message sizes */
for(l=0;l<MLOOPSIZE;l++){
/* Initialize the sending data */
m_size = (int)(Math.exp(Math.log((double)SMIN)+(double) ((double) l/(double) MLOOPSIZE*logsize)));
obj_double [] arr_obj = new obj_double[m_size];
for(int k=0;k<m_size;k++){
arr_obj[k] = new obj_double(0.0);
}
time[0] = 0.0;
size=INITSIZE;
MPI.COMM_WORLD.Barrier();
/* Start the timer */
while (time[0] < TARGETTIME && size < MAXSIZE){
if(rank==0){
JGFInstrumentor.resetTimer("Section1:Bcast:Object");
JGFInstrumentor.startTimer("Section1:Bcast:Object");
}
/* Carryout the broadcast operation */
for (int k=0; k<size; k++){
MPI.COMM_WORLD.Bcast(arr_obj,0,arr_obj.length,MPI.OBJECT,0);
MPI.COMM_WORLD.Barrier();
}
/* Stop the timer */
if(rank==0){
JGFInstrumentor.stopTimer("Section1:Bcast:Object");
time[0] = JGFInstrumentor.readTimer("Section1:Bcast:Object");
JGFInstrumentor.addOpsToTimer("Section1:Bcast:Object",(double) size*arr_obj.length);
}
/* Broadcast time to the other processes */
MPI.COMM_WORLD.Barrier();
MPI.COMM_WORLD.Bcast(time,0,1,MPI.DOUBLE,0);
size *=2;
}
size /=2;
/* determine the cost of the Barrier, subtract the cost and write out the performance time */
MPI.COMM_WORLD.Barrier();
if(rank==0) {
JGFInstrumentor.resetTimer("Section1:Bcast:Barrier");
JGFInstrumentor.startTimer("Section1:Bcast:Barrier");
}
for (int k=0; k<size; k++){
MPI.COMM_WORLD.Barrier();
}
if(rank==0) {
JGFInstrumentor.stopTimer("Section1:Bcast:Barrier");
b_time = JGFInstrumentor.readTimer("Section1:Bcast:Barrier");
JGFInstrumentor.addTimeToTimer("Section1:Bcast:Object", -b_time);
JGFInstrumentor.printperfTimer("Section1:Bcast:Object",arr_obj.length);
}
}
}
public static void main(String[] argv) throws MPIException{
}
public JGFBcastBench(String[] argv) throws Exception {
/* Initialise MPI */
MPI.Init(argv);
rank = MPI.COMM_WORLD.Rank();
nprocess = MPI.COMM_WORLD.Size();
if(rank==0){
JGFInstrumentor.printHeader(1,0,nprocess);
}
JGFBcastBench bc = new JGFBcastBench(rank, nprocess);
bc.JGFrun();
/* Finalise MPI */
MPI.Finalize();
}
}
|
package com.huaweicloud.sdk.meeting.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.function.Consumer;
import java.util.Objects;
/**
* ModResourceDTO
*/
public class ModResourceDTO {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="id")
private String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="type")
private String type;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="expireDate")
private Long expireDate;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="isDisabled")
private Boolean isDisabled;
public ModResourceDTO withId(String id) {
this.id = id;
return this;
}
/**
* 资源标识
* @return id
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ModResourceDTO withType(String type) {
this.type = type;
return this;
}
/**
* 资源类型,企业内ID和TYPE唯一标识一个资源项,若只传资源ID可能会修改多个资源的信息. - VMR - 云会议室 - CONF_CALL - 会议并发数 - HARD_1080P - 1080P硬终端 - HARD_720P - 720P硬终端 - SOFT - 软终端用户数 - ROOM - 大屏软终端 - LIVE - 直播推流 - RECORD - 录播空间 - HARD_THIRD_PARTY - 第三方硬终端账号 - HUAWEI_VISION -智慧屏
* @return type
*/
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ModResourceDTO withExpireDate(Long expireDate) {
this.expireDate = expireDate;
return this;
}
/**
* 到期时间
* minimum: 0
* @return expireDate
*/
public Long getExpireDate() {
return expireDate;
}
public void setExpireDate(Long expireDate) {
this.expireDate = expireDate;
}
public ModResourceDTO withIsDisabled(Boolean isDisabled) {
this.isDisabled = isDisabled;
return this;
}
/**
* 资源是否被停用
* @return isDisabled
*/
public Boolean getIsDisabled() {
return isDisabled;
}
public void setIsDisabled(Boolean isDisabled) {
this.isDisabled = isDisabled;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModResourceDTO modResourceDTO = (ModResourceDTO) o;
return Objects.equals(this.id, modResourceDTO.id) &&
Objects.equals(this.type, modResourceDTO.type) &&
Objects.equals(this.expireDate, modResourceDTO.expireDate) &&
Objects.equals(this.isDisabled, modResourceDTO.isDisabled);
}
@Override
public int hashCode() {
return Objects.hash(id, type, expireDate, isDisabled);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModResourceDTO {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" expireDate: ").append(toIndentedString(expireDate)).append("\n");
sb.append(" isDisabled: ").append(toIndentedString(isDisabled)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package es.bsc.compss.types.data.listener;
import es.bsc.compss.types.data.operation.DataOperation;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class EventListener {
private static final AtomicInteger nextId = new AtomicInteger(0);
private final int id = nextId.getAndIncrement();
public Integer getId() {
return id;
}
public abstract void notifyEnd(DataOperation fOp);
public abstract void notifyFailure(DataOperation fOp, Exception e);
}
|
package com.github.thomasfischl.rayden.util;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import com.github.thomasfischl.rayden.raydenDSL.KeywordCall;
import com.github.thomasfischl.rayden.raydenDSL.KeywordDecl;
import com.github.thomasfischl.rayden.raydenDSL.KeywordType;
import com.github.thomasfischl.rayden.raydenDSL.LocatorDecl;
import com.github.thomasfischl.rayden.raydenDSL.LocatorPartDecl;
import com.github.thomasfischl.rayden.raydenDSL.Model;
import com.github.thomasfischl.rayden.raydenDSL.ObjectRepositoryDecl;
import com.github.thomasfischl.rayden.raydenDSL.ObjectRepositryControlDecl;
import com.github.thomasfischl.rayden.runtime.RaydenRuntime;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class RaydenModelUtils {
private static LoadingCache<Model, Collection<KeywordDecl>> cache;
public static List<KeywordDecl> getAllKeywords(EObject obj) {
return getAllKeywords(getRoot(obj));
}
public static List<KeywordDecl> getAllKeywords(Model root) {
List<KeywordDecl> keywords = new ArrayList<>();
if (root != null) {
keywords.addAll(loadImportedKeywords(root));
for (KeywordDecl keyword : root.getKeywords()) {
keywords.add(keyword);
}
}
return keywords;
}
public static List<ObjectRepositryControlDecl> getAllApplications(Model model) {
List<ObjectRepositryControlDecl> controls = new ArrayList<>();
EList<ObjectRepositoryDecl> ors = model.getObjectrepositories();
for (ObjectRepositoryDecl or : ors) {
for (ObjectRepositryControlDecl ctrl : or.getControls()) {
if ("application".equals(ctrl.getType().getType())) {
controls.add(ctrl);
}
}
}
return controls;
}
public static Model getRoot(EObject obj) {
if (obj == null) {
return null;
}
if (obj instanceof Model) {
return (Model) obj;
}
return getRoot(obj.eContainer());
}
public static String normalizeKeyword(String name) {
if (name == null) {
return null;
}
name = name.trim();
if (name.endsWith("!") || name.endsWith(".") || name.endsWith("?")) {
name = name.substring(0, name.length() - 1);
}
return name.trim();
}
public static KeywordDecl getKeywordDecl(EObject obj) {
if (obj == null) {
return null;
}
if (obj instanceof KeywordDecl) {
return (KeywordDecl) obj;
}
return getKeywordDecl(obj.eContainer());
}
public static boolean isInlineKeyword(KeywordCall keyword) {
return keyword.getKeywordList() != null && keyword.getParameters() == null;
}
public static boolean isScriptedKeyword(KeywordDecl keyword) {
return keyword.getScript() != null;
}
public static boolean isTestSuiteKeyword(KeywordDecl keyword) {
return keyword.getType() == KeywordType.TESTSUITE;
}
public static Collection<KeywordDecl> loadImportedKeywords(Model model) {
if (cache == null) {
CacheLoader<Model, Collection<KeywordDecl>> loader = new CacheLoader<Model, Collection<KeywordDecl>>() {
@Override
public Collection<KeywordDecl> load(Model model) throws Exception {
try {
RaydenRuntime runtime = RaydenRuntime.createRuntime();
File workingFolder = new File(".");
// define special workspace for eclipse
IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(model.eResource().getURI().toPlatformString(true));
if (resource != null && resource.getProject() != null) {
IProject project = resource.getProject();
workingFolder = new File(project.getLocationURI());
}
System.out.println("Set working folder: " + workingFolder);
runtime.setWorkingFolder(workingFolder);
runtime.loadRaydenFile(new FileReader(new File(workingFolder, resource.getName())));
return runtime.getDefinedImportedKeywords().values();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
};
cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(10000).build(loader);
}
if (model.eResource() != null) {
try {
return cache.get(model);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
return new ArrayList<KeywordDecl>();
}
public static ObjectRepositryControlDecl getControl(LocatorDecl locator, Model root) {
List<ObjectRepositryControlDecl> applications = getAllApplications(root);
EList<LocatorPartDecl> parts = locator.getParts();
for (ObjectRepositryControlDecl application : applications) {
ObjectRepositryControlDecl control = getControl(application, parts, 0);
if (control != null) {
return control;
}
}
return null;
}
private static ObjectRepositryControlDecl getControl(ObjectRepositryControlDecl parentControl, EList<LocatorPartDecl> parts, int index) {
if (parts.size() <= index) {
return parentControl;
}
LocatorPartDecl part = parts.get(index);
if (part.getName().trim().equals(parentControl.getName().trim())) {
for (ObjectRepositryControlDecl control : parentControl.getControls()) {
ObjectRepositryControlDecl result = getControl(control, parts, index + 1);
if (result != null) {
return result;
}
}
return parentControl;
} else {
return null;
}
}
}
|
package com.ycsoft.report.query.redis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.ycsoft.commons.exception.ReportException;
import com.ycsoft.report.commons.ReportConstants;
import com.ycsoft.report.commons.SerializeUtil;
import com.ycsoft.report.dao.redis.JedisDao;
import com.ycsoft.report.query.cube.impl.AbstractDataSet;
import com.ycsoft.report.query.daq.DataReader;
import com.ycsoft.report.query.daq.translate.CacheAcquisition;
import com.ycsoft.report.query.daq.translate.CacheHeadCell;
import com.ycsoft.report.query.daq.translate.CacheKey;
import static com.ycsoft.report.commons.ReportConstants.memory_row_max;
/**
* 使用redis执行cube运算
* 当内存中计算的结果集大于1000条时,把结果转储到redis。
* CacheKey的排序交给mongodb实现
*/
public class RedisAcquisition extends CacheAcquisition {
private JedisDao jedisDao=null;
private String query_id=null;;
public RedisAcquisition(JedisDao jedisDao, String query_id){
this.jedisDao=jedisDao;
this.query_id= query_id;
}
/**
* RedisCacheKey含有在redis使用的键值
* @throws ReportException
*/
@Override
protected CacheKey createCacheKey(List<Object> keylist,List<Integer> sortlist) throws ReportException {
return new RedisCacheKey(keylist,sortlist,this.query_id);
}
/**
* 在redis的cube运算,当计算键值>memory_row_max时,使用redis缓存合并数据
* @return
*/
@Override
public DataReader translate(String query_cache_id, AbstractDataSet dataset)
throws ReportException {
List<CacheHeadCell> headlist=this.createCacheHeadCell(dataset);
int no_crosshead_start=this.getNoCrossheadStart(headlist);
//初始化排序器
sort=new CacheKeySortByDB(no_crosshead_start,this.query_id);
DataReader dr=super.translate(query_cache_id, dataset);
//计算结果还在内存中
if(this.useredis){
if(this.getMenoryMap().size()>0){
//this.mergeSet();
mergeSetNoBacth();
}
return new RedisDR();
}else{
return dr;
}
}
private CacheKeySortByDB sort=null;
private boolean useredis=false;
/**
* 当java内存中运算的cube运算键值达到memory_row_max限额时,
* 把运算键值提交给redis缓存合并;清空java内存中运算的cube运算键值
*/
@Override
protected boolean isMenoryMax() throws ReportException {
if(this.getMenoryMap().size()>memory_row_max){
//this.mergeSet();
mergeSetNoBacth();
this.getMenoryMap().clear();
if(!this.useredis){
this.useredis=true;
}
}
return false;
}
/**
* 本地缓存单条提交redis合并运算
* @throws ReportException
*/
private void mergeSetNoBacth() throws ReportException{
try{
//cube缓存redis的keys
List<CacheKey> sortdbkeys=new ArrayList<CacheKey>(ReportConstants.cache_batch_size);
Iterator<CacheKey> it= this.getMenoryMap().keySet().iterator();
while(it.hasNext()){
//提取一个内存中键值
RedisCacheKey key= (RedisCacheKey) it.next();
byte[] rediskey=key.getRediskey().getBytes();
byte[] redisvalue=this.jedisDao.get(rediskey);
ArrayList<Double> localValue=(ArrayList<Double>) this.getMenoryMap().get(key);
if(redisvalue==null){
//缓存不存在则提交缓存
this.jedisDao.set(rediskey, SerializeUtil.serialize(localValue));
sortdbkeys.add(key);
}else{
//合并本地
ArrayList<Double> serverValue= (ArrayList<Double>) SerializeUtil.unserialize(redisvalue);
for(int j=0;j<localValue.size();j++){
localValue.set(j,localValue.get(j).doubleValue()+serverValue.get(j).doubleValue());
}
this.jedisDao.set(rediskey, SerializeUtil.serialize(localValue));
}
//提交服务器
if(sortdbkeys.size()>=ReportConstants.cache_batch_size||!it.hasNext()){
sort.openWriteMode();
sort.writeCacheKey(sortdbkeys);
sortdbkeys.clear();
}
}
}catch(ReportException e){
sort.close();
throw e;
}catch(Exception e){
sort.close();
throw new ReportException(e);
}
}
/**
* 本地缓存批量提交redis合并运算
* <p> 存在bug
* @throws ReportException
*/
private void mergeSet() throws ReportException {
try{
//批量提交数量
int batch_idx=0;
//cube缓存redis的keys
ArrayList<byte[]> rediskeys=new ArrayList<byte[]>(ReportConstants.cache_batch_size);
//cube缓存redis的keysvalues
ArrayList<byte[]> rediskeyvalues=new ArrayList<byte[]>(ReportConstants.cache_batch_size*2);
//新计算出来的CacheKey列表
List<CacheKey> newcechekeys=new ArrayList<CacheKey>(ReportConstants.cache_batch_size);
Map<Integer,CacheKey> newcechekeyMap=new HashMap<Integer,CacheKey>(ReportConstants.cache_batch_size);
Iterator<CacheKey> it= this.getMenoryMap().keySet().iterator();
while(it.hasNext()){
//提取一个内存中键值
RedisCacheKey key= (RedisCacheKey) it.next();
rediskeys.add(key.getRediskey().getBytes());
newcechekeyMap.put(batch_idx, key);
batch_idx++;
//当从内存提取键值达到批量提交限额或元素迭代完时,提交redis缓存并合并相同的key对应的计算结果
if(batch_idx>=ReportConstants.cache_batch_size||!it.hasNext()){
batch_idx=0;//从新计数
//从redi获取keys对应的values,如果获取的值为空,说明redis上不存在这个值的缓存
List<byte[]> redisvalues=this.jedisDao.mget(rediskeys.toArray(new byte[rediskeys.size()][]));
for(int i=0;i<rediskeys.size();i++){
byte[] value=redisvalues.get(i);
ArrayList<Double> cubeValue=(ArrayList<Double>) this.getMenoryMap().get(key);
if(value!=null){
//如果value不为空,redis获取的值和本地相同key的值相加
List<Double> tempCubeValue= (List<Double>) SerializeUtil.unserialize(value);
for(int j=0;j<cubeValue.size();j++){
cubeValue.set(j,cubeValue.get(j).doubleValue()+tempCubeValue.get(j).doubleValue());
}
}else{
//value为空,说明CacheKey是新计算出来的
newcechekeys.add(newcechekeyMap.get(i));
}
rediskeyvalues.add(rediskeys.get(i));
rediskeyvalues.add(SerializeUtil.serialize(cubeValue));
}
this.jedisDao.mset(rediskeyvalues.toArray(new byte[rediskeyvalues.size()][]));
rediskeys.clear();
rediskeyvalues.clear();
//新生成的cachekey提交sortdb保存
if(newcechekeys.size()>=ReportConstants.cache_batch_size||!it.hasNext()){
sort.openWriteMode();
sort.writeCacheKey(newcechekeys);
newcechekeys.clear();
}
newcechekeyMap.clear();
}
}
}catch(ReportException e){
sort.close();
throw e;
}catch(Exception e){
sort.close();
throw new ReportException(e);
}
}
/**
* 使用sort_db排序key并从redis的cube缓存中提取计算结果
*/
class RedisDR implements DataReader{
private int row_idx=-1;
private int row_max=0;
private List<RedisCacheKey> redisCacheKeys=new ArrayList<RedisCacheKey>();
public void close() throws ReportException {
sort.close();
}
public Object getObject(int i) throws ReportException {
return redisCacheKeys.get(this.row_idx).getKeys().get(i-1);
}
public String getString(int i) throws ReportException {
return redisCacheKeys.get(this.row_idx).getKeys().get(i-1).toString();
}
public boolean next() throws ReportException {
this.row_idx++;
if(row_idx>=this.row_max){
redisCacheKeys.clear();
List<byte[]> rediskeys=new ArrayList<byte[]>(ReportConstants.cache_batch_size);
Map<Integer,RedisCacheKey> cachekeyMap=new HashMap<Integer,RedisCacheKey>(ReportConstants.cache_batch_size);
for(int i=0;i<ReportConstants.cache_batch_size;i++){
//从sortDB读取排序好的RedisCacheKey
RedisCacheKey key= sort.readCacheKey();
if(key==null){ break;}
rediskeys.add(key.getRediskey().getBytes());
cachekeyMap.put(i, key);
}
if(rediskeys.size()>0){
//从redis缓存中提取计算结果
byte[][] bytekeys=rediskeys.toArray(new byte[rediskeys.size()][]);
List<byte[]> values=jedisDao.mget(bytekeys);
for(int i=0;i<values.size();i++ ){
RedisCacheKey key=cachekeyMap.get(i);
key.getKeys().addAll((ArrayList<Double>)SerializeUtil.unserialize(values.get(i)));
redisCacheKeys.add(key);
}
//删除已读取的缓存计算结果数据
jedisDao.del(bytekeys);
}
row_max=redisCacheKeys.size();
this.row_idx=0;
}
if(row_max<=0)
return false;
else
return true;
}
public void open() throws ReportException {
sort.openReadMode();
row_idx=-1;
row_max=0;
}
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_random_predec_75a.java
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-75a.tmpl.java
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: random Set data to a random value
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: decrement
* GoodSink: Ensure there will not be an underflow before decrementing data
* BadSink : Decrement data, which can cause an Underflow
* Flow Variant: 75 Data flow: data passed in a serialized object from one method to another in different source files in the same package
*
* */
package testcases.CWE191_Integer_Underflow.s05;
import testcasesupport.*;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import javax.servlet.http.*;
import java.security.SecureRandom;
public class CWE191_Integer_Underflow__int_random_predec_75a extends AbstractTestCase
{
public void bad() throws Throwable
{
int data;
/* POTENTIAL FLAW: Set data to a random value */
data = (new SecureRandom()).nextInt();
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE191_Integer_Underflow__int_random_predec_75b()).badSink(dataSerialized );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
public void good() throws Throwable
{
goodG2B();
goodB2G();
}
/* goodG2B() - use GoodSource and BadSink */
private void goodG2B() throws Throwable
{
int data;
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE191_Integer_Underflow__int_random_predec_75b()).goodG2BSink(dataSerialized );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
/* goodB2G() - use BadSource and GoodSink */
private void goodB2G() throws Throwable
{
int data;
/* POTENTIAL FLAW: Set data to a random value */
data = (new SecureRandom()).nextInt();
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE191_Integer_Underflow__int_random_predec_75b()).goodB2GSink(dataSerialized );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
/**
* Subinterface of {@link BeanPostProcessor} that adds a before-destruction callback.
*
* <p>The typical usage will be to invoke custom destruction callbacks on
* specific bean types, matching corresponding initialization callbacks.
*
* @author Juergen Hoeller
* @since 1.0.1
*/
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given bean instance before its
* destruction, e.g. invoking custom destruction callbacks.
* <p>Like DisposableBean's {@code destroy} and a custom destroy method, this
* callback will only apply to beans which the container fully manages the
* lifecycle for. This is usually the case for singletons and scoped beans.
* @param bean the bean instance to be destroyed
* @param beanName the name of the bean
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.DisposableBean#destroy()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#setDestroyMethodName(String)
*
* 在销毁之前调用
*/
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
/**
* Determine whether the given bean instance requires destruction by this
* post-processor.
* <p>The default implementation returns {@code true}. If a pre-5 implementation
* of {@code DestructionAwareBeanPostProcessor} does not provide a concrete
* implementation of this method, Spring silently assumes {@code true} as well.
* @param bean the bean instance to check
* @return {@code true} if {@link #postProcessBeforeDestruction} is supposed to
* be called for this bean instance eventually, or {@code false} if not needed
* @since 4.3
*/
default boolean requiresDestruction(Object bean) {
return true;
}
}
|
package com.gowpar.com.gowpar.playground;
import java.util.ArrayList;
import java.util.Random;
public class OddEvenStream {
public static void main(String[] args) {
ArrayList<Integer> randomIntList = generateRandomIntList();
randomIntList
.stream()
.map(i -> i%2 ==0)
.forEach(System.out::println);
}
public static ArrayList<Integer> generateRandomIntList() {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i <= 2000; i++) {
arrayList.add(random.nextInt(1000));
}
return arrayList;
}
}
|
package org.batfish.datamodel;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.io.ObjectStreamException;
import org.batfish.datamodel.visitors.GenericIpSpaceVisitor;
public class IpIpSpace extends IpSpace {
// Soft values: let it be garbage collected in times of pressure.
// Maximum size 2^20: Just some upper bound on cache size, well less than GiB.
// (12 bytes seems smallest possible entry (long + int), would be 12 MiB total).
private static final LoadingCache<Ip, IpIpSpace> CACHE =
CacheBuilder.newBuilder()
.softValues()
.maximumSize(1 << 20)
.build(CacheLoader.from(IpIpSpace::new));
private static final String PROP_IP = "ip";
private final Ip _ip;
@JsonCreator
static IpIpSpace create(@JsonProperty(PROP_IP) Ip ip) {
return CACHE.getUnchecked(ip);
}
private IpIpSpace(Ip ip) {
_ip = ip;
}
@Override
public <R> R accept(GenericIpSpaceVisitor<R> visitor) {
return visitor.visitIpIpSpace(this);
}
@Override
protected int compareSameClass(IpSpace o) {
return _ip.compareTo(((IpIpSpace) o)._ip);
}
@Override
protected boolean exprEquals(Object o) {
return _ip.equals(((IpIpSpace) o)._ip);
}
@JsonProperty(PROP_IP)
public Ip getIp() {
return _ip;
}
@Override
public int hashCode() {
return _ip.hashCode();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(IpIpSpace.class).add(PROP_IP, _ip).toString();
}
/** Cache after deserialization. */
private Object readResolve() throws ObjectStreamException {
return CACHE.getUnchecked(_ip);
}
}
|
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.ast.visitors;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.j2cl.ast.AbstractRewriter;
import com.google.j2cl.ast.BinaryExpression;
import com.google.j2cl.ast.BinaryOperator;
import com.google.j2cl.ast.CompilationUnit;
import com.google.j2cl.ast.Expression;
import com.google.j2cl.ast.PrefixExpression;
import com.google.j2cl.ast.PrefixOperator;
import com.google.j2cl.ast.RuntimeMethods;
import com.google.j2cl.ast.TypeDescriptor;
import com.google.j2cl.ast.TypeDescriptors;
/** Replaces long operations with corresponding long utils method calls. */
public class NormalizeLongs extends NormalizationPass {
@Override
public void applyTo(CompilationUnit compilationUnit) {
compilationUnit.accept(
new AbstractRewriter() {
@Override
public Expression rewriteBinaryExpression(BinaryExpression binaryExpression) {
Expression leftOperand = binaryExpression.getLeftOperand();
Expression rightOperand = binaryExpression.getRightOperand();
TypeDescriptor returnTypeDescriptor = binaryExpression.getTypeDescriptor();
// Skips non-long operations.
if ((!TypeDescriptors.isPrimitiveLong(leftOperand.getTypeDescriptor())
&& !TypeDescriptors.isPrimitiveLong(rightOperand.getTypeDescriptor()))
|| (!TypeDescriptors.isPrimitiveLong(returnTypeDescriptor)
&& !TypeDescriptors.isPrimitiveBoolean(returnTypeDescriptor))) {
return binaryExpression;
}
BinaryOperator operator = binaryExpression.getOperator();
// Skips assignment because it doesn't need special handling.
if (operator == BinaryOperator.ASSIGN) {
return binaryExpression;
}
return RuntimeMethods.createLongUtilsMethodCall(
getLongOperationFunctionName(operator),
returnTypeDescriptor,
leftOperand,
rightOperand);
}
@Override
public Expression rewritePrefixExpression(PrefixExpression prefixExpression) {
Expression operand = prefixExpression.getOperand();
// Only interested in longs.
if (!TypeDescriptors.isPrimitiveLong(operand.getTypeDescriptor())) {
return prefixExpression;
}
PrefixOperator operator = prefixExpression.getOperator();
// Unwrap PLUS operator because it's a NOOP.
if (operator == PrefixOperator.PLUS) {
return prefixExpression.getOperand();
}
// LongUtils.$someOperation(operand);
return RuntimeMethods.createLongUtilsMethodCall(
getLongOperationFunctionName(operator), operand);
}
});
}
private static String getLongOperationFunctionName(PrefixOperator prefixOperator) {
switch (prefixOperator) {
case MINUS:
return "$negate"; // Multiply by -1;
case COMPLEMENT:
return "$not"; // Bitwise not
default:
checkArgument(
false, "The requested binary operator is invalid on Longs " + prefixOperator + ".");
return null;
}
}
private static String getLongOperationFunctionName(BinaryOperator binaryOperator) {
switch (binaryOperator) {
case TIMES:
return "$times";
case DIVIDE:
return "$divide";
case REMAINDER:
return "$remainder";
case PLUS:
return "$plus";
case MINUS:
return "$minus";
case LEFT_SHIFT:
return "$leftShift";
case RIGHT_SHIFT_SIGNED:
return "$rightShiftSigned";
case RIGHT_SHIFT_UNSIGNED:
return "$rightShiftUnsigned";
case LESS:
return "$less";
case GREATER:
return "$greater";
case LESS_EQUALS:
return "$lessEquals";
case GREATER_EQUALS:
return "$greaterEquals";
case EQUALS:
return "$equals";
case NOT_EQUALS:
return "$notEquals";
case BIT_XOR:
return "$xor";
case BIT_AND:
return "$and";
case BIT_OR:
return "$or";
default:
checkArgument(
false,
"The requested binary operator doesn't translate to a LongUtils call: "
+ binaryOperator
+ ".");
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.