answer stringlengths 17 10.2M |
|---|
package com.philihp.weblabora.model;
import static com.philihp.weblabora.model.TerrainTypeEnum.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.philihp.weblabora.model.building.*;
public class CommandUse implements MoveCommand, InvalidDuringSettlement {
@Override
public void execute(Board board, CommandParameters params)
throws WeblaboraException {
String buildingId = params.get(0);
UsageParam usageParam = null;
boolean usingPrior = params.getSuffix().contains("*");
switch (params.size()) {
case 1:
usageParam = new UsageParam("");
break;
case 2:
usageParam = new UsageParam(params.get(1));
break;
default:
usageParam = new UsageParam("");
Integer x = null;
for (int i = 1; i < params.size(); i++) {
if(x == null) {
x = Integer.parseInt(params.get(i));
}
else {
usageParam.pushCoordinate(
x, Integer.parseInt(params.get(i)));
x = null;
}
}
if(x != null) {
throw new WeblaboraException("Coordinate building usage parameters must come in pairs. Parsed "+x+" for the x, but no y number.");
}
break;
}
execute(board, BuildingEnum.valueOf(buildingId), usageParam, usingPrior, params.getPlaceClergyman());
System.out.println("Using " + buildingId + " with " + usageParam);
}
public static void execute(Board board, BuildingEnum buildingId,
UsageParam param, boolean usingPrior, boolean placeClergyman) throws WeblaboraException {
Building building = board.findBuildingInstance(buildingId);
Player buildingOwner = building.getLocation().getLandscape().getPlayer();
Terrain location = building.getLocation();
if (placeClergyman) {
if (usingPrior) {
buildingOwner.placePrior(location);
} else {
buildingOwner.placeClergyman(location);
}
}
building.use(board, param);
}
} |
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.JULLogger;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.loader.JsModuleManagerFactory;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
/** A simple program that takes the main JS module file and replaces #include markers with the contents of other files.
*
* @author Enrique Zamudio
*/
public class Stitcher {
private static String VERSION="
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
try (FileInputStream fIn = new FileInputStream(sourceFile);
FileChannel source = fIn.getChannel();
FileOutputStream fOut = new FileOutputStream(destFile);
FileChannel destination = fOut.getChannel()) {
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
}
}
private static void compileLanguageModule(List<String> sources, PrintWriter writer, String clmod)
throws IOException {
final File clSrcDir = new File("../ceylon.language/src/ceylon/language/");
final File clSrcDirJs = new File("../ceylon.language/runtime-js");
File tmpdir = File.createTempFile("ceylonjs", "clsrc");
tmpdir.delete();
tmpdir = new File(tmpdir.getAbsolutePath());
tmpdir.mkdir();
tmpdir.deleteOnExit();
final File tmpout = new File(tmpdir, "modules");
tmpout.mkdir();
tmpout.deleteOnExit();
Options opts = Options.parse(new ArrayList<String>(Arrays.asList(
"-rep", "build/runtime", "-nocomments", "-optimize",
"-out", tmpout.getAbsolutePath(), "-nomodule")));
//Typecheck the whole language module
System.out.println("Compiling language module from Ceylon source");
TypeCheckerBuilder tcb = new TypeCheckerBuilder().addSrcDirectory(clSrcDir.getParentFile().getParentFile())
.addSrcDirectory(new File(clSrcDir.getParentFile().getParentFile().getParentFile(), "runtime-js"));
tcb.setRepositoryManager(CeylonUtils.repoManager().systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos()).outRepo(opts.getOutDir()).buildManager());
//This is to use the JSON metamodel
JsModuleManagerFactory.setVerbose(true);
tcb.moduleManagerFactory(new JsModuleManagerFactory((Map<String,Object>)JSONValue.parse(clmod)));
TypeChecker tc = tcb.getTypeChecker();
tc.process();
if (tc.getErrors() > 0) {
System.exit(1);
}
for (String line : sources) {
//Compile these files
System.out.println("Compiling " + line);
final List<String> includes = new ArrayList<String>();
for (String filename : line.split(",")) {
final boolean isJsSrc = filename.trim().endsWith(".js");
final File src = new File(isJsSrc ? clSrcDirJs : clSrcDir,
isJsSrc ? filename.trim() :
String.format("%s.ceylon", filename.trim()));
if (src.exists() && src.isFile() && src.canRead()) {
includes.add(src.getPath());
} else {
throw new IllegalArgumentException("Invalid Ceylon language module source " + src);
}
}
//Compile only the files specified in the line
//Set this before typechecking to share some decls that otherwise would be private
JsCompiler.compilingLanguageModule=true;
JsCompiler jsc = new JsCompiler(tc, opts).stopOnErrors(false);
jsc.setFiles(includes);
jsc.generate();
File compsrc = new File(tmpout, String.format("ceylon/language/%s/ceylon.language-%<s.js", VERSION));
if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) {
try (BufferedReader jsr = new BufferedReader(new FileReader(compsrc))) {
String jsline = null;
while ((jsline = jsr.readLine()) != null) {
if (!jsline.contains("=require('")) {
writer.println(jsline);
}
}
} finally {
compsrc.delete();
}
} else {
System.out.println("WTF??? No generated js for language module!!!!");
System.exit(1);
}
}
}
private static void stitch(File infile, PrintWriter writer, List<String> sourceFiles) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8"));
try {
String line = null;
String clModel = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0) {
if (line.equals("//#METAMODEL")) {
System.out.println("Generating language module metamodel in JSON...");
TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false);
tcb.addSrcDirectory(new File("../ceylon.language/src"));
TypeChecker tc = tcb.getTypeChecker();
tc.process();
MetamodelVisitor mmg = null;
for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) {
if (!pu.getCompilationUnit().getErrors().isEmpty()) {
System.out.println("whoa, errors in the language module "
+ pu.getCompilationUnit().getLocation());
for (Message err : pu.getCompilationUnit().getErrors()) {
System.out.println(err.getMessage());
}
}
if (mmg == null) {
mmg = new MetamodelVisitor(pu.getPackage().getModule());
}
pu.getCompilationUnit().visit(mmg);
}
writer.print("var $$METAMODEL$$=");
clModel = JSONObject.toJSONString(mmg.getModel());
writer.print(clModel);
writer.println(";");
writer.flush();
} else if (line.equals("//#COMPILED")) {
System.out.println("Compiling language module sources");
compileLanguageModule(sourceFiles, writer, clModel);
} else if (!line.endsWith("//IGNORE")) {
writer.println(line);
}
}
}
} finally {
if (reader != null) reader.close();
}
}
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.err.println("This program requires 3 arguments to run:");
System.err.println("1. The path to the main JS file");
System.err.println("2. The path to the list of language module files to compile from Ceylon source");
System.err.println("3. The path of the resulting JS file");
System.exit(1);
return;
}
File infile = new File(args[0]);
if (infile.exists() && infile.isFile() && infile.canRead()) {
File outfile = new File(args[2]);
if (!outfile.getParentFile().exists()) {
outfile.getParentFile().mkdirs();
}
VERSION=outfile.getParentFile().getName();
ArrayList<String> clsrc = new ArrayList<String>();
File clSourcesPath = new File(args[1]);
if (!(clSourcesPath.exists() && clSourcesPath.isFile() && clSourcesPath.canRead())) {
throw new IllegalArgumentException("Invalid language module sources list " + args[2]);
}
try (BufferedReader listReader = new BufferedReader(new FileReader(clSourcesPath))) {
String line;
//Copy the files to a temporary dir
while ((line = listReader.readLine()) != null) {
if (!line.startsWith("#") && line.length() > 0) {
clsrc.add(line);
}
}
} finally {
}
try (PrintWriter writer = new PrintWriter(outfile, "UTF-8")) {
stitch(infile, writer, clsrc);
} finally {
ShaSigner.sign(outfile, new JULLogger(), true);
}
} else {
System.err.println("Input file is invalid: " + infile);
System.exit(2);
}
}
} |
package com.softserverinc.edu.entities;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.persistence.*;
import java.util.Date;
@Entity
public class WorkLog {
@Id
@GeneratedValue
@Column(unique = true, nullable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "issueId" ,referencedColumnName = "id", nullable = false)
private Issue issue;
@ManyToOne
@JoinColumn(name = "userId", referencedColumnName = "id", nullable = false)
private User user;
@Column(nullable = false)
private Date time;
@Column(name = "amount")
private Long amount;
public WorkLog() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Issue getIssue() {
return issue;
}
public void setIssueId(Issue issueId) {
this.issue = issueId;
}
public User getUserId() {
return user;
}
public void setUserId(User userId) {
this.user = userId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
} |
package com.stackmob.customcode;
import com.stackmob.core.InvalidSchemaException;
import com.stackmob.core.DatastoreException;
import com.stackmob.core.customcode.CustomCodeMethod;
import com.stackmob.core.rest.ProcessedAPIRequest;
import com.stackmob.core.rest.ResponseToProcess;
import com.stackmob.sdkapi.SDKServiceProvider;
import com.stackmob.sdkapi.*;
import java.net.HttpURLConnection;
import java.util.*;
import com.stripe.model.Customer;
public class CreateCustomer implements CustomCodeMethod {
@Override
public String getMethodName() {
return "createCustomer";
}
@Override
public List<String> getParams() {
return Arrays.asList("token", "username");
}
@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
DataService ds = serviceProvider.getDataService();
List<SMCondition> query = new ArrayList<SMCondition>();
Map<String, List<SMObject>> results = new HashMap<String, List<SMObject>>();
String username = request.getParams().get("username");
try {
query.add(new SMEquals("username", new SMString(username)));
results.put("results", ds.readObjects("pnuser", query));
} catch (InvalidSchemaException ise) {
} catch (DatastoreException dse) {}
return new ResponseToProcess(HttpURLConnection.HTTP_OK, results);
}
} |
package com.tterrag.k9.mappings.srg;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.tterrag.k9.mappings.MappingType;
import com.tterrag.k9.mappings.NameType;
import com.tterrag.k9.mappings.Parser;
import com.tterrag.k9.mappings.SignatureHelper;
import com.tterrag.k9.util.annotation.NonNull;
import com.tterrag.k9.util.annotation.Nullable;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class TsrgParser implements Parser<ZipFile, SrgMapping> {
private static final SignatureHelper sigHelper = new SignatureHelper();
private final SrgDatabase db;
@Override
public List<SrgMapping> parse(ZipFile zip) throws IOException {
Set<String> staticMethods;
List<String> lines;
try {
ZipEntry staticMethodsEntry = zip.getEntry("config/static_methods.txt");
// This file no longer exists in tsrgv2 versions (starting at 1.17)
if (staticMethodsEntry != null) {
staticMethods = Sets.newHashSet(IOUtils.readLines(zip.getInputStream(staticMethodsEntry), Charsets.UTF_8));
} else {
staticMethods = Collections.emptySet();
}
lines = IOUtils.readLines(zip.getInputStream(zip.getEntry("config/joined.tsrg")), Charsets.UTF_8);
} finally {
zip.close();
}
List<SrgMapping> ret = new ArrayList<>();
SrgMapping currentClass = null;
int fieldNumber = 2;
for (String line : lines) {
SrgMapping mapping;
if (line.startsWith("tsrg2 ")) {
// TSRGv2 support, skip header line and check that this is standard name set
if (!line.startsWith("tsrg2 obf srg")) {
throw new UnsupportedOperationException("Custom names in tsrgv2 is not supported yet");
}
// So we can support extra names on the end, e.g. "obf srg id" which is present in newer MCPConfig exports
fieldNumber = line.split(" ").length - 1;
continue;
}
if (!line.startsWith("\t")) {
String[] names = line.split(" ");
mapping = currentClass = new SrgMapping(db, MappingType.CLASS, names[0], names[1], null, null, null);
} else if (!line.startsWith("\t\t")) {
String[] data = line.substring(1).split(" ");
if (data.length == fieldNumber) {
mapping = new SrgMapping(db, MappingType.FIELD, data[0], data[1], null, null, currentClass.getIntermediate());
} else {
// TSRGv2 Support
MappingType type = data[1].startsWith("(") ? MappingType.METHOD : MappingType.FIELD;
mapping = new SrgMapping(db, type, data[0], data[2], data[1], null, currentClass.getIntermediate()) {
private @Nullable String srgDesc;
@Override
public @NonNull String getIntermediateDesc() {
if (srgDesc == null) {
srgDesc = sigHelper.mapSignature(NameType.INTERMEDIATE, getOriginalDesc(), this, db);
}
return srgDesc;
}
};
if (staticMethods.contains(data[2])) {
mapping.setStatic(true);
}
}
} else {
if (line.trim().equals("static")) {
// Mark the previous method mapping as static
ret.get(ret.size() - 1).setStatic(true);
}
// NO-OP (params)
continue;
}
ret.add(mapping);
}
return ret;
}
} |
package com.wrapper.spotify;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.exceptions.detailed.*;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.cache.CacheResponseStatus;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Level;
public class SpotifyHttpManager implements IHttpManager {
private static final int DEFAULT_CACHE_MAX_ENTRIES = 1000;
private static final int DEFAULT_CACHE_MAX_OBJECT_SIZE = 8192;
private final HttpHost proxy;
private final UsernamePasswordCredentials proxyCredentials;
private final Integer cacheMaxEntries;
private final Integer cacheMaxObjectSize;
private static CloseableHttpClient httpClient = CachingHttpClients.custom().build();
/**
* Construct a new SpotifyHttpManager instance.
*
* @param builder The builder.
*/
public SpotifyHttpManager(Builder builder) {
this.proxy = builder.proxy;
this.proxyCredentials = builder.proxyCredentials;
this.cacheMaxEntries = builder.cacheMaxEntries;
this.cacheMaxObjectSize = builder.cacheMaxObjectSize;
CacheConfig cacheConfig = CacheConfig.custom()
.setMaxCacheEntries(cacheMaxEntries != null ? cacheMaxEntries : DEFAULT_CACHE_MAX_ENTRIES)
.setMaxObjectSize(cacheMaxEntries != null ? cacheMaxEntries : DEFAULT_CACHE_MAX_OBJECT_SIZE)
.setSharedCache(false)
.build();
ConnectionConfig connectionConfig = ConnectionConfig
.custom()
.setCharset(Charset.forName("UTF-8"))
.build();
new BasicCredentialsProvider();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (proxy != null) {
credentialsProvider.setCredentials(
new AuthScope(proxy.getHostName(), proxy.getPort(), null, proxy.getSchemeName()),
proxyCredentials
);
}
RequestConfig requestConfig = RequestConfig
.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setProxy(proxy)
.build();
httpClient = CachingHttpClients
.custom()
.setCacheConfig(cacheConfig)
.setDefaultConnectionConfig(connectionConfig)
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.build();
}
public HttpHost getProxy() {
return proxy;
}
public UsernamePasswordCredentials getProxyCredentials() {
return proxyCredentials;
}
public Integer getCacheMaxEntries() {
return cacheMaxEntries;
}
public Integer getCacheMaxObjectSize() {
return cacheMaxObjectSize;
}
@Override
public String get(URI uri, Header[] headers) throws
IOException,
SpotifyWebApiException {
assert (uri != null);
assert (headers != null);
final HttpGet httpGet = new HttpGet();
httpGet.setURI(uri);
httpGet.setHeaders(headers);
String responseBody = getResponseBody(execute(httpGet));
httpGet.releaseConnection();
return responseBody;
}
@Override
public String post(URI uri, Header[] headers, List<NameValuePair> postParameters) throws
IOException,
SpotifyWebApiException {
assert (uri != null);
assert (headers != null);
assert (postParameters != null);
final HttpPost httpPost = new HttpPost();
httpPost.setURI(uri);
httpPost.setHeaders(headers);
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
String responseBody = getResponseBody(execute(httpPost));
httpPost.releaseConnection();
return responseBody;
}
@Override
public String put(URI uri, Header[] headers, List<NameValuePair> putParameters) throws
IOException,
SpotifyWebApiException {
assert (uri != null);
assert (headers != null);
assert (putParameters != null);
final HttpPut httpPut = new HttpPut();
httpPut.setURI(uri);
httpPut.setHeaders(headers);
httpPut.setEntity(new UrlEncodedFormEntity(putParameters));
String responseBody = getResponseBody(execute(httpPut));
httpPut.releaseConnection();
return responseBody;
}
@Override
public String delete(URI uri, Header[] headers) throws
IOException,
SpotifyWebApiException {
assert (uri != null);
assert (headers != null);
final HttpDelete httpDelete = new HttpDelete();
httpDelete.setURI(uri);
httpDelete.setHeaders(headers);
String responseBody = getResponseBody(execute(httpDelete));
httpDelete.releaseConnection();
return responseBody;
}
private HttpResponse execute(HttpRequestBase method) throws
IOException {
HttpCacheContext context = HttpCacheContext.create();
HttpResponse response = httpClient.execute(method, context);
try {
CacheResponseStatus responseStatus = context.getCacheResponseStatus();
switch (responseStatus) {
case CACHE_HIT:
SpotifyApi.LOGGER.log(
Level.CONFIG,
"A response was generated from the cache with no requests sent upstream");
break;
case CACHE_MODULE_RESPONSE:
SpotifyApi.LOGGER.log(
Level.CONFIG,
"The response was generated directly by the caching module");
break;
case CACHE_MISS:
SpotifyApi.LOGGER.log(
Level.CONFIG,
"The response came from an upstream server");
break;
case VALIDATED:
SpotifyApi.LOGGER.log(
Level.CONFIG,
"The response was generated from the cache after validating the entry with the origin server");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getResponseBody(HttpResponse httpResponse) throws
IOException,
SpotifyWebApiException {
final StatusLine statusLine = httpResponse.getStatusLine();
final String responseBody = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
final JsonObject jsonObject = new JsonParser().parse(responseBody).getAsJsonObject();
final String errorMessage;
if (jsonObject.has("error") && jsonObject.get("error").getAsJsonObject().has("message")) {
errorMessage = jsonObject.getAsJsonObject("error").get("message").getAsString();
} else {
errorMessage = statusLine.getReasonPhrase();
}
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK:
return responseBody;
case HttpStatus.SC_CREATED:
return responseBody;
case HttpStatus.SC_ACCEPTED:
return responseBody;
case HttpStatus.SC_NO_CONTENT:
throw new NoContentException(statusLine.getReasonPhrase());
case HttpStatus.SC_NOT_MODIFIED:
return responseBody;
case HttpStatus.SC_BAD_REQUEST:
throw new BadRequestException(errorMessage);
case HttpStatus.SC_UNAUTHORIZED:
throw new UnauthorizedException(errorMessage);
case HttpStatus.SC_FORBIDDEN:
throw new ForbiddenException(errorMessage);
case HttpStatus.SC_NOT_FOUND:
throw new NotFoundException(errorMessage);
case 429: // TOO_MANY_REQUESTS (additional status code, RFC 6585)
throw new TooManyRequestsException(errorMessage);
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
throw new InternalServerErrorException(errorMessage);
case HttpStatus.SC_BAD_GATEWAY:
throw new BadGatewayException(errorMessage);
case HttpStatus.SC_SERVICE_UNAVAILABLE:
throw new ServiceUnavailableException(errorMessage);
default:
return responseBody;
}
}
public static class Builder {
private HttpHost proxy;
private UsernamePasswordCredentials proxyCredentials;
private Integer cacheMaxEntries;
private Integer cacheMaxObjectSize;
public Builder setProxy(HttpHost proxy) {
this.proxy = proxy;
return this;
}
public Builder setProxyCredentials(UsernamePasswordCredentials proxyCredentials) {
this.proxyCredentials = proxyCredentials;
return this;
}
public Builder setCacheMaxEntries(Integer cacheMaxEntries) {
this.cacheMaxEntries = cacheMaxEntries;
return this;
}
public Builder setCacheMaxObjectSize(Integer cacheMaxObjectSize) {
this.cacheMaxObjectSize = cacheMaxObjectSize;
return this;
}
public SpotifyHttpManager build() {
return new SpotifyHttpManager(this);
}
}
} |
package com.xiaogua.better.file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
public class FileCommonUtil extends org.apache.commons.io.FileUtils {
public static String getSystemLineSeparator() {
return System.getProperty("line.separator", "\n");
}
/**
* BufferedReader
*/
public static BufferedReader getBufferedReader(String filePath, String encoding) throws Exception {
return new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding));
}
/**
* BufferedWriter
*/
public BufferedWriter getBufferedWriter(String filePath, String encoding) throws Exception {
return getBufferedWriter(filePath, encoding, false);
}
/**
* BufferedWriter
*/
public BufferedWriter getBufferedWriter(String filePath, String encoding,boolean append) throws Exception {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath,append), encoding);
BufferedWriter bw = new BufferedWriter(osw);
return bw;
}
public static void cleanFileContent(String filePath) {
cleanFileContent(new File(filePath));
}
public static void cleanFileContent(File file) {
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(new byte[0]);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(out);
}
}
public static void appendContentToFile(String filePath, String content) {
FileWriter writer = null;
try {
writer = new FileWriter(filePath, true);
writer.write(content);
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(writer);
}
}
public static void appendContentToFile(String fileName, String content, String encoding) {
RandomAccessFile randomFile = null;
try {
if (encoding == null) {
encoding = "utf-8";
}
randomFile = new RandomAccessFile(fileName, "rw");
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.write(content.getBytes(encoding));
randomFile.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(randomFile);
}
}
/**
* txt
*/
public static String getFileExtension(String filePath) {
return FilenameUtils.getExtension(filePath);
}
/**
* e:/test_tmp/sys.xmlsys
*/
public static String getFileBaseName(String filePath) {
return FilenameUtils.getBaseName(filePath);
}
/**
* sys.xml
*/
public static String getFileName(String filePath) {
return FilenameUtils.getName(filePath);
}
/**
* , e:/test_tmp/sys.xmle:/test_tmp/
*/
public static String getFullPathNoFile(String filePath) {
return FilenameUtils.getFullPath(filePath);
}
/**
* ,, e:/test_tmp/sys.xmle:/test_tmp
*/
public static String getFullPathNoEndSeparator(String filePath) {
return FilenameUtils.getFullPathNoEndSeparator(filePath);
}
public static boolean isEndOfExtension(String filePath, String suffix) {
if (filePath == null || suffix == null) {
return false;
}
return FilenameUtils.isExtension(filePath, suffix);
}
public static boolean isEndOfExtension(String filePath, String[] suffixArr) {
return isEndOfExtension(filePath, suffixArr, false);
}
public static boolean isEndOfExtension(String filePath, String[] suffixArr, boolean ignoreCase) {
if (filePath == null) {
return false;
}
if (suffixArr == null || suffixArr.length == 0) {
return false;
}
if (ignoreCase) {
filePath = filePath.toLowerCase();
for (int i = 0, len = suffixArr.length; i < len; i++) {
suffixArr[i] = (suffixArr[i] == null ? null : suffixArr[i].toLowerCase());
}
}
return FilenameUtils.isExtension(filePath, suffixArr);
}
/**
* e:/test_tmp/sys.xml e:/test_tmp/sys
*/
public static String removeExtension(String filePath) {
return FilenameUtils.removeExtension(filePath);
}
/**
*
*
* @param size
* @return
*/
public static String getReadableSize(long size) {
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
final int unitIndex = (int) (Math.log10(size) / 3);
final double unitValue = 1 << (unitIndex * 10);
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
return readableSize;
}
/**
*
*
* @param filename
* @return
* @throws IOException
*/
public static int getFileTotalLine(String filename) throws Exception {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
/**
*
*
* @param filePath
* @return
*/
public static String getFileLastLine(String filePath) {
RandomAccessFile raf;
String lastLine = "";
try {
raf = new RandomAccessFile(filePath, "r");
long len = raf.length();
if (len != 0L) {
long pos = len - 1;
while (pos > 0) {
pos
raf.seek(pos);
if (raf.readByte() == '\n') {
lastLine = raf.readLine();
break;
}
}
}
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
return lastLine;
}
/**
*
*
* @param filePath
* @param fileSize
* @throws Exception
*/
public static void fastCreateBigFile(String filePath, int fileSize) throws Exception {
RandomAccessFile r = new RandomAccessFile(filePath, "rw");
r.setLength(fileSize);
r.close();
}
/**
*
*
* @param file
* @throws IOException
*/
public static List<File> getFileListByDFS(File file) throws IOException {
Stack<File> stack = new Stack<File>();
stack.push(file);
File fileInStack = null;
List<File> fileList = new ArrayList<File>();
while (!stack.isEmpty()) {
fileInStack = stack.pop();
File[] files = fileInStack.listFiles();
for (File eachFile : files) {
if (eachFile.isFile()) {
fileList.add(eachFile);
} else {
stack.push(eachFile);
}
}
}
return fileList;
}
/**
*
*
* @param file
* @throws IOException
*/
public static List<File> getFileListByBFS(File file) throws IOException {
Queue<File> queue = new LinkedList<File>();
queue.offer(file);
File fileInQueue = null;
List<File> fileList = new ArrayList<File>();
while (queue.size() > 0) {
fileInQueue = queue.poll();
File[] files = fileInQueue.listFiles();
for (File eachFile : files) {
if (eachFile.isFile()) {
fileList.add(eachFile);
} else {
queue.offer(eachFile);
}
}
}
return fileList;
}
} |
package de.linkvt.bachelor.config;
import de.linkvt.bachelor.web.converters.message.FunctionalSyntaxHttpMessageConverter;
import de.linkvt.bachelor.web.converters.message.ManchesterSyntaxHttpMessageConverter;
import de.linkvt.bachelor.web.converters.message.OntologySyntax;
import de.linkvt.bachelor.web.converters.message.OwlXmlHttpMessageConverter;
import de.linkvt.bachelor.web.converters.message.RdfXmlOntologyHttpMessageConverter;
import de.linkvt.bachelor.web.converters.message.TurtleOntologyHttpMessageConverter;
import de.linkvt.bachelor.web.converters.parameter.StringToFeaturesConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Configures the web module.
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private StringToFeaturesConverter converter;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(converter);
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true)
.favorParameter(true)
.ignoreUnknownPathExtensions(false)
.defaultContentType(MediaType.TEXT_PLAIN)
.mediaType("owx", OntologySyntax.OWL_XML.getMediaType())
.mediaType("owl", OntologySyntax.RDF_XML.getMediaType())
.mediaType("rdf", OntologySyntax.RDF_XML.getMediaType())
.mediaType("xml", OntologySyntax.RDF_XML.getMediaType())
.mediaType("ofn", OntologySyntax.FUNCTIONAL.getMediaType())
.mediaType("omn", OntologySyntax.MANCHESTER.getMediaType())
.mediaType("ttl", OntologySyntax.TURTLE.getMediaType());
}
@Bean
public HttpMessageConverters customConverters() {
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new FunctionalSyntaxHttpMessageConverter());
converters.add(new ManchesterSyntaxHttpMessageConverter());
converters.add(new OwlXmlHttpMessageConverter());
converters.add(new RdfXmlOntologyHttpMessageConverter());
converters.add(new TurtleOntologyHttpMessageConverter());
return new HttpMessageConverters(converters);
}
} |
package edu.columbia.tjw.item.algo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Code cloned from streaminer project, and updated to use more primitives for performance reasons.
* <p>
* Original javadoc follows.
* <p>
* This class is an implementation of the Greenwald-Khanna algorithm for computing
* epsilon-approximate quantiles of large data sets. In its pure form it is an offline
* algorithm. But it is used as a black box by many online algorithms for computing
* epsilon-approximate quantiles on data streams.<br>
* Our implementation widely adapts the original idea published by <i>Michael Greenwald
* </i> and <i>Sanjeev Khanna</i> in their paper <i>"Space-Efficient Online Computation
* of Quantile Summaries"</i>. Contrary to their idea this implementation uses a list
* rather than a tree structure to maintain the elements.
*
* @author Markus Kokott, Carsten Przyluczky
*/
public class GKQuantiles implements Serializable
{
private static final long serialVersionUID = 0x3b9df13d1769c5bdL;
/**
* This value specifies the error bound.
*/
private final double _epsilon;
private List<QuantileBlock> summary;
private double minimum;
private double maximum;
private int stepsUntilMerge;
/**
* GK needs 1 / (2 * epsilon) elements to complete it's initial phase
*/
private boolean initialPhase;
private int count;
public GKQuantiles()
{
this(0.05);
}
/**
* Creates a new GKQuantiles object that computes epsilon-approximate quantiles.
*
* @param epsilon_ The maximum error bound for quantile estimation.
*/
public GKQuantiles(double epsilon_)
{
if (!(epsilon_ > 0 && epsilon_ < 1))
{
throw new RuntimeException("Epsilon must be in [0, 1]");
}
this._epsilon = epsilon_;
this.minimum = Double.MAX_VALUE;
this.maximum = Double.MIN_VALUE;
double mergingSteps = Math.floor(1.0 / (2.0 * _epsilon));
this.stepsUntilMerge = (int) mergingSteps;
this.summary = new ArrayList<QuantileBlock>();
this.count = 0;
this.initialPhase = true;
}
public void offer(double value)
{
insertItem(value);
incrementCount();
if (count % stepsUntilMerge == 0 && !initialPhase)
{
compress();
}
}
/**
* Estimates appropriate quantiles (i.e. values that holds epsilon accuracy). Note that if
* the query parameter doesn't lay in [0,1] <code>Double.NaN</code> is returned! The same
* result will be returned if an empty instance of GK is queried.
*
* @param q a <code>float</code> value
* @return an estimated quantile represented by a {@link Double}. Will return {@link Double#NaN}
* if <code>phi</code> isn't between 0 and 1 or this instance of <code>GKQuantiles</code> is empty.
*/
public double getQuantile(double q)
{
if (count == 0 || q < 0 || q > 1)
{
return Double.NaN;
}
if (count == 1)
{
return minimum;
}
if (count == 2)
{
if (q < 0.5)
{
return minimum;
}
if (q >= 0.5)
{
return maximum;
}
}
int wantedRank = (int) (q * count);
int currentMinRank = 0;
int currentMaxRank = 0;
double tolerance = (_epsilon * count);
// if the wanted range is as most epsilon * count ranks smaller than the maximum the maximum
// will always be an appropriate estimate
if (wantedRank > count - tolerance)
{
return maximum;
}
// if the wanted range is as most epsilon * count ranks greater than the minimum the minimum
// will always be an appropriate estimate
if (wantedRank < tolerance)
{
return minimum;
}
QuantileBlock lastTuple = summary.get(0);
// usually a range is estimated during this loop. it's element's value will be returned
for (QuantileBlock nextBlock : summary)
{
currentMinRank += nextBlock.getOffset();
currentMaxRank = currentMinRank + nextBlock.getRange();
if (currentMaxRank - wantedRank <= tolerance)
{
lastTuple = nextBlock;
if (wantedRank - currentMinRank <= tolerance)
{
return nextBlock.getValue();
}
}
}
return lastTuple.getValue();
}
/**
* Checks whether <code>item</code> is a new extreme value (i.e. minimum or maximum) or lays between those values
* and calls the appropriate insert method.
*
* @param item {@link Double} value of current element
*/
private void insertItem(double item)
{
if (item < minimum)
{
insertAsNewMinimum(item);
return;
}
if (item >= maximum)
{
insertAsNewMaximum(item);
return;
}
insertInBetween(item);
}
/**
* This method will be called every time an element arrives whose value is smaller than the value
* of the current minimum. Contrary to "normal" elements, the minimum's range have to be zero.
*
* @param item - new element with a {@link Double} value smaller than the current minimum of the summary.
*/
private void insertAsNewMinimum(double item)
{
minimum = item;
QuantileBlock newTuple = new QuantileBlock(item, 1, 0);
summary.add(0, newTuple);
}
/**
* This method will be called every time an element arrives whose value is greater than the value
* of the current maximum. Contrary to "normal" elements, the maximum's range have to be zero.
*
* @param item - new element with a {@link Double} value greater than the current maximum of the summary.
*/
private void insertAsNewMaximum(double item)
{
if (item == maximum)
{
QuantileBlock newTuple = new QuantileBlock(item, 1,
computeRangeForNewTuple(summary.get(summary.size() - 1)));
summary.add(summary.size() - 2, newTuple);
}
else
{
maximum = item;
QuantileBlock newTuple = new QuantileBlock(item, 1, 0);
summary.add(newTuple);
}
}
/**
* Every time a new element gets processed this method is called to insert this element into
* the summary. During initial phase element's ranges have to be zero. After this phase every
* new element's range depends on its successor.
*
* @param item - a new arrived element represented by a {@link Double} value.
*/
private void insertInBetween(double item)
{
QuantileBlock newTuple = new QuantileBlock(item, 1, 0);
for (int i = 0; i < summary.size() - 1; i++)
{
QuantileBlock current = summary.get(i);
QuantileBlock next = summary.get(i + 1);
if (item >= current.getValue() && item < next.getValue())
{
// while GK have seen less than 1 / (2*epsilon) elements, all elements must have an
// offset of 0
if (!initialPhase)
{
newTuple.setRange(computeRangeForNewTuple(next));
}
summary.add(i + 1, newTuple);
return;
}
}
}
/**
* Increments <code>count</code> and ends the initial phase if enough elements have been seen.
*/
private void incrementCount()
{
count++;
if (count == stepsUntilMerge)
{
initialPhase = false;
}
}
/**
* Due to space efficiency the summary is compressed periodically
*/
private void compress()
{
if (this.summary.size() < 2)
{
// We don't compress if there's nothing to compress.
return;
}
List<List<QuantileBlock>> partitions = getPartitionsOfSummary();
List<QuantileBlock> mergedSummary = new ArrayList<QuantileBlock>();
// just merge tuples per partition and concatenate the single resulting working sets
mergedSummary.addAll(partitions.get(partitions.size() - 1));
for (int i = partitions.size() - 2; i > 0; i
{
mergedSummary.addAll(mergeWorkingSet(partitions.get(i)));
}
mergedSummary.addAll(partitions.get(0));
mergedSummary = sortWorkingSet(mergedSummary);
summary = mergedSummary;
}
private List<QuantileBlock> mergeWorkingSet(List<QuantileBlock> workingSet)
{
// recursion stops here
if (workingSet.size() < 2)
{
return workingSet;
}
LinkedList<QuantileBlock> mergedWorkingSet = new LinkedList<QuantileBlock>(); // resulting working
// set
LinkedList<QuantileBlock> currentWorkingSet = new LinkedList<QuantileBlock>(); // elements for
// this step of recursion
LinkedList<QuantileBlock> remainingWorkingSet = new LinkedList<QuantileBlock>(); // remaining elements
// after this step
// of recursion
remainingWorkingSet.addAll(workingSet);
int index = 1;
int bandOfChildren = computeBandOfTuple(workingSet.get(0));
int bandOfParent = computeBandOfTuple(workingSet.get(index));
currentWorkingSet.add(workingSet.get(0));
remainingWorkingSet.removeFirst();
// we are looking for the next tuple that have a greater band than the first element because that
// element will be the limit for the first element to get merged into
while (bandOfChildren == bandOfParent && workingSet.size() - 1 > index)
{
// the working set will be partitioned into a working set for the current step of recursion and
// a partition that contains all elements that have to be processed in later steps
currentWorkingSet.add(workingSet.get(index));
remainingWorkingSet.remove(workingSet.get(index));
index++;
bandOfParent = computeBandOfTuple(workingSet.get(index));
}
QuantileBlock parent = workingSet.get(index);
// there is no real parent. all elements have the same band
if (bandOfParent == bandOfChildren)
{
currentWorkingSet.add(parent);
mergedWorkingSet.addAll(mergeSiblings(currentWorkingSet));
return mergedWorkingSet;
}
int capacityOfParent = computeCapacityOfTuple(parent);
// an element can be merged into it's parent if the resulting tuple isn't full (i.e. capacityOfParent > 1
// after merging)
while (capacityOfParent > currentWorkingSet.getLast().getOffset() && currentWorkingSet.size() > 1)
{
merge(currentWorkingSet.getLast(), parent);
currentWorkingSet.removeLast();
capacityOfParent = computeCapacityOfTuple(parent);
}
// checking whether all children were merged into parent or some were left over
if (currentWorkingSet.isEmpty())
{
mergedWorkingSet.addAll(mergeWorkingSet(remainingWorkingSet));
}
// if there are some children left, some of them can probably be merged into siblings.
// if there is any child left over, parent can't be merged into any other tuple, so it must be removed
// from the elements in the remaining working set.
else
{
remainingWorkingSet.remove(parent);
mergedWorkingSet.addAll(mergeSiblings(currentWorkingSet));
mergedWorkingSet.add(parent);
mergedWorkingSet.addAll(mergeWorkingSet(remainingWorkingSet));
}
return mergedWorkingSet;
}
/**
* this method merges elements that have the same band
*
* @param workingSet - a {@link LinkedList} of {@link QuantileBlock}
* @return a {@link LinkedList} of {@link QuantileBlock} with smallest possible size in respect to
* GKs merging operation.
*/
private LinkedList<QuantileBlock> mergeSiblings(LinkedList<QuantileBlock> workingSet)
{
// nothing left to merge
if (workingSet.size() < 2)
{
return workingSet;
}
LinkedList<QuantileBlock> mergedSiblings = new LinkedList<QuantileBlock>();
// it is only possible to merge an element into a sibling, if this sibling is the element's
// direct neighbor to the right
QuantileBlock lastSibling = workingSet.getLast();
workingSet.removeLast();
boolean canStillMerge = true;
// as long as the rightmost element can absorb elements, it will absorb his sibling to the left
while (canStillMerge && !workingSet.isEmpty())
{
if (this.areMergeable(workingSet.getLast(), lastSibling))
{
merge(workingSet.getLast(), lastSibling);
workingSet.removeLast();
}
else
{
canStillMerge = false;
}
}
mergedSiblings.add(lastSibling);
// recursion
mergedSiblings.addAll(mergeSiblings(workingSet));
return mergedSiblings;
}
/**
* call this method to merge the element <code>left</code> into the element <code>right</code>.
* Please note, that only elements with smaller value and a band not greater than <code>right
* </code> can be element <code>left</code>.
*
* @param left - element the will be deleted after merging
* @param right - element that will contain the offset of element <code>left</code> after merging
*/
private void merge(QuantileBlock left, QuantileBlock right)
{
right.setOffset(right.getOffset() + left.getOffset());
}
/**
* The range of an element depends on range and offset of it's succeeding element.
* This methods computes the current element's range.
*
* @return range of current element as {@link Integer} value
*/
private int computeRangeForNewTuple(QuantileBlock successor)
{
if (initialPhase)
{
return 0;
}
//this is how it's done during algorithm detail in the paper
double range = 2.0 * _epsilon * count;
range = Math.floor(range);
//this is the more adequate version presented at section "empirical measurements"
int successorRange = successor.getRange();
int successorOffset = successor.getOffset();
if (successorRange + successorOffset - 1 >= 0)
{
return (successorRange + successorOffset - 1);
}
return (int) range;
}
/**
* Partitions a list into {@link LinkedList}s of {@link QuantileBlock}, so that bands of elements
* in a single {@link LinkedList} are monotonically increasing.
*
* @return a {@link LinkedList} containing {@link LinkedList}s of {@link Double} which are
* the partitions of {@link #summary}
*/
private List<List<QuantileBlock>> getPartitionsOfSummary()
{
List<List<QuantileBlock>> partitions = new LinkedList<List<QuantileBlock>>();
List<QuantileBlock> workingSet = summary;
LinkedList<QuantileBlock> currentPartition = new LinkedList<QuantileBlock>();
QuantileBlock lastTuple;
QuantileBlock lastButOneTuple;
// assuring that the minimum and maximum won't appear in a partition with other elements
QuantileBlock minimum = workingSet.get(0);
QuantileBlock maximum = workingSet.get(workingSet.size() - 1);
workingSet.remove(0);
workingSet.remove(workingSet.size() - 1);
// adding the minimum as the first element into partitions
currentPartition = new LinkedList<QuantileBlock>();
currentPartition.add(minimum);
partitions.add(currentPartition);
currentPartition = new LinkedList<QuantileBlock>();
// nothing left to partitioning
if (workingSet.size() < 2)
{
partitions.add(workingSet);
// adding the maximum as the very last element into partitions
currentPartition = new LinkedList<QuantileBlock>();
currentPartition.add(maximum);
partitions.add(currentPartition);
return partitions;
}
// we process the working set from the very last element to the very first one
while (workingSet.size() >= 2)
{
lastTuple = workingSet.get(workingSet.size() - 1);
lastButOneTuple = workingSet.get(workingSet.size() - 2);
currentPartition.addFirst(lastTuple);
// every time we find an element whose band is greater than the current one the current partition
// ended and we have to add a new partition to the resulting list
if (isPartitionBorder(lastButOneTuple, lastTuple))
{
partitions.add(currentPartition);
currentPartition = new LinkedList<QuantileBlock>();
}
else
{
// here got's the last element inserted into an partition
if (workingSet.size() == 2)
{
currentPartition.addFirst(lastButOneTuple);
}
}
workingSet.remove(workingSet.size() - 1);
}
partitions.add(currentPartition);
// adding the maximum as a partition of it's own at the very last position
currentPartition = new LinkedList<QuantileBlock>();
currentPartition.add(maximum);
partitions.add(currentPartition);
return partitions;
}
/**
* Call this method to get the current capacity of an element.
*
* @param tuple - a {@link QuantileBlock}
* @return {@link Integer} value representing the <code>tuple</code>'s capacity
*/
private int computeCapacityOfTuple(QuantileBlock tuple)
{
int offset = tuple.getOffset();
double currentMaxCapacity = Math.floor(2.0 * _epsilon * count);
return (int) (currentMaxCapacity - offset);
}
/**
* A tuple's band depend on the number of seen elements (<code>count</code>) and the
* tuple's range.
* <ul>
* <li> While GK hasn't finished it's initial phase, all elements have to be put into a
* band of their own. This is done using a band -1.
* <li> If count and range are logarithmically equal the tuple's band will be 0
* <li> Else the tuple's band will be a value between 1 and <i>log(2*epsilon*count)</i>
* </ul>
* Please refer to the paper if you are interested in the formula for computing bands.
*
* @param tuple - a {@link QuantileBlock}
* @return {@link Integer} value specifying <code>tuple</code>'s band
*/
private int computeBandOfTuple(QuantileBlock tuple)
{
double p = Math.floor(2 * _epsilon * count);
// this will be true for new tuples
if (areLogarithmicallyEqual(p, tuple.getRange()))
{
return 0;
}
// initial phase
if (tuple.getRange() == 0)
{
return -1;
}
int alpha = 0;
double lowerBound = 0d;
double upperBound = 0d;
while (alpha < (Math.log(p) / Math.log(2)))
{
alpha++;
int twoPowAlpha = 2 << alpha;
lowerBound = p - twoPowAlpha - (p % twoPowAlpha);
if (lowerBound <= tuple.getRange())
{
int twoPowAlphaM1 = 2 << (alpha - 1);
upperBound = p - twoPowAlphaM1 - (p % twoPowAlphaM1);
if (upperBound >= tuple.getRange())
{
return alpha;
}
}
}
return alpha;
}
/**
* Checks if two given values are logarithmically equal, i.e. the floored logarithm of
* <code>valueOne</code> equals the floored logarithm of <code>valueTwo</code>.
*
* @param valueOne - a {@link Double} representing a {@link QuantileBlock}s band
* @param valueTwo - a {@link Double} representing a {@link QuantileBlock}s band
* @return <code>true</code> if both values are logarithmically equal
*/
private boolean areLogarithmicallyEqual(double valueOne, double valueTwo)
{
return (Math.floor(Math.log(valueOne)) == Math.floor(Math.log(valueTwo)));
}
/**
* To check whether a pair of elements are mergeable or not you should use this method. Its
* decision takes into account the bands and values of the given elements.
*
* @param tuple The element that will be deleted after merging.
* @param parent The element that will absorb <code>tuple</code> during merge.
* @return <code>true</code> if given elements are mergeable or <code>false</code> else.
*/
private boolean areMergeable(QuantileBlock tuple, QuantileBlock parent)
{
int capacityOfParent = computeCapacityOfTuple(parent);
// return true if parent's capacity suffices to absorb tuple and tuple's band isn't greater than parent's
if (capacityOfParent > tuple.getOffset() && computeBandOfTuple(parent) >= computeBandOfTuple(tuple))
{
return true;
}
return false;
}
/**
* Bands of elements in a partition are monotonically increasing from the first to the last element.
* So a partition border is found if a preceding element has a greater band than the current
* element. This method checks this condition for given elements.
*
* @param left preceding element.
* @param right current element.
* @return <code>true</code> if a partition boarder exists between the given elements or <code>
* false</code> else.
*/
private boolean isPartitionBorder(QuantileBlock left, QuantileBlock right)
{
if (computeBandOfTuple(left) > computeBandOfTuple(right))
{
return true;
}
return false;
}
/**
* Sorts a {@link LinkedList} of {@link QuantileBlock}.
*
* @param workingSet - partitions of summary as a {@link LinkedList} of {@link QuantileBlock}.
* @return the given working set in ascending order.
*/
private static List<QuantileBlock> sortWorkingSet(List<QuantileBlock> workingSet)
{
List<QuantileBlock> sortedWorkingSet = new ArrayList<QuantileBlock>();
while (workingSet.size() > 1)
{
QuantileBlock currentMinimum = workingSet.get(0);
for (int i = 0; i < workingSet.size(); i++)
{
if (currentMinimum.getValue() > workingSet.get(i).getValue())
{
currentMinimum = workingSet.get(i);
}
}
workingSet.remove(currentMinimum);
sortedWorkingSet.add(currentMinimum);
}
sortedWorkingSet.add(workingSet.get(0));
return sortedWorkingSet;
}
public int getCount()
{
return this.count;
}
@Override
public String toString()
{
StringBuffer s = new StringBuffer();
s.append(getClass().getCanonicalName());
s.append(" {");
s.append(" epsilon=");
s.append(_epsilon);
s.append(" }");
return s.toString();
}
/**
* This is just a wrapper class to hold all needed informations of an element. It contains the following
* informations:
* <ul>
* <li><b>value</b>: the value of the element</li>
* <li><b>offset</b>: the difference between the least rank of this element and the rank of the preceding
* element.</li>
* <li><b>range</b>: the span between this elements least and most rank</li>
* <ul>
*/
private static final class QuantileBlock implements Serializable
{
private static final long serialVersionUID = 0x80ca623569742e28L;
private final double value;
private int offset;
private int range;
public QuantileBlock(Double value, Integer offset, Integer range)
{
this.value = value;
this.offset = offset;
this.range = range;
}
public double getValue()
{
return value;
}
public int getOffset()
{
return offset;
}
public void setOffset(int offset)
{
this.offset = offset;
}
public int getRange()
{
return range;
}
public void setRange(int range)
{
this.range = range;
}
@Override
public String toString()
{
String out = "( " + value + ", " + offset + ", " + range + " )";
return out;
}
}
} |
package edu.neu.ccs.pyramid.eval;
import java.util.stream.IntStream;
public class MicroMeasures extends LabelBasedMeasures {
/**
* Construct function: initialize each variables.
*
* @param numLabels
*/
public MicroMeasures(int numLabels) {
super(numLabels);
}
/**
* Returns the average Micro precision for all labels.
* @return average precision
*/
public double getPrecision() {
int tp = IntStream.of(truePositives).sum();
int fp = IntStream.of(falsePositives).sum();
int fn = IntStream.of(falseNegatives).sum();
return ConfusionMatrixMeasures.precision(tp,fp,fn);
}
/**
* Returns the average Micro recall for all labels.
* @return average recall
*/
public double getRecall() {
int tp = IntStream.of(truePositives).sum();
int fp = IntStream.of(falsePositives).sum();
int fn = IntStream.of(falseNegatives).sum();
return ConfusionMatrixMeasures.recall(tp,fp,fn);
}
/**
* Returns the average Micro specificity for all labels.
* @return average specificity
*/
public double getSpecificity() {
int tn = IntStream.of(trueNegatives).sum();
int fp = IntStream.of(falsePositives).sum();
int fn = IntStream.of(falseNegatives).sum();
return ConfusionMatrixMeasures.specificity(tn,fp,fn);
}
/**
* Returns the average Micro F score for all labels.
* @param beta
* @return average F score
*/
public double getFScore(double beta) {
int tp = IntStream.of(truePositives).sum();
int fp = IntStream.of(falsePositives).sum();
int fn = IntStream.of(falseNegatives).sum();
return ConfusionMatrixMeasures.fScore(tp,fp,fn,beta);
}
/**
* Returns the average Micro F1 score for all labels.
* @return average F1 score
*/
public double getF1Score() {
return getFScore(1.0);
}
@Override
public String toString() {
return "Micro-Precision: \t" + getPrecision() +
"\nMicro-Recall: \t" + getRecall() +
"\nMicro-Specificity: \t" + getSpecificity() +
"\nMicro-F1Score: \t" + getF1Score();
}
} |
package function.coverage.comparison;
import function.annotation.base.Gene;
import function.annotation.base.Exon;
import function.coverage.base.CoverageCommand;
import function.genotype.base.SampleManager;
import global.Data;
import utils.LogManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import utils.FormatManager;
import utils.MathManager;
/**
*
* @author qwang, nick
*/
public class ExonClean {
int totalBases = 0;
int totalCleanedBases = 0;
double caseCoverage = 0;
double ctrlCoverage = 0;
ArrayList<SortedExon> exonList = new ArrayList<>();
HashMap<String, SortedExon> cleanedExonMap = new HashMap<>();
public void addExon(String name, float caseAvg, float ctrlAvg, float absDiff, int regionSize) {
exonList.add(new SortedExon(name, caseAvg, ctrlAvg, absDiff, regionSize));
totalBases += regionSize;
}
private double getAllCoverage() {
return (caseCoverage * SampleManager.getCaseNum() + ctrlCoverage * SampleManager.getCtrlNum()) / SampleManager.getListSize();
}
protected double getCutoff() {
//make sure the list has included all data and sortd.
Collections.sort(exonList);
int i;
float cutoff;
float[] data = new float[exonList.size()];
float meandata = 0;
//calculate mean data
for (i = 0; i < data.length; i++) {
data[i] = exonList.get(i).getCovDiff();
meandata += data[i];
}
meandata /= data.length;
float total_variation = 0;
for (i = 0; i < data.length; i++) {
data[i] = (data[i] - meandata) * (data[i] - meandata);
total_variation += data[i];
}
data[0] /= total_variation;
for (i = 1; i < data.length; i++) {
data[i] = data[i - 1] + data[i] / total_variation;
}
for (i = 0; i < data.length; i++) {
data[i] = data[i] - (float) (i + 1) / (float) data.length;
}
int index = 0;
double max_value = Double.MIN_VALUE;
for (i = 0; i < data.length; i++) {
if (data[i] > max_value) {
max_value = data[i];
index = i;
}
}
cutoff = exonList.get(index).getCovDiff();
LogManager.writeAndPrint("\nThe automated cutoff value for absolute mean coverage difference for sites is " + Float.toString(cutoff));
if (CoverageCommand.exonCleanCutoff != Data.NO_FILTER) {
cutoff = CoverageCommand.exonCleanCutoff;
LogManager.writeAndPrint("User specified cutoff value "
+ FormatManager.getSixDegitDouble(cutoff) + " is applied instead.");
}
return cutoff;
}
public void initCleanedRegionMap() {
double cutoff = getCutoff();
for (SortedExon sortedRegion : exonList) {
if (sortedRegion.getCutoff() < cutoff
&& sortedRegion.getCaseAvg() + sortedRegion.getCtrlAvg() > 0) {
totalCleanedBases += sortedRegion.getLength();
ctrlCoverage += sortedRegion.getCtrlAvg() * sortedRegion.getLength();
caseCoverage += sortedRegion.getCaseAvg() * sortedRegion.getLength();
cleanedExonMap.put(sortedRegion.getName(), sortedRegion);
}
}
caseCoverage = MathManager.devide(caseCoverage, totalBases);
ctrlCoverage = MathManager.devide(ctrlCoverage, totalBases);
}
public String getCleanedGeneStrByExon(Gene gene) {
StringBuilder sb = new StringBuilder();
int size = 0;
sb.append(gene.getName());
sb.append(" ").append(gene.getChr()).append(" (");
boolean isFirst = true;
for (Exon exon : gene.getExonList()) {
String exonIdStr = gene.getName() + "_" + exon.getIdStr();
if (cleanedExonMap.containsKey(exonIdStr)) {
size += exon.getLength();
if (isFirst) {
isFirst = false;
} else {
sb.append(",");
}
sb.append(exon.getStartPosition());
sb.append("..").append(exon.getEndPosition());
}
}
sb.append(") ").append(size);
if (size > 0 && !gene.getChr().isEmpty()) {
return sb.toString();
} else {
return "";
}
}
public String getCleanedGeneSummaryStrByExon(Gene gene) {
int geneSize = 0;
double caseAvg = 0;
double ctrlAvg = 0;
for (Exon exon : gene.getExonList()) {
String regionIdStr = gene.getName() + "_" + exon.getIdStr();
SortedExon sortedExon = cleanedExonMap.get(regionIdStr);
if (sortedExon != null) {
geneSize += sortedExon.getLength();
caseAvg += (double) sortedExon.getLength() * sortedExon.getCaseAvg();
ctrlAvg += (double) sortedExon.getLength() * sortedExon.getCtrlAvg();
}
}
return getGeneStr(gene, geneSize, caseAvg, ctrlAvg);
}
private String getGeneStr(Gene gene, int geneSize, double caseAvg, double ctrlAvg) {
StringBuilder sb = new StringBuilder();
sb.append(gene.getName()).append(",");
sb.append(gene.getChr()).append(",");
sb.append(gene.getLength()).append(",");
caseAvg = MathManager.devide(caseAvg, geneSize);
ctrlAvg = MathManager.devide(ctrlAvg, geneSize);
sb.append(FormatManager.getSixDegitDouble(caseAvg)).append(",");
sb.append(FormatManager.getSixDegitDouble(ctrlAvg)).append(",");
double absDiff = MathManager.abs(caseAvg, ctrlAvg);
sb.append(FormatManager.getSixDegitDouble(absDiff)).append(",");
sb.append(geneSize);
return sb.toString();
}
public void outputLog() {
int numExonsTotal = exonList.size();
int numExonsPruned = numExonsTotal - cleanedExonMap.size();
LogManager.writeAndPrint("The number of exons before pruning is " + numExonsTotal);
LogManager.writeAndPrint("The number of exons after pruning is " + cleanedExonMap.size());
LogManager.writeAndPrint("The number of exons pruned is " + numExonsPruned);
double percentExonsPruned = (double) numExonsPruned / (double) numExonsTotal * 100;
LogManager.writeAndPrint("The % of exons pruned is "
+ FormatManager.getSixDegitDouble(percentExonsPruned) + "%");
LogManager.writeAndPrint("The total number of bases before pruning is "
+ FormatManager.getSixDegitDouble((double) totalBases / 1000000.0) + " MB");
LogManager.writeAndPrint("The total number of bases after pruning is "
+ FormatManager.getSixDegitDouble((double) totalCleanedBases / 1000000.0) + " MB");
LogManager.writeAndPrint("The % of bases pruned is "
+ FormatManager.getSixDegitDouble(100.0 - (double) totalCleanedBases / (double) totalBases * 100) + "%");
LogManager.writeAndPrint("The average coverage rate for all samples after pruning is "
+ FormatManager.getSixDegitDouble(getAllCoverage() * 100) + "%");
LogManager.writeAndPrint("The average number of bases well covered for all samples after pruning is "
+ FormatManager.getSixDegitDouble(getAllCoverage() * totalBases / 1000000.0) + " MB");
LogManager.writeAndPrint("The average coverage rate for cases after pruning is "
+ FormatManager.getSixDegitDouble(caseCoverage * 100) + "%");
LogManager.writeAndPrint("The average number of bases well covered for cases after pruning is "
+ FormatManager.getSixDegitDouble(caseCoverage * totalBases / 1000000.0) + " MB");
LogManager.writeAndPrint("The average coverage rate for controls after pruning is "
+ FormatManager.getSixDegitDouble(ctrlCoverage * 100) + "%");
LogManager.writeAndPrint("The average number of bases well covered for controls after pruning is "
+ FormatManager.getSixDegitDouble(ctrlCoverage * totalBases / 1000000.0) + " MB");
}
} |
package org.duracloud.sync;
import org.duracloud.sync.backup.SyncBackupManager;
import org.duracloud.sync.config.SyncToolConfig;
import org.duracloud.sync.config.SyncToolConfigParser;
import org.duracloud.sync.endpoint.DuraStoreChunkSyncEndpoint;
import org.duracloud.sync.endpoint.SyncEndpoint;
import org.duracloud.sync.mgmt.ChangedList;
import org.duracloud.sync.mgmt.StatusManager;
import org.duracloud.sync.mgmt.SyncManager;
import org.duracloud.sync.monitor.DirectoryUpdateMonitor;
import org.duracloud.sync.util.LogUtil;
import org.duracloud.sync.walker.DeleteChecker;
import org.duracloud.sync.walker.DirWalker;
import org.duracloud.sync.walker.RestartDirWalker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SyncTool {
private final Logger logger = LoggerFactory.getLogger(SyncTool.class);
private SyncToolConfig syncConfig;
private SyncManager syncManager;
private SyncBackupManager syncBackupManager;
private DirectoryUpdateMonitor dirMonitor;
private SyncEndpoint syncEndpoint;
private DirWalker dirWalker;
private LogUtil logUtil;
private SyncToolConfig processCommandLineArgs(String[] args) {
SyncToolConfigParser syncConfigParser = new SyncToolConfigParser();
syncConfig = syncConfigParser.processCommandLine(args);
return syncConfig;
}
/**
* Determines if the sync directory list has been changed since the
* previous run. If it has, a restart cannot occur.
* @return true if sync directories have not been changed, false otherwise
*/
private boolean restartPossible() {
SyncToolConfigParser syncConfigParser = new SyncToolConfigParser();
SyncToolConfig prevConfig =
syncConfigParser.retrievePrevConfig(syncConfig.getBackupDir());
if(prevConfig != null) {
return syncConfig.getSyncDirs().equals(prevConfig.getSyncDirs());
} else {
return false;
}
}
private void setupLogging(){
logUtil = new LogUtil();
logUtil.setupLogger(syncConfig.getBackupDir());
}
private void startSyncManager() {
syncEndpoint =
new DuraStoreChunkSyncEndpoint(syncConfig.getHost(),
syncConfig.getPort(),
syncConfig.getContext(),
syncConfig.getUsername(),
syncConfig.getPassword(),
syncConfig.getSpaceId(),
syncConfig.syncDeletes(),
syncConfig.getMaxFileSize());
syncManager = new SyncManager(syncConfig.getSyncDirs(),
syncEndpoint,
syncConfig.getNumThreads(),
syncConfig.getPollFrequency());
syncManager.beginSync();
}
private long startSyncBackupManager(boolean restart) {
syncBackupManager =
new SyncBackupManager(syncConfig.getBackupDir(),
syncConfig.getPollFrequency());
long lastBackup = 0;
if(restart) {
lastBackup = syncBackupManager.attemptRestart();
}
syncBackupManager.startupBackups();
return lastBackup;
}
private void startDirWalker() {
dirWalker = DirWalker.start(syncConfig.getSyncDirs());
}
private void startRestartDirWalker(long lastBackup) {
dirWalker = RestartDirWalker.start(syncConfig.getSyncDirs(), lastBackup);
}
private void startDeleteChecker() {
DeleteChecker.start(syncEndpoint.getFilesList(),
syncConfig.getSyncDirs());
}
private void startDirMonitor() {
dirMonitor = new DirectoryUpdateMonitor(syncConfig.getSyncDirs(),
syncConfig.getPollFrequency(),
syncConfig.syncDeletes());
dirMonitor.startMonitor();
}
private void listenForExit() {
StatusManager statusManager = StatusManager.getInstance();
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
boolean exit = false;
while(!exit) {
String input;
try {
input = br.readLine();
if(input.equalsIgnoreCase("exit") ||
input.equalsIgnoreCase("x")) {
exit = true;
} else if(input.equalsIgnoreCase("config") ||
input.equalsIgnoreCase("c")) {
System.out.println(syncConfig.getPrintableConfig());
} else if(input.equalsIgnoreCase("status") ||
input.equalsIgnoreCase("s")) {
System.out.println(statusManager.getPrintableStatus());
} else if(input.startsWith("l ")) {
logUtil.setLogLevel(input.substring(2));
System.out.println("Log level set to " +
logUtil.getLogLevel());
} else {
System.out.println(getPrintableHelp());
}
} catch(IOException e) {
logger.warn(e.getMessage(), e);
}
}
closeSyncTool();
}
private void waitForExit() {
StatusManager statusManager = StatusManager.getInstance();
int loops = 0;
boolean exit = false;
while(!exit) {
if(dirWalker.walkComplete()) {
if(ChangedList.getInstance().getListSize() <= 0) {
if(statusManager.getInWork() <= 0) {
exit = true;
System.out.println("Sync Tool processing " +
"complete, final status:");
System.out.println(statusManager.getPrintableStatus());
break;
}
}
}
if(loops >= 600) { // Print status every 10 minutes
System.out.println(statusManager.getPrintableStatus());
loops = 0;
}
sleep(10000);
}
closeSyncTool();
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
}
private void closeSyncTool() {
syncBackupManager.endBackups();
syncManager.endSync();
dirMonitor.stopMonitor();
long inWork = StatusManager.getInstance().getInWork();
if(inWork > 0) {
System.out.println("\nThe Sync Tool will exit after the remaining "
+ inWork + " work items have completed\n");
}
}
public void runSyncTool(SyncToolConfig syncConfig) {
this.syncConfig = syncConfig;
setupLogging();
System.out.print("\nStarting up the Sync Tool ...");
startSyncManager();
System.out.print("...");
boolean restart = restartPossible();
System.out.print("...");
long lastBackup = startSyncBackupManager(restart);
System.out.print("...");
if(restart && lastBackup > 0) {
logger.info("Running Sync Tool re-start file check");
startRestartDirWalker(lastBackup);
System.out.print("...");
} else {
logger.info("Running Sync Tool complete file check");
startDirWalker();
System.out.print("...");
}
if(syncConfig.syncDeletes()) {
startDeleteChecker();
}
System.out.print("...");
startDirMonitor();
System.out.println("... Startup Complete");
if(syncConfig.exitOnCompletion()) {
System.out.println(syncConfig.getPrintableConfig());
System.out.println("The Sync Tool will exit when processing " +
"is complete.\n");
waitForExit();
} else {
printWelcome();
listenForExit();
}
}
private void printWelcome() {
System.out.println(syncConfig.getPrintableConfig());
System.out.println(getPrintableHelp());
}
public String getPrintableHelp() {
StringBuilder help = new StringBuilder();
help.append("\n
help.append(" Sync Tool Help");
help.append("\n
help.append("The following commands are available:\n");
help.append("x - Exits the Sync Tool\n");
help.append("c - Prints the Sync Tool configuration\n");
help.append("s - Prints the Sync Tool status\n");
help.append("l <Level> - Changes the log level to <Level> (may ");
help.append("be any of DEBUG, INFO, WARN, ERROR)\n");
help.append("Location of logs: " + logUtil.getLogLocation() + "\n");
help.append("
return help.toString();
}
public static void main(String[] args) throws Exception {
SyncTool syncTool = new SyncTool();
SyncToolConfig syncConfig = syncTool.processCommandLineArgs(args);
syncTool.runSyncTool(syncConfig);
}
} |
package io.github.data4all.model.drawing;
/**
* A Point is a Object that can hold an x and y coordinate There is no further
* logic in this class
*
* @author tbrose
*/
public class Point {
private final float x;
private final float y;
public Point(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
@Override
public int hashCode() {
return Float.valueOf(x).hashCode() + Float.valueOf(y).hashCode();
}
@Override
public boolean equals(Object o) {
return (o == this)
|| ((o instanceof Point) && x == ((Point) o).getX() && y == ((Point) o)
.getY());
}
public boolean equalsTo(float x, float y) {
return this.x == x && this.y == y;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Point[x=" + x + ",y=" + y + "]";
}
public static double getBeta(Point a, Point b, Point c) {
// Calculate the two vectors
if (a != null && b != null && c != null) {
Point x = new Point(a.getX() - b.getX(), a.getY() - b.getY());
Point y = new Point(c.getX() - b.getX(), c.getY() - b.getY());
return Math.acos((x.getX() * y.getX() + x.getY() * y.getY())
/ (Math.hypot(x.getX(), x.getY()) * Math.hypot(y.getX(),
y.getY())));
} else {
throw new IllegalArgumentException("parameters cannot be null");
}
}
} |
package thredds.server.wms;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.simpleframework.xml.load.Persister;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import thredds.server.wms.responses.*;
import thredds.servlet.ThreddsConfig;
import thredds.servlet.DatasetHandler;
import thredds.servlet.UsageLog;
import thredds.util.Version;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Map;
import java.util.HashMap;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dt.GridDataset;
import uk.ac.rdg.resc.ncwms.styles.ColorPalette;
import uk.ac.rdg.resc.ncwms.usagelog.UsageLogEntry;
import uk.ac.rdg.resc.ncwms.controller.RequestParams;
import uk.ac.rdg.resc.ncwms.controller.ColorScaleRange;
import uk.ac.rdg.resc.ncwms.exceptions.WmsException;
import uk.ac.rdg.resc.ncwms.exceptions.MetadataException;
import uk.ac.rdg.resc.ncwms.exceptions.Wms1_1_1Exception;
import uk.ac.rdg.resc.ncwms.config.Config;
public class WMSController extends AbstractController {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WMSController.class);
private static org.slf4j.Logger logServerStartup = org.slf4j.LoggerFactory.getLogger("catalogInit");
public static final Version WMS_VER_1_1_1 = new Version( "1.1.1");
public static final Version WMS_VER_1_3_0 = new Version( "1.3.0");
private boolean allow;
protected String getPath() {
return "wms/";
}
private Config config;
private Map<String, ColorScaleRange> colorRange;
public void init() throws ServletException {
allow = ThreddsConfig.getBoolean("WMS.allow", false);
logServerStartup.info("initializing WMS: " + allow);
if (allow) {
String paletteLocation = this.getServletContext().getRealPath("/WEB-INF/" +
ThreddsConfig.get("WMS.paletteLocationDir", "palettes"));
String OGCMetaXmlFile = this.getServletContext().getRealPath("/WEB-INF/" +
ThreddsConfig.get("WMS.ogcMetaXML", "OGCMeta.xml"));
File configFile = null;
try {
configFile = new File(OGCMetaXmlFile);
config = new Persister().read(Config.class, configFile);
}
catch (Exception e) {
logServerStartup.debug("Loaded configuration from " + OGCMetaXmlFile);
throw new ServletException("Cannot read OGC config file " + e.toString());
}
File paletteLocationDir = new File(paletteLocation);
if (paletteLocationDir.exists() && paletteLocationDir.isDirectory()) {
ColorPalette.loadPalettes(paletteLocationDir);
} else {
log.info("Directory of palette files does not exist or is not a directory");
}
colorRange = new HashMap<String, ColorScaleRange>();
// LOOK Problem - global setting
NetcdfDataset.setDefaultEnhanceMode(EnumSet.of(NetcdfDataset.Enhance.ScaleMissingDefer, NetcdfDataset.Enhance.CoordSystems));
}
}
public void destroy() {
NetcdfDataset.shutdown();
}
protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String jspPage = "";
ModelAndView result = null;
log.info( UsageLog.setupRequestContext( req ) );
if (allow) {
Map<String, Object> model = new HashMap<String, Object>();
UsageLogEntry usageLogEntry = new UsageLogEntry(req);
GridDataset dataset = null;
String errMessage = "";
RequestParams params = new RequestParams(req.getParameterMap());
String versionString = params.getWmsVersion();
try
{
if ( versionString == null) {
//for Google!
versionString = "1.1.1";
}
String request = params.getMandatoryString("request");
dataset = openDataset(req, res);
FileBasedResponse response;
log.debug("Processing request: (version): " + versionString );
if (request.equalsIgnoreCase("GetCapabilities")) {
String service = params.getMandatoryString( "service" );
if ( ! service.equalsIgnoreCase( "WMS" ) )
{
throw new WmsException( "The SERVICE parameter must be WMS" );
}
errMessage = "Error encountered while processing GetCapabilities request";
long startupDate = this.getApplicationContext().getStartupDate();
GetCapabilities getCap = new GetCapabilities(params, dataset, usageLogEntry);
getCap.setConfig(config);
getCap.setStartupDate(startupDate);
response = getCap;
} else if (request.equalsIgnoreCase("GetMap")) {
errMessage = "Error encountered while processing GetMap request ";
WmsGetMap getMapHandler = new WmsGetMap(params, dataset, usageLogEntry);
response = getMapHandler;
// LOOK how do we close the log messages ?
log.info( "GetMap: " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, -1));
} else if (request.equalsIgnoreCase("GetLegendGraphic")) {
errMessage = "Error encountered while processing GetLegendGraphic request ";
response = new GetLegendGraphic(params, dataset, usageLogEntry);
} else if (request.equalsIgnoreCase("GetFeatureInfo")) {
errMessage = "Error encountered while processing GetFeatureInfo request ";
response = new GetFeatureInfo(params, dataset, usageLogEntry);
} else if (request.equals("GetMetadata")) {
errMessage = "Error encountered while processing GetMetadata request ";
MetadataResponse metaController = new MetadataResponse(params, dataset, usageLogEntry);
metaController.setConfig(config);
response = metaController;
}
// else if (request.equals("GetKML")) {
// } else if (request.equals("GetKMLRegion")) {
else
throw new WmsException( "Unsupported REQUEST parameter" );
result = response.processRequest(res, req);
closeDataset(dataset);
return result;
}
catch (MetadataException me) {
log.debug("MetadataException: " + me.toString());
}
catch (WmsException e) {
log.debug("WMS Exception! " + errMessage);
if ( versionString.equals("1.1.1"))
{
model.put( "exception", new Wms1_1_1Exception( e));
jspPage = "displayWms1_1_1Exception";
}
else if ( versionString.equals("1.3.0"))
{
model.put( "exception", e );
jspPage = "displayWmsException";
}
else
{
model.put( "exception", e );
jspPage = "displayWmsException";
}
return new ModelAndView(jspPage, model);
}
catch (java.net.SocketException se) { // Google Earth does thius a lot for some reason
log.info( "handleRequestInternal(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, -10), se);
return null;
}
catch (Throwable t) {
log.info( "handleRequestInternal(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, -1), t);
res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
return null;
}
finally {
//if ((result == null) || (result.getModel() == null) || (result.getModel().get("dataset") == null)) {
closeDataset(dataset);
// } // else use DatasetCloser HandlerInterceptor
}
} else {
// ToDo - Server not configured to support WMS. Should
// response code be 404 (Not Found) instead of 403 (Forbidden)?
res.sendError(HttpServletResponse.SC_FORBIDDEN, "Service not supported");
log.info( "handleRequestInternal(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, -1));
return null;
}
log.info( "handleRequestInternal(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, -3));
return null;
}
//Clearly, this is something STOLEN from WCSServlet
private GridDataset openDataset(HttpServletRequest req, HttpServletResponse res) throws WmsException {
log.debug("in openDataset");
GridDataset dataset;
String datasetPath = req.getPathInfo();
try {
dataset = DatasetHandler.openGridDataset(req, res, datasetPath);
//System.out.println("**openGridDataset "+dataset.getLocationURI());
}
catch (IOException e) {
log.warn("WMSController: Failed to open dataset <" + datasetPath + ">: " + e.getMessage());
throw new WmsException("Failed to open dataset, \"" + datasetPath + "\".");
}
if (dataset == null) {
log.debug("WMSController: Unknown dataset <" + datasetPath + ">.");
throw new WmsException("Unknown dataset, \"" + datasetPath + "\".");
}
log.debug("leave openDataset");
return dataset;
}
private void closeDataset(GridDataset dataset) {
if (dataset == null) return;
try {
//System.out.println("**Controller closed "+dataset.getLocationURI());
dataset.close();
} catch (IOException ioe) {
log.warn("Failed to properly close the dataset", ioe);
}
}
} |
package io.sigpipe.sing.stat;
public class SummaryStatistics {
private long num;
private double min;
private double max;
private double mean;
private double std;
private double var;
public SummaryStatistics(RunningStatistics rs) {
this.num = rs.n();
this.min = rs.min();
this.max = rs.max();
this.mean = rs.mean();
this.var = rs.var();
this.std = rs.std();
}
public double num() {
return this.num;
}
public double min() {
return this.min;
}
public double max() {
return this.max;
}
public double mean() {
return this.mean;
}
public double std() {
return this.std;
}
public double var() {
return this.var;
}
@Override
public String toString() {
String str = "";
str += "Number of Samples: " + num + System.lineSeparator();
str += "Mean: " + mean + System.lineSeparator();
str += "Variance: " + var() + System.lineSeparator();
str += "Std Dev: " + std() + System.lineSeparator();
str += "Min: " + min + System.lineSeparator();
str += "Max: " + max;
return str;
}
} |
package jfdi.ui.commandhandlers;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.logging.Logger;
import com.google.common.eventbus.Subscribe;
import edu.emory.mathcs.backport.java.util.Collections;
import jfdi.common.utilities.JfdiLogger;
import jfdi.logic.events.AddTaskDoneEvent;
import jfdi.logic.events.AddTaskFailedEvent;
import jfdi.logic.events.AliasDoneEvent;
import jfdi.logic.events.AliasFailedEvent;
import jfdi.logic.events.CommandRedoneEvent;
import jfdi.logic.events.CommandUndoneEvent;
import jfdi.logic.events.DeleteTaskDoneEvent;
import jfdi.logic.events.DeleteTaskFailedEvent;
import jfdi.logic.events.ExitCalledEvent;
import jfdi.logic.events.FilesReplacedEvent;
import jfdi.logic.events.HelpRequestedEvent;
import jfdi.logic.events.InitializationFailedEvent;
import jfdi.logic.events.InvalidCommandEvent;
import jfdi.logic.events.ListDoneEvent;
import jfdi.logic.events.MarkTaskDoneEvent;
import jfdi.logic.events.MarkTaskFailedEvent;
import jfdi.logic.events.MoveDirectoryDoneEvent;
import jfdi.logic.events.MoveDirectoryFailedEvent;
import jfdi.logic.events.NoSurpriseEvent;
import jfdi.logic.events.RedoFailedEvent;
import jfdi.logic.events.RenameTaskDoneEvent;
import jfdi.logic.events.RenameTaskFailedEvent;
import jfdi.logic.events.RescheduleTaskDoneEvent;
import jfdi.logic.events.RescheduleTaskFailedEvent;
import jfdi.logic.events.SearchDoneEvent;
import jfdi.logic.events.ShowDirectoryEvent;
import jfdi.logic.events.SurpriseEvent;
import jfdi.logic.events.UnaliasDoneEvent;
import jfdi.logic.events.UnaliasFailEvent;
import jfdi.logic.events.UndoFailedEvent;
import jfdi.logic.events.UnmarkTaskDoneEvent;
import jfdi.logic.events.UnmarkTaskFailEvent;
import jfdi.logic.events.UseDirectoryDoneEvent;
import jfdi.logic.events.UseDirectoryFailedEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.exceptions.FilePathPair;
import jfdi.ui.Constants;
import jfdi.ui.Constants.ListStatus;
import jfdi.ui.Constants.MsgType;
import jfdi.ui.MainController;
import jfdi.ui.items.ListItem;
public class CommandHandler {
public MainController controller;
public Logger logger = JfdiLogger.getLogger();
@Subscribe
public void handleAddTaskDoneEvent(AddTaskDoneEvent e) {
TaskAttributes task = e.getTask();
appendTaskToDisplayList(task, true);
if (shouldSort()) {
sortDisplayList();
}
controller.relayFb(
String.format(Constants.CMD_SUCCESS_ADDED,
task.getDescription()), MsgType.SUCCESS);
logger.fine(String.format(Constants.LOG_ADDED_SUCCESS, task.getId()));
controller.updateNotiBubbles();
}
@Subscribe
public void handleAddTaskFailEvent(AddTaskFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_ADD_UNKNOWN,
MsgType.ERROR);
logger.fine(String.format(Constants.LOG_ADD_FAIL_UNKNOWN));
break;
case EMPTY_DESCRIPTION:
controller.relayFb(Constants.CMD_ERROR_CANT_ADD_EMPTY,
MsgType.ERROR);
logger.fine(String.format(Constants.LOG_ADD_FAIL_EMPTY));
break;
case DUPLICATED_TASK:
controller.relayFb(Constants.CMD_ERROR_CANT_ADD_DUPLICATE,
MsgType.ERROR);
logger.fine(String.format(Constants.LOG_ADD_FAIL_DUPLICATE));
break;
default:
break;
}
}
@Subscribe
public void handleAliasDoneEvent(AliasDoneEvent e) {
controller.relayFb(
String.format(Constants.CMD_SUCCESS_ALIAS, e.getAlias(),
e.getCommand()), MsgType.SUCCESS);
}
@Subscribe
public void handleAliasFailEvent(AliasFailedEvent e) {
switch (e.getError()) {
case INVALID_PARAMETERS:
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_ALIAS_INVALID,
e.getAlias(), e.getCommand()), MsgType.ERROR);
// logger.fine(String.format(format, args));
break;
case DUPLICATED_ALIAS:
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_ALIAS_DUPLICATED,
e.getAlias()), MsgType.ERROR);
// logger.fine(String.format(format, args));
break;
case UNKNOWN:
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_ALIAS_UNKNOWN,
e.getCommand()), MsgType.ERROR);
// logger.fine(String.format(format, args));
break;
default:
break;
}
}
@Subscribe
public void handleCommandRedoneEvent(CommandRedoneEvent e) {
Class<? extends Command> cmdType = e.getCommandType();
switchContext(controller.displayStatus, true);
controller.relayFb(
String.format(Constants.CMD_SUCCESS_REDONE, cmdType.toString()),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleCommandUndoneEvent(CommandUndoneEvent e) {
Class<? extends Command> cmdType = e.getCommandType();
switchContext(controller.displayStatus, true);
controller.relayFb(
String.format(Constants.CMD_SUCCESS_UNDONE, cmdType.toString()),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleDeleteTaskDoneEvent(DeleteTaskDoneEvent e) {
ArrayList<Integer> deletedIds = e.getDeletedIds();
Collections.sort(deletedIds, Comparator.reverseOrder());
int indexCount = -1;
for (int screenId : deletedIds) {
indexCount = screenId - 1;
controller.importantList.remove(indexCount);
logger.fine(String.format(Constants.LOG_DELETED_SUCCESS, screenId));
}
controller.relayFb(Constants.CMD_SUCCESS_DELETED, MsgType.SUCCESS);
indexCount = 1;
for (ListItem item : controller.importantList) {
if (item.getIndex() != indexCount) {
item.setIndex(indexCount);
}
indexCount++;
}
controller.updateNotiBubbles();
}
@Subscribe
public void handleDeleteTaskFailEvent(DeleteTaskFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_DELETE_UNKNOWN,
MsgType.ERROR);
logger.fine(Constants.LOG_DELETE_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ID:
for (Integer screenId : e.getInvalidIds()) {
controller.relayFb(String.format(
Constants.CMD_ERROR_CANT_DELETE_NO_ID, screenId),
MsgType.ERROR);
}
logger.fine(Constants.LOG_DELETE_FAIL_NOID);
break;
default:
break;
}
}
@Subscribe
public void handleExitCalledEvent(ExitCalledEvent e) {
System.out.printf("\nMoriturus te saluto.\n");
System.exit(0);
logger.fine(Constants.LOG_USER_EXIT);
}
@Subscribe
public void handleHelpRequestEvent(HelpRequestedEvent e) {
switchContext(ListStatus.HELP, false);
controller.showHelpDisplay();
controller.relayFb(Constants.CMD_SUCCESS_HELP, MsgType.SUCCESS);
}
@Subscribe
public void handleFilesReplacedEvent(FilesReplacedEvent e) {
String fb = "";
for (FilePathPair item : e.getFilePathPairs()) {
fb += String.format("\n" + Constants.CMD_ERROR_INIT_FAIL_REPLACED,
item.getOldFilePath(), item.getNewFilePath());
}
controller.appendFb(fb, MsgType.WARNING);
controller.updateNotiBubbles();
}
@Subscribe
public void handleInitializationFailedEvent(InitializationFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_INIT_FAIL_UNKNOWN,
MsgType.ERROR);
break;
case INVALID_PATH:
controller.relayFb(
String.format(Constants.CMD_ERROR_INIT_FAIL_INVALID,
e.getPath()), MsgType.ERROR);
break;
default:
break;
}
}
@Subscribe
public void handleInvalidCommandEvent(InvalidCommandEvent e) {
controller.relayFb(
String.format(Constants.CMD_WARNING_DONTKNOW, e.getInputString()),
MsgType.WARNING);
logger.fine(Constants.LOG_INVALID_COMMAND);
}
@Subscribe
public void handleListDoneEvent(ListDoneEvent e) {
if (!controller.isUpdate) {
switch (e.getListType()) {
case ALL:
switchContext(ListStatus.ALL, false);
break;
case COMPLETED:
switchContext(ListStatus.COMPLETE, false);
break;
case INCOMPLETE:
switchContext(ListStatus.INCOMPLETE, false);
break;
case OVERDUE:
switchContext(ListStatus.OVERDUE, false);
break;
case UPCOMING:
switchContext(ListStatus.UPCOMING, false);
break;
default:
break;
}
listTasks(e.getItems(), false);
controller.relayFb(Constants.CMD_SUCCESS_LISTED, MsgType.SUCCESS);
}
updateBubble(e);
}
@Subscribe
public void handleMarkTaskDoneEvent(MarkTaskDoneEvent e) {
ArrayList<Integer> doneIds = e.getScreenIds();
Collections.sort(doneIds, Comparator.reverseOrder());
int indexCount = -1;
for (Integer screenId : doneIds) {
indexCount = screenId - 1;
controller.importantList.get(indexCount).setMarkT();
controller.importantList.get(indexCount).strikeOut();
refreshDisplay();
// controller.displayList(controller.displayStatus);
// logger.fine(String.format(Constants.LOG_DELETED_SUCCESS, num));
}
controller.relayFb(
String.format(Constants.CMD_SUCCESS_MARKED, indexCount + 1),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
private void refreshDisplay() {
controller.listMain.refresh();
}
@Subscribe
public void handleMarkTaskFailEvent(MarkTaskFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_MARK_UNKNOWN,
MsgType.ERROR);
// logger.fine(Constants.LOG_DELETE_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ID:
// NEED TO CHANGE TO INDEX SOON????
for (Integer screenId : e.getInvalidIds()) {
controller.relayFb(String.format(
Constants.CMD_ERROR_CANT_MARK_NO_ID, screenId),
MsgType.ERROR);
}
// logger.fine(Constants.LOG_DELETE_FAIL_NOID);
break;
default:
break;
}
}
@Subscribe
public void handleMoveDirectoryDoneEvent(MoveDirectoryDoneEvent e) {
switchContext(ListStatus.INCOMPLETE, true);
controller.relayFb(
String.format(Constants.CMD_SUCCESS_MOVED, e.getNewDirectory()),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleMoveDirectoryFailEvent(MoveDirectoryFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(
String.format(Constants.CMD_ERROR_MOVE_FAIL_UNKNOWN,
e.getNewDirectory()), MsgType.ERROR);
break;
case INVALID_PATH:
controller.relayFb(
String.format(Constants.CMD_ERROR_MOVE_FAIL_INVALID,
e.getNewDirectory()), MsgType.ERROR);
break;
default:
break;
}
}
@Subscribe
public void handleNoSurpriseEvent(NoSurpriseEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_SURP_FAIL_UNKNOWN,
MsgType.ERROR);
break;
case NO_TASKS:
controller.relayFb(Constants.CMD_ERROR_SURP_FAIL_NO_TASKS,
MsgType.ERROR);
break;
default:
break;
}
}
@Subscribe
public void handleRedoFailedEvent(RedoFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_REDO_FAIL_UNKNOWN,
MsgType.ERROR);
break;
case NONTHING_TO_REDO:
controller.relayFb(Constants.CMD_ERROR_REDO_FAIL_NO_TASKS,
MsgType.ERROR);
break;
default:
break;
}
}
@Subscribe
public void handleRenameTaskDoneEvent(RenameTaskDoneEvent e) {
TaskAttributes task = e.getTask();
int count = 0;
for (int i = 0; i < controller.importantList.size(); i++) {
if (controller.getIdFromIndex(i) == task.getId()) {
controller.importantList.get(i).setDescription(
task.getDescription());
count = i;
break;
}
}
controller.relayFb(
String.format(Constants.CMD_SUCCESS_RENAMED, count + 1,
task.getDescription()), MsgType.SUCCESS);
logger.fine(String.format(Constants.LOG_RENAMED_SUCCESS, task.getId()));
controller.updateNotiBubbles();
}
@Subscribe
public void handleRenameTaskFailEvent(RenameTaskFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_RENAME_UNKNOWN,
MsgType.ERROR);
logger.fine(Constants.LOG_RENAME_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ID:
// NEED TO CHANGE TO INDEX SOON????
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_RENAME_NO_ID,
e.getScreenId()), MsgType.ERROR);
logger.fine(Constants.LOG_RENAME_FAIL_NOID);
break;
case NO_CHANGES:
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_RENAME_NO_CHANGES,
e.getDescription()), MsgType.ERROR);
logger.fine(Constants.LOG_RENAME_FAIL_NOCHANGE);
break;
case DUPLICATED_TASK:
controller.relayFb(Constants.CMD_ERROR_CANT_RENAME_DUPLICATE,
MsgType.ERROR);
logger.fine(String.format(Constants.LOG_RENAME_FAIL_DUPLICATE));
break;
default:
break;
}
}
@Subscribe
public void handleRescheduleTaskDoneEvent(RescheduleTaskDoneEvent e) {
int count = 0;
TaskAttributes task = e.getTask();
for (int i = 0; i < controller.importantList.size(); i++) {
if (controller.getIdFromIndex(i) == task.getId()) {
controller.importantList.get(i).setTimeDate(
task.getStartDateTime(), task.getEndDateTime());
count = i;
break;
}
}
if (shouldSort()) {
sortDisplayList();
}
controller.relayFb(
String.format(Constants.CMD_SUCCESS_RESCHEDULED, count + 1),
MsgType.SUCCESS);
logger.fine(String.format(Constants.LOG_RESCHED_SUCCESS, task.getId()));
controller.updateNotiBubbles();
}
@Subscribe
public void handleRescheduleTaskFailEvent(RescheduleTaskFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_RESCHEDULE_UNKNOWN,
MsgType.ERROR);
logger.fine(Constants.LOG_RESCHE_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ID:
// NEED TO CHANGE TO INDEX SOON????
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_RESCHEDULE_NO_ID,
e.getScreenId()), MsgType.ERROR);
logger.fine(Constants.LOG_RESCHE_FAIL_NOID);
break;
case NO_CHANGES:
controller.relayFb(
Constants.CMD_ERROR_CANT_RESCHEDULE_NO_CHANGES
+ e.getStartDateTime() + " - to - "
+ e.getEndDateTime() + " -!", MsgType.ERROR);
logger.fine(Constants.LOG_RESCHE_FAIL_NOCHANGE);
break;
case DUPLICATED_TASK:
controller.relayFb(Constants.CMD_ERROR_CANT_RESCHEDULE_DUPLICATE,
MsgType.ERROR);
logger.fine(String.format(Constants.LOG_RESCHE_FAIL_DUPLICATE));
break;
default:
break;
}
}
@Subscribe
public void handleSearchDoneEvent(SearchDoneEvent e) {
listTasks(e.getResults(), false);
switchContext(ListStatus.SEARCH, false);
for (String key : e.getKeywords()) {
controller.searchCmd += key + " ";
}
//controller.switchTabSkin();
controller.setHighlights(e.getKeywords());
controller.relayFb(Constants.CMD_SUCCESS_SEARCH, MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleShowDirectoryEvent(ShowDirectoryEvent e) {
controller.relayFb(
String.format(Constants.CMD_SUCCESS_SHOWDIRECTORY, e.getPwd()),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleSurpriseEvent(SurpriseEvent e) {
controller.importantList.clear();
TaskAttributes task = e.getTask();
appendTaskToDisplayList(task, false);
switchContext(ListStatus.ALL, false);
switchContext(ListStatus.SURPRISE, false);
controller.relayFb(Constants.CMD_SUCCESS_SURPRISED, MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleUnaliasDoneEvent(UnaliasDoneEvent e) {
controller.relayFb(
String.format(Constants.CMD_SUCCESS_UNALIAS, e.getAlias()),
MsgType.SUCCESS);
}
@Subscribe
public void handleUnaliasFailEvent(UnaliasFailEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_UNALIAS_UNKNOWN,
e.getAlias()), MsgType.ERROR);
// logger.fine(Constants.LOG_RESCHE_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ALIAS:
// NEED TO CHANGE TO INDEX SOON????
controller.relayFb(
String.format(Constants.CMD_ERROR_CANT_UNALIAS_NO_ALIAS,
e.getAlias()), MsgType.ERROR);
// logger.fine(Constants.LOG_RESCHE_FAIL_NOID);
break;
default:
break;
}
}
@Subscribe
public void handleUndoFailedEvent(UndoFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_UNDO_FAIL_UNKNOWN,
MsgType.ERROR);
break;
case NONTHING_TO_UNDO:
controller.relayFb(Constants.CMD_ERROR_UNDO_FAIL_NO_TASKS,
MsgType.ERROR);
break;
default:
break;
}
}
@Subscribe
public void handleUnmarkTaskDoneEvent(UnmarkTaskDoneEvent e) {
ArrayList<Integer> undoneIds = e.getScreenIds();
Collections.sort(undoneIds, Comparator.reverseOrder());
int indexCount = -1;
for (Integer screenId : undoneIds) {
indexCount = screenId - 1;
controller.importantList.get(indexCount).setMarkF();
controller.importantList.get(indexCount).removeStrike();
refreshDisplay();
// controller.displayList(controller.displayStatus);
// logger.fine(String.format(Constants.LOG_DELETED_SUCCESS, num));
}
controller.relayFb(
String.format(Constants.CMD_SUCCESS_UNMARKED, indexCount + 1),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleUnmarkTaskFailEvent(UnmarkTaskFailEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(Constants.CMD_ERROR_CANT_UNMARK_UNKNOWN,
MsgType.ERROR);
// logger.fine(Constants.LOG_DELETE_FAIL_UNKNOWN);
break;
case NON_EXISTENT_ID:
// NEED TO CHANGE TO INDEX SOON????
for (Integer screenId : e.getInvalidIds()) {
controller.relayFb(String.format(
Constants.CMD_ERROR_CANT_UNMARK_NO_ID, screenId),
MsgType.ERROR);
}
// logger.fine(Constants.LOG_DELETE_FAIL_NOID);
break;
default:
break;
}
}
@Subscribe
public void handleUseDirectoryDoneEvent(UseDirectoryDoneEvent e) {
switchContext(ListStatus.INCOMPLETE, true);
controller.relayFb(
String.format(Constants.CMD_SUCCESS_USED, e.getNewDirectory()),
MsgType.SUCCESS);
controller.updateNotiBubbles();
}
@Subscribe
public void handleUseDirectoryFailEvent(UseDirectoryFailedEvent e) {
switch (e.getError()) {
case UNKNOWN:
controller.relayFb(
String.format(Constants.CMD_ERROR_USE_FAIL_UNKNOWN,
e.getNewDirectory()), MsgType.ERROR);
break;
case INVALID_PATH:
controller.relayFb(
String.format(Constants.CMD_ERROR_USE_FAIL_INVALID,
e.getNewDirectory()), MsgType.ERROR);
break;
default:
break;
}
}
public void setController(MainController controller) {
this.controller = controller;
}
/**
* Sets the display list to the given ArrayList of tasks which match the context.
*
* @param tasks
* the ArrayList of tasks to be displayed
*/
private void listTasks(ArrayList<TaskAttributes> tasks, boolean shouldCheckContext) {
controller.importantList.clear();
for (TaskAttributes task : tasks) {
appendTaskToDisplayList(task, shouldCheckContext);
}
}
/**
* Appends a task to the list of tasks displayed.
*
* @param task
* the task to be appended
*/
private void appendTaskToDisplayList(TaskAttributes task, boolean shouldCheckContext) {
if (shouldCheckContext && !isSameContext(task)) {
return;
}
int onScreenId = controller.importantList.size() + 1;
ListItem listItem;
if (task.isCompleted()) {
listItem = new ListItem(onScreenId, task, true);
controller.importantList.add(listItem);
controller.importantList.get(controller.importantList.size() - 1).strikeOut();
listItem.strikeOut();
} else {
listItem = new ListItem(onScreenId, task, false);
controller.importantList.add(listItem);
controller.importantList.get(controller.importantList.size() - 1)
.getStyleClass().add("itemBox");
}
}
private void sortDisplayList() {
ArrayList<TaskAttributes> taskList = new ArrayList<TaskAttributes>();
controller.importantList.forEach(listItem -> taskList.add(listItem.getItem()));
Collections.sort(taskList);
listTasks(taskList, false);
}
private boolean shouldSort() {
return controller.displayStatus.equals(ListStatus.OVERDUE)
|| controller.displayStatus.equals(ListStatus.UPCOMING);
}
private boolean isSameContext(TaskAttributes task) {
switch (controller.displayStatus) {
case ALL:
return true;
case SEARCH:
return false;
case SURPRISE:
return false;
case HELP:
return false;
case COMPLETE:
return task.isCompleted();
case INCOMPLETE:
return !task.isCompleted();
case OVERDUE:
return task.isOverdue();
case UPCOMING:
return task.isUpcoming();
default:
assert false;
return false;
}
}
private void switchContext(ListStatus status, Boolean isListing) {
if (status.equals(ListStatus.HELP)) {
controller.beforeHelp = controller.displayStatus;
}
controller.displayStatus = status;
if (isListing) {
controller.transListCmd();
}
controller.switchTabSkin();
}
private void updateBubble(ListDoneEvent e) {
Integer count = e.getItems().size();
switch (e.getListType()) {
case INCOMPLETE:
controller.incompletePlaceHdr.set(count.toString());
break;
case OVERDUE:
controller.overduePlaceHdr.set(count.toString());
break;
case UPCOMING:
controller.upcomingPlaceHdr.set(count.toString());
break;
default:
break;
}
}
} |
package me.nallar.modpatcher;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/**
* Tries to ensure that our transformer is last
*/
public class ModPatcherTweaker implements ITweaker {
@SuppressWarnings("unchecked")
public static void add() {
List<String> newTweaks = (List<String>) Launch.blackboard.get("TweakClasses");
newTweaks.add(ModPatcherTweaker.class.getName());
}
private static void inject() {
LaunchClassLoaderUtil.addTransformer(ModPatcherTransformer.getInstance());
try {
Class<?> mixinEnvironmentClass = Class.forName("org.spongepowered.asm.mixin.MixinEnvironment", false, ModPatcherTweaker.class.getClassLoader());
Field f = mixinEnvironmentClass.getDeclaredField("excludeTransformers");
f.setAccessible(true);
Set<String> vals = (Set<String>) f.get(null);
vals.add(ModPatcherTransformer.class.getName());
} catch (ClassNotFoundException ignored) {
// TODO Silence this once confirmed working?
PatcherLog.trace("Failed to find mixin environment, normal for non-spongepowered", ignored);
} catch (NoSuchFieldException | IllegalAccessException e) {
PatcherLog.warn("Failed to add mixin transformer exclusion for our transformer", e);
}
}
@Override
public void acceptOptions(List<String> list, File file, File file1, String s) {
}
@Override
public void injectIntoClassLoader(LaunchClassLoader launchClassLoader) {
inject();
}
@Override
public String getLaunchTarget() {
throw new UnsupportedOperationException("ModPatcherTweaker is not a primary tweaker.");
}
@Override
public String[] getLaunchArguments() {
inject();
LaunchClassLoaderUtil.dumpTransformersIfEnabled();
return new String[0];
}
} |
package net.aicomp.javachallenge2015;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class Bookmaker {
private static boolean DEBUG = false;
private static final int PLAYERS_NUM = 4;
private static final int MAP_WIDTH = 40;
private static final int BLOCK_WIDTH = 5;
private static final int INITIAL_LIFE = 5;
private static final int FORCED_END_TURN = 10000;
private static final int PANEL_REBIRTH_TURN = 5 * 4;
public static final int PLAYER_REBIRTH_TURN = 5 * 4;
public static final int ATTACKED_PAUSE_TURN = 5 * 4;
public static final int MUTEKI_TURN = 10 * 4;
private static final int REPULSION = 7;
public static final int ACTION_TIME_LIMIT = 2000;
private static final int TIME_TO_FALL = 1 * 4;
public static final String READY = "Ready";
public static final String UP = "U";
public static final String DOWN = "D";
public static final String RIGHT = "R";
public static final String LEFT = "L";
public static final String ATTACK = "A";
public static final String NONE = "N";
public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT };
private static Player[] players;
private static Random rnd;
private static int turn;
private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH];
private static final String EXEC_COMMAND = "a";
private static final String PAUSE_COMMAND = "p";
private static final String UNPAUSE_COMMAND = "u";
public static void main(String[] args) throws InterruptedException,
ParseException {
Options options = new Options()
.addOption(
EXEC_COMMAND,
true,
"The command and arguments with double quotation marks to execute AI program (e.g. -a \"java MyAI\")")
.addOption(
PAUSE_COMMAND,
true,
"The command and arguments with double quotation marks to pause AI program (e.g. -p \"echo pause\")")
.addOption(
UNPAUSE_COMMAND,
true,
"The command and arguments with double quotation marks to unpause AI program (e.g. -u \"echo unpause\")");
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
if (!hasCompleteArgs(line)) {
HelpFormatter help = new HelpFormatter();
help.printHelp("java -jar JavaChallenge2015.jar [OPTIONS]\n"
+ "[OPTIONS]: ", "", options, "", true);
return;
}
String[] execAICommands = line.getOptionValues(EXEC_COMMAND);
String[] pauseAICommands = line.getOptionValues(PAUSE_COMMAND);
String[] unpauseAICommands = line.getOptionValues(UNPAUSE_COMMAND);
rnd = new Random(System.currentTimeMillis());
turn = 0;
players = new Player[PLAYERS_NUM];
for (int i = 0; i < players.length; i++) {
players[i] = new Player(INITIAL_LIFE, execAICommands[i],
pauseAICommands[i], unpauseAICommands[i]);
}
rebirthPhase();
while (!isFinished()) {
int turnPlayer = turn % PLAYERS_NUM;
String command = infromationPhase(turnPlayer);
printLOG(command);
// DEBUG
if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard()
&& !players[turnPlayer].isPausing(turn)) {
command = new Scanner(System.in).next();
}
actionPhase(turnPlayer, command);
rebirthPhase();
turn++;
}
System.out.println("Game Finished!");
}
/**
*
*
* @param line
* @author J.Kobayashi
* @return 4
* {@code true}{@code false}
*/
private static boolean hasCompleteArgs(CommandLine line) {
if (line == null) {
return false;
}
if (line.getOptionValues(EXEC_COMMAND) == null
|| line.getOptionValues(EXEC_COMMAND).length != PLAYERS_NUM) {
return false;
}
if (line.getOptionValues(PAUSE_COMMAND) == null
|| line.getOptionValues(PAUSE_COMMAND).length != PLAYERS_NUM) {
return false;
}
if (line.getOptionValues(UNPAUSE_COMMAND) == null
|| line.getOptionValues(UNPAUSE_COMMAND).length != PLAYERS_NUM) {
return false;
}
return true;
}
private static void printLOG(String command) {
System.out.println(turn);
for (Player player : players) {
System.out.print(player.life + " ");
}
System.out.println();
for (int x = 0; x < MAP_WIDTH; x++) {
outer: for (int y = 0; y < MAP_WIDTH; y++) {
if (DEBUG) {
for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) {
Player player = players[playerID];
if (player.isOnBoard() && player.x == x
&& player.y == y) {
char c = (char) (playerID + 'A');
System.out.print(c + "" + c);
continue outer;
}
}
}
System.out.print(" " + board[x][y]);
}
System.out.println();
}
for (Player player : players) {
if (player.isOnBoard()) {
System.out.println(player.x + " " + player.y + " "
+ Bookmaker.DIRECTION[player.dir]);
} else {
System.out.println((-1) + " " + (-1) + " "
+ Bookmaker.DIRECTION[player.dir]);
}
}
System.out.println(command);
}
private static void rebirthPhase() {
for (int i = 0; i < MAP_WIDTH; i++) {
for (int j = 0; j < MAP_WIDTH; j++) {
if (board[i][j] < 0) {
board[i][j]++;
} else if (board[i][j] == 1) {
board[i][j] = -PANEL_REBIRTH_TURN;
} else if (board[i][j] > 1) {
board[i][j]
}
}
}
for (int i = 0; i < PLAYERS_NUM; i++) {
Player p = players[i];
if (p.isOnBoard() && !p.isMuteki(turn)) {
if (board[p.x][p.y] < 0) {
p.drop(turn);
}
} else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) {
search: while (true) {
int x = nextInt();
int y = nextInt();
for (int j = 0; j < PLAYERS_NUM; j++) {
if (i == j) {
continue;
}
Player other = players[j];
if (other.isOnBoard()
&& dist(x, y, other.x, other.y) <= REPULSION) {
continue search;
}
}
p.reBirthOn(x, y, turn);
p.dir = nextDir();
break;
}
}
}
}
private static String infromationPhase(int turnPlayer) {
if (!players[turnPlayer].isAlive()) {
return NONE;
}
ArrayList<Integer> lifes = new ArrayList<Integer>();
ArrayList<String> wheres = new ArrayList<String>();
for (int i = 0; i < PLAYERS_NUM; i++) {
lifes.add(players[i].life);
if (players[i].isOnBoard()) {
wheres.add(players[i].x + " " + players[i].y);
} else {
wheres.add((-1) + " " + (-1));
}
}
String command = players[turnPlayer].getAction(turnPlayer, turn, board,
lifes, wheres);
return command;
}
private static void actionPhase(int turnPlayer, String command) {
Player p = players[turnPlayer];
if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) {
return;
}
if (command.equals(ATTACK)) {
int xNow = p.x / BLOCK_WIDTH;
int yNow = p.y / BLOCK_WIDTH;
for (int x = 0; x < MAP_WIDTH; x++) {
for (int y = 0; y < MAP_WIDTH; y++) {
int xBlock = x / BLOCK_WIDTH;
int yBlock = y / BLOCK_WIDTH;
if (p.dir == 0) {
if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow)
* TIME_TO_FALL;
}
} else if (p.dir == 1) {
if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow)
* TIME_TO_FALL;
}
} else if (p.dir == 2) {
if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow)
* TIME_TO_FALL;
}
} else if (p.dir == 3) {
if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow)
* TIME_TO_FALL;
}
}
}
}
p.attackedPause(turn);
return;
}
{
int tox = -1, toy = -1;
if (command.equals(UP)) {
tox = p.x - 1;
toy = p.y;
} else if (command.equals(RIGHT)) {
tox = p.x;
toy = p.y + 1;
} else if (command.equals(DOWN)) {
tox = p.x + 1;
toy = p.y;
} else if (command.equals(LEFT)) {
tox = p.x;
toy = p.y - 1;
} else {
return;
}
if (!isInside(tox, toy)) {
return;
}
p.directTo(command);
for (int i = 0; i < PLAYERS_NUM; i++) {
if (!players[i].isOnBoard() || i == turnPlayer) {
continue;
}
if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) {
return;
}
}
p.moveTo(tox, toy);
}
}
private static int dist(int x1, int y1, int x2, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
private static int nextInt() {
int ret = (int) (rnd.nextDouble() * MAP_WIDTH);
return ret;
}
private static int nextDir() {
int rng = rnd.nextInt(4);
return rng;
}
private static boolean isInside(int x, int y) {
return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH;
}
private static boolean isFinished() {
int livingCnt = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].life > 0) {
livingCnt++;
}
}
return livingCnt == 1 || turn > FORCED_END_TURN;
}
} |
package net.gigimoi.zombietc.weapon;
import net.gigimoi.zombietc.EntityZZombie;
import net.gigimoi.zombietc.TileBarricade;
import net.gigimoi.zombietc.event.GameManager;
import net.gigimoi.zombietc.helpers.MouseOverHelper;
import net.gigimoi.zombietc.helpers.TextAlignment;
import net.gigimoi.zombietc.helpers.TextRenderHelper;
import net.gigimoi.zombietc.net.MessageTryShoot;
import net.gigimoi.zombietc.net.MessageReload;
import net.gigimoi.zombietc.net.MessageShoot;
import net.gigimoi.zombietc.ZombieTC;
import net.gigimoi.zombietc.helpers.TextureHelper;
import net.gigimoi.zombietc.pathfinding.Point3;
import net.gigimoi.zombietc.proxy.ClientProxy;
import net.minecraft.block.Block;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.client.IItemRenderer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.model.AdvancedModelLoader;
import net.minecraftforge.client.model.IModelCustom;
import org.lwjgl.opengl.GL11;
import scala.util.Right;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ItemWeapon extends Item implements IItemRenderer {
public static ItemWeapon radomVis = new ItemWeapon("Radom Vis", FireMechanism.semiAutomatic, 1, 1, 9, 90, 20, 1).barrelLength(1f).sightHeight(0.1f);
public static ItemWeapon stormRifle = new ItemWeapon("Storm Rifle", FireMechanism.automatic, 0.5, 6, 30, 120, 20, 3).barrelLength(2f).sightHeight(1f);
public static ItemWeapon thompson = new ItemWeapon("Thompson", FireMechanism.automatic, 0.5, 6, 30, 120, 20, 2).barrelLength(1.8f).sightHeight(0.1f);
public static ItemWeapon karbine = new ItemWeapon("Karbine", FireMechanism.semiAutomatic, 0.7, 1, 9, 90, 20, 20).barrelLength(2.5f).sightHeight(0.1f);
public FireMechanism fireMechanism;
public double inventoryScale;
double adsLift;
public int clipSize;
public int initialAmmo;
public int reloadTime;
public int fireDelay;
private float barrelLength;
private float sightHeight;
public ItemWeapon barrelLength(float length) { this.barrelLength = length; return this; }
public ItemWeapon sightHeight(float height) { this.sightHeight = height; return this; }
public ItemWeapon(String name, FireMechanism fireMechanism, double inventoryScale, double adsLift, int clipSize, int initialAmmo, int reloadTime, int fireDelay) {
this.setUnlocalizedName(name);
setMaxStackSize(1);
this.fireMechanism = fireMechanism;
this.inventoryScale = inventoryScale;
this.adsLift = adsLift;
this.clipSize = clipSize;
this.initialAmmo = initialAmmo;
this.reloadTime = reloadTime;
this.fireDelay = fireDelay;
ZombieTC.proxy.registerWeaponRender(this);
}
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return true;
}
public IModelCustom modelGun;
public static IModelCustom modelFlash;
private static Random _r = new Random();
@Override
public void renderItem(ItemRenderType type, ItemStack stack, Object... data) {
GL11.glPushMatrix();
if(type == ItemRenderType.EQUIPPED_FIRST_PERSON) {
//EntityPlayer player = (EntityPlayer) data[1];
GL11.glTranslated(0, 1, 0);
}
if(type == ItemRenderType.INVENTORY) {
GL11.glScaled(0.8 * inventoryScale, 0.8 * inventoryScale, 0.8 * inventoryScale);
}
if(type == ItemRenderType.EQUIPPED) {
GL11.glRotated(90, 0, 1, 0);
GL11.glTranslated(0, 1, 0);
}
ensureTagCompund(stack);
GL11.glScaled(0.2f, 0.2f, 0.2f);
GL11.glRotated(90, 1, 0, 0);
GL11.glRotated(135, 0, 0, 1);
GL11.glRotated(0, 0, 1, 0);
if(type != ItemRenderType.INVENTORY && stack.getTagCompound().getBoolean("InSights") && stack.getTagCompound().getInteger("Reload Timer") == 0) {
GL11.glTranslated(-1, 3.45, -0.65 + -adsLift / 5f);
}
if(type != ItemRenderType.INVENTORY && stack.getTagCompound().getInteger("Reload Timer") > 0) {
GL11.glRotated(10, 0, 1, 0);
GL11.glRotated(50, 0, 0, -1);
}
if(type == ItemRenderType.INVENTORY) {
GL11.glRotated(-45, 0, 1, 0);
}
boolean shoot = false;
if(stack.getTagCompound().getBoolean("Shoot")) {
shoot = true;
stack.getTagCompound().setBoolean("Shoot", false);
}
if(modelGun == null) {
modelGun = AdvancedModelLoader.loadModel(new ResourceLocation(ZombieTC.MODID, "models/guns/" + getUnlocalizedName().substring(5) + ".obj"));
}
if(modelFlash == null) {
modelFlash = AdvancedModelLoader.loadModel(new ResourceLocation(ZombieTC.MODID, "models/muzzleflash.obj"));
}
TextureHelper.bindTexture(new ResourceLocation(ZombieTC.MODID, "textures/models/guns/" + getUnlocalizedName().substring(5) + ".png"));
if(type == ItemRenderType.ENTITY) {
GL11.glScaled(0.5, 0.5, 0.5);
}
modelGun.renderAll();
if(shoot) {
TextureHelper.bindTexture(new ResourceLocation(ZombieTC.MODID, "textures/models/muzzleflash.png"));
GL11.glTranslated(_r.nextInt(100) / 100f - 0.5f, _r.nextInt(100) / 100f - 0.3f, _r.nextInt(100) / 100f - 0.5f);
GL11.glTranslated(-barrelLength * 4, 0, sightHeight * 1.5f);
modelFlash.renderAll();
}
GL11.glPopMatrix();
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
ensureTagCompund(stack);
stack.getTagCompound().setBoolean("InSights",!stack.getTagCompound().getBoolean("InSights"));
return stack;
}
@Override
public boolean hitEntity(ItemStack stack, EntityLivingBase attacker, EntityLivingBase attacked) {
return false; //TODO: Deal no damage
}
public void ensureTagCompund(ItemStack stack) {
if(!stack.hasTagCompound()) {
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setBoolean("InSights", false);
stack.getTagCompound().setBoolean("Shoot", false);
stack.getTagCompound().setInteger("ShootCooldown", 0);
stack.getTagCompound().setInteger("Rounds", clipSize);
stack.getTagCompound().setInteger("Ammo", initialAmmo);
stack.getTagCompound().setInteger("Reload Time", 0);
}
}
@Override
public void onUpdate(ItemStack stack, World world, Entity entity, int p_77663_4_, boolean p_77663_5_) {
ensureTagCompund(stack);
NBTTagCompound tag = stack.getTagCompound();
if(tag.getInteger("Reload Timer") > 0) {
tag.setInteger("Reload Timer", tag.getInteger("Reload Timer") - 1);
if(tag.getInteger("Reload Timer") == 0) {
tag.setInteger("Rounds", clipSize);
tag.setInteger("ShootCooldown", 0);
}
}
if(ZombieTC.editorModeManager.enabled) {
return;
}
if(entity != null) {
if(world.isRemote && entity.getClass() != EntityClientPlayerMP.class) {
return;
}
if(!world.isRemote && entity.getClass() == EntityPlayerMP.class) {
return;
}
EntityPlayer player = (EntityPlayer)entity;
tag.setInteger("ShootCooldown", tag.getInteger("ShootCooldown") - 1);
if(player.getHeldItem() == stack) {
player.swingProgress = 0f;
player.isSwingInProgress = false;
player.swingProgressInt = 0;
if(world.isRemote) {
if(ClientProxy.reload.isPressed() && tag.getInteger("Reload Timer") == 0 && tag.getInteger("Rounds") != clipSize) {
tag.setInteger("Reload Timer", reloadTime);
ZombieTC.network.sendToServer(new MessageReload(player));
}
if(tag.getInteger("Reload Timer") == 0 && fireMechanism.checkFire(this, stack)) {
if(tag.getInteger("Rounds") > 0) {
tag.setInteger("ShootCooldown", fireDelay);
tag.setBoolean("Shoot", true);
tag.setInteger("Rounds", tag.getInteger("Rounds") - 1);
//player.cameraYaw += 1;
ZombieTC.proxy.playSound("pistolShoot", (float)player.posX, (float)player.posY, (float)player.posZ);
ZombieTC.network.sendToServer(new MessageTryShoot(player));
//<fuckmefuckmefuckme>
ArrayList<Integer> damages = new ArrayList<Integer>();
ArrayList<Integer> tickers = new ArrayList<Integer>();
List blocks = new ArrayList<Block>();
List<Point3> blockBarricades = (List<Point3>)GameManager.blockBarricades.clone();
for(int i = 0; i < blockBarricades.size(); i++) {
Point3 vec = GameManager.blockBarricades.get(i);
blocks.add(world.getBlock((int)vec.xCoord, (int)vec.yCoord, (int)vec.zCoord));
TileEntity te = world.getTileEntity((int) vec.xCoord, (int) vec.yCoord, (int) vec.zCoord);
damages.add(((TileBarricade)te).damage);
tickers.add(((TileBarricade)te).ticker);
world.setBlock((int) vec.xCoord, (int) vec.yCoord, (int) vec.zCoord, Blocks.air);
}
MovingObjectPosition trace = MouseOverHelper.getMouseOver(5000.0F);
for(int i = 0; i < blockBarricades.size(); i++) {
Point3 vec = blockBarricades.get(i);
world.setBlock((int) vec.xCoord, (int) vec.yCoord, (int) vec.zCoord, (Block) blocks.get(i));
TileBarricade te = (TileBarricade)world.getTileEntity((int) vec.xCoord, (int) vec.yCoord, (int) vec.zCoord);
te.damage = damages.get(i);
te.ticker = tickers.get(i);
}
//</fuckmefuckmefuckme>
if(trace.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
Entity hit = trace.entityHit;
if(hit != null && hit.getClass() == EntityZZombie.class) {
ZombieTC.network.sendToServer(new MessageShoot(player, trace.entityHit, this));
}
}
}
}
}
}
}
super.onUpdate(stack, world, entity, p_77663_4_, p_77663_5_);
}
public void drawUIFor(ItemStack stack, RenderGameOverlayEvent event) {
ensureTagCompund(stack);
NBTTagCompound tag = stack.getTagCompound();
int rounds = tag.getInteger("Rounds");
int totalAmmo = tag.getInteger("Ammo");
String out = "Ammo: " + rounds + "/" + clipSize + " - " + totalAmmo;
TextRenderHelper.drawString(out, event.resolution.getScaledWidth() - 2, 2, TextAlignment.Right);
if(tag.getInteger("Reload Timer") > 0) {
TextRenderHelper.drawString("Reloading...", event.resolution.getScaledWidth() - 2, 12, TextAlignment.Right);
}
}
} |
package net.minecraftforge.common;
import static net.minecraftforge.common.ForgeVersion.Status.*;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
public class ForgeVersion
{
//This number is incremented every time we remove deprecated code/major API changes, never reset
public static final int majorVersion = 11;
//This number is incremented every minecraft release, never reset
public static final int minorVersion = 14;
//This number is incremented every time a interface changes or new major feature is added, and reset every Minecraft version
public static final int revisionVersion = 2;
//This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
public static final int buildVersion = 0;
private static Status status = PENDING;
private static String target = null;
public static int getMajorVersion()
{
return majorVersion;
}
public static int getMinorVersion()
{
return minorVersion;
}
public static int getRevisionVersion()
{
return revisionVersion;
}
public static int getBuildVersion()
{
return buildVersion;
}
public static Status getStatus()
{
return status;
}
public static String getTarget()
{
return target;
}
public static String getVersion()
{
return String.format("%d.%d.%d.%d", majorVersion, minorVersion, revisionVersion, buildVersion);
}
public static enum Status
{
PENDING,
FAILED,
UP_TO_DATE,
OUTDATED,
AHEAD,
BETA,
BETA_OUTDATED
}
public static void startVersionCheck()
{
new Thread("Forge Version Check")
{
@SuppressWarnings("unchecked")
@Override
public void run()
{
try
{
URL url = new URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/promotions_slim.json");
InputStream con = url.openStream();
String data = new String(ByteStreams.toByteArray(con));
con.close();
Map<String, Object> json = new Gson().fromJson(data, Map.class);
//String homepage = (String)json.get("homepage");
Map<String, String> promos = (Map<String, String>)json.get("promos");
String rec = promos.get(MinecraftForge.MC_VERSION + "-recommended");
String lat = promos.get(MinecraftForge.MC_VERSION + "-latest");
ArtifactVersion current = new DefaultArtifactVersion(getVersion());
if (rec != null)
{
ArtifactVersion recommended = new DefaultArtifactVersion(rec);
int diff = recommended.compareTo(current);
if (diff == 0)
status = UP_TO_DATE;
else if (diff < 0)
{
status = AHEAD;
if (lat != null)
{
if (current.compareTo(new DefaultArtifactVersion(lat)) < 0)
{
status = OUTDATED;
target = lat;
}
}
}
else
{
status = OUTDATED;
target = rec;
}
}
else if (lat != null)
{
if (current.compareTo(new DefaultArtifactVersion(lat)) < 0)
{
status = BETA_OUTDATED;
target = lat;
}
else
status = BETA;
}
else
status = BETA;
}
catch (Exception e)
{
e.printStackTrace();
status = FAILED;
}
}
}.start();
}
} |
package monto.eclipse.launching;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;
import monto.eclipse.Activator;
import monto.eclipse.launching.debug.MontoDebugTarget;
import monto.eclipse.launching.debug.MontoLineBreakpoint;
import monto.service.command.CommandMessage;
import monto.service.command.Commands;
import monto.service.gson.GsonMonto;
import monto.service.launching.DebugLaunchConfiguration;
import monto.service.launching.LaunchConfiguration;
import monto.service.launching.debug.Breakpoint;
import monto.service.product.Products;
import monto.service.types.Language;
import monto.service.types.Source;
public class LaunchConfigurationDelegate implements ILaunchConfigurationDelegate {
private static int runSessionIdCounter = 0;
private static int debugSessionIdCounter = 1000000000;
@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch,
IProgressMonitor monitor) throws CoreException {
String mainClassPhysicalName =
configuration.getAttribute(MainClassLaunchConfigurationTab.ATTR_PHYSICAL_NAME, "");
String mainClassLogicalName =
configuration.getAttribute(MainClassLaunchConfigurationTab.ATTR_LOGICAL_NAME, "");
String mainClassLanguage =
configuration.getAttribute(MainClassLaunchConfigurationTab.ATTR_LAGUAGE, "");
Source source = new Source(mainClassPhysicalName, mainClassLogicalName);
Language language = new Language(mainClassLanguage);
if (mode.equals("run")) {
runSessionIdCounter += 1;
Activator.sendCommandMessage(
new CommandMessage(runSessionIdCounter, 1, Commands.RUN_LAUNCH_CONFIGURATION, language,
GsonMonto.toJsonTree(new LaunchConfiguration(source))));
launch.addProcess(createMontoProcess(launch, runSessionIdCounter, mode));
} else if (mode.equals("debug")) {
debugSessionIdCounter += 1;
IBreakpoint[] eclipseBreakpoints =
DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(Activator.PLUGIN_ID);
List<Breakpoint> breakpoints =
Arrays.stream(eclipseBreakpoints).flatMap(eclipseBreakpoint -> {
if (eclipseBreakpoint != null && eclipseBreakpoint instanceof MontoLineBreakpoint) {
MontoLineBreakpoint montoBreakpoint = (MontoLineBreakpoint) eclipseBreakpoint;
try {
return Stream.of(
new Breakpoint(montoBreakpoint.getSource(), montoBreakpoint.getLineNumber()));
} catch (CoreException e) {
System.err.printf("Couldn't translate MontoLineBreakpoint to Breakpoint: %s (%s)",
e.getClass().getName(), e.getMessage());
e.printStackTrace();
}
}
return Stream.empty();
}).collect(Collectors.toList());
Activator.sendCommandMessage(new CommandMessage(debugSessionIdCounter, 1,
Commands.DEBUG_LAUNCH_CONFIGURATION, language,
GsonMonto.toJsonTree(new DebugLaunchConfiguration(source, breakpoints))));
MontoProcess process = createMontoProcess(launch, debugSessionIdCounter, mode);
MontoDebugTarget debugTarget = new MontoDebugTarget(debugSessionIdCounter, launch, process);
Activator.getDefault().getDemultiplexer().addProductListener(Products.HIT_BREAKPOINT,
debugTarget::onBreakpointHit);
launch.addProcess(process);
launch.addDebugTarget(debugTarget);
debugTarget.fireEvent(DebugEvent.CREATE);
}
}
MontoProcess createMontoProcess(ILaunch launch, int sessionId, String mode) {
MontoProcess process = new MontoProcess(launch, sessionId, mode);
Activator.getDefault().getDemultiplexer().addProductListener(Products.STREAM_OUTPUT,
process::onStreamOutputProduct);
Activator.getDefault().getDemultiplexer().addProductListener(Products.PROCESS_TERMINATED,
process::onProcessTerminatedProduct);
return process;
}
} |
package nl.topicus.jdbc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Supplier;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.google.api.core.InternalApi;
import com.google.auth.Credentials;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.auth.oauth2.UserCredentials;
import com.google.cloud.ReadChannel;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.BatchClient;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.Operation;
import com.google.cloud.spanner.ResultSets;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Type.StructField;
import com.google.cloud.spanner.Value;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.rpc.Code;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata;
import nl.topicus.jdbc.MetaDataStore.TableKeyMetaData;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
import nl.topicus.jdbc.resultset.CloudSpannerResultSet;
import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement;
import nl.topicus.jdbc.statement.CloudSpannerStatement;
import nl.topicus.jdbc.transaction.CloudSpannerTransaction;
/**
* JDBC Driver for Google Cloud Spanner.
*
* @author loite
*
*/
public class CloudSpannerConnection extends AbstractCloudSpannerConnection {
public static class CloudSpannerDatabaseSpecification {
public final String project;
public final String instance;
public final String database;
private final String key;
public CloudSpannerDatabaseSpecification(String instance, String database) {
this(null, instance, database);
}
public CloudSpannerDatabaseSpecification(String project, String instance, String database) {
Preconditions.checkNotNull(instance);
Preconditions.checkNotNull(database);
this.project = project;
this.instance = instance;
this.database = database;
this.key = Objects.toString(project, "") + "/" + instance + "/" + database;
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof CloudSpannerDatabaseSpecification))
return false;
return ((CloudSpannerDatabaseSpecification) o).key.equals(key);
}
}
private static final String GOOGLE_CLOUD_STORAGE_PREFIX = "gs:
private final CloudSpannerDriver driver;
private final CloudSpannerDatabaseSpecification database;
private Spanner spanner;
private String clientId;
private DatabaseClient dbClient;
private DatabaseAdminClient adminClient;
private boolean autoCommit = true;
private boolean closed;
private boolean readOnly;
/**
* Special mode for Cloud Spanner: When the connection is in this mode, queries will be executed
* using the {@link BatchClient} instead of the default {@link DatabaseClient}
*/
private boolean originalBatchReadOnly;
private boolean batchReadOnly;
private final RunningOperationsStore operations = new RunningOperationsStore();
private final String url;
private final Properties suppliedProperties;
private boolean originalAllowExtendedMode;
private boolean allowExtendedMode;
private boolean originalAsyncDdlOperations;
private boolean asyncDdlOperations;
private boolean originalAutoBatchDdlOperations;
private boolean autoBatchDdlOperations;
private final List<String> autoBatchedDdlOperations = new ArrayList<>();
private boolean originalReportDefaultSchemaAsNull = true;
private boolean reportDefaultSchemaAsNull = true;
private boolean useCustomHost = false;
private String simulateProductName;
private Integer simulateMajorVersion;
private Integer simulateMinorVersion;
private CloudSpannerTransaction transaction;
private Timestamp lastCommitTimestamp;
private MetaDataStore metaDataStore;
private static int nextConnectionID = 1;
private final Logger logger;
private Map<String, Class<?>> typeMap = new HashMap<>();
@VisibleForTesting
CloudSpannerConnection() {
this(null);
}
@VisibleForTesting
CloudSpannerConnection(DatabaseClient dbClient, BatchClient batchClient) {
this.driver = null;
this.database = null;
this.url = null;
this.suppliedProperties = null;
this.logger = null;
this.dbClient = dbClient;
this.transaction = new CloudSpannerTransaction(dbClient, batchClient, this);
this.metaDataStore = new MetaDataStore(this);
}
@VisibleForTesting
CloudSpannerConnection(CloudSpannerDatabaseSpecification database) {
this.driver = null;
this.database = database;
this.url = null;
this.suppliedProperties = null;
this.logger = null;
this.transaction = new CloudSpannerTransaction(null, null, this);
this.metaDataStore = new MetaDataStore(this);
}
CloudSpannerConnection(CloudSpannerDriver driver, String url,
CloudSpannerDatabaseSpecification database, String credentialsPath, String oauthToken,
Properties suppliedProperties, boolean useCustomHost) throws SQLException {
this.driver = driver;
this.database = database;
this.url = url;
this.suppliedProperties = suppliedProperties;
int logLevel = CloudSpannerDriver.getLogLevel();
synchronized (CloudSpannerConnection.class) {
logger = new Logger(nextConnectionID++);
logger.setLogLevel(logLevel);
}
try {
Credentials credentials = null;
if (credentialsPath != null) {
credentials = getCredentialsFromFile(credentialsPath);
} else if (oauthToken != null) {
credentials = getCredentialsFromOAuthToken(oauthToken);
}
if (credentials != null) {
if (credentials instanceof UserCredentials) {
clientId = ((UserCredentials) credentials).getClientId();
}
if (credentials instanceof ServiceAccountCredentials) {
clientId = ((ServiceAccountCredentials) credentials).getClientId();
}
}
String host = null;
if (useCustomHost) {
// Extract host from url
int endIndex = url.indexOf(';');
if (endIndex == -1) {
endIndex = url.length();
}
host = url.substring("jdbc:cloudspanner:".length(), endIndex);
}
spanner = driver.getSpanner(database.project, credentials, host);
dbClient = spanner.getDatabaseClient(
DatabaseId.of(spanner.getOptions().getProjectId(), database.instance, database.database));
BatchClient batchClient = spanner.getBatchClient(
DatabaseId.of(spanner.getOptions().getProjectId(), database.instance, database.database));
adminClient = spanner.getDatabaseAdminClient();
transaction = new CloudSpannerTransaction(dbClient, batchClient, this);
metaDataStore = new MetaDataStore(this);
} catch (SpannerException e) {
throw new CloudSpannerSQLException(
"Error when opening Google Cloud Spanner connection: " + e.getMessage(), e);
} catch (IOException e) {
throw new CloudSpannerSQLException(
"Error when opening Google Cloud Spanner connection: " + e.getMessage(), Code.UNKNOWN, e);
}
}
public static GoogleCredentials getCredentialsFromOAuthToken(String oauthToken) {
GoogleCredentials credentials = null;
if (oauthToken != null && oauthToken.length() > 0) {
credentials = GoogleCredentials.create(new AccessToken(oauthToken, null));
}
return credentials;
}
public static GoogleCredentials getCredentialsFromFile(String credentialsPath)
throws IOException {
if (credentialsPath == null || credentialsPath.length() == 0)
throw new IllegalArgumentException("credentialsPath may not be null or empty");
GoogleCredentials credentials = null;
if (credentialsPath.startsWith(GOOGLE_CLOUD_STORAGE_PREFIX)) {
try {
Storage storage = StorageOptions.newBuilder().build().getService();
String bucketName = getBucket(credentialsPath);
String blobName = getBlob(credentialsPath);
Blob blob = storage.get(bucketName, blobName);
ReadChannel reader = blob.reader();
InputStream inputStream = Channels.newInputStream(reader);
credentials =
GoogleCredentials.fromStream(inputStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY);
} catch (Exception e) {
throw new IllegalArgumentException(
"Invalid credentials path: " + credentialsPath + ". Reason: " + e.getMessage(), e);
}
} else {
File credentialsFile = new File(credentialsPath);
if (!credentialsFile.isFile()) {
throw new IOException(String.format("Error reading credential file %s: File does not exist",
credentialsPath));
}
try (InputStream credentialsStream = new FileInputStream(credentialsFile)) {
credentials = GoogleCredentials.fromStream(credentialsStream,
CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY);
}
}
return credentials;
}
static String getBucket(String storageUrl) {
Preconditions.checkArgument(storageUrl.startsWith(GOOGLE_CLOUD_STORAGE_PREFIX),
String.format("Storage URL must start with %s", GOOGLE_CLOUD_STORAGE_PREFIX));
Preconditions.checkArgument(storageUrl.substring(5).contains("/"),
"Storage URL must contain a blob name");
return storageUrl.substring(5, storageUrl.indexOf('/', 5));
}
static String getBlob(String storageUrl) {
Preconditions.checkArgument(storageUrl.startsWith(GOOGLE_CLOUD_STORAGE_PREFIX),
String.format("Storage URL must start with %s", GOOGLE_CLOUD_STORAGE_PREFIX));
Preconditions.checkArgument(storageUrl.substring(5).contains("/"),
"Storage URL must contain a blob name");
return storageUrl.substring(storageUrl.indexOf('/', 5) + 1);
}
public static String getServiceAccountProjectId(String credentialsPath) {
String project = null;
if (credentialsPath != null) {
try (InputStream credentialsStream = new FileInputStream(credentialsPath)) {
JSONObject json = new JSONObject(new JSONTokener(credentialsStream));
project = json.getString("project_id");
} catch (IOException | JSONException ex) {
// ignore
}
}
return project;
}
Spanner getSpanner() {
return spanner;
}
public String getSimulateProductName() {
return simulateProductName;
}
@Override
public void setSimulateProductName(String productName) {
this.simulateProductName = productName;
}
public Integer getSimulateMajorVersion() {
return simulateMajorVersion;
}
@Override
public void setSimulateMajorVersion(Integer majorVersion) {
this.simulateMajorVersion = majorVersion;
}
public Integer getSimulateMinorVersion() {
return simulateMinorVersion;
}
@Override
public void setSimulateMinorVersion(Integer minorVersion) {
this.simulateMinorVersion = minorVersion;
}
/**
* Execute one or more DDL-statements on the database and wait for it to finish or return after
* syntax check (when running in async mode). Calling this method will also automatically commit
* the currently running transaction.
*
* @param inputSql The DDL-statement(s) to execute. Some statements may end up not being sent to
* Cloud Spanner if they contain IF [NOT] EXISTS clauses. The driver will check whether the
* condition is met, and only then will it be sent to Cloud Spanner.
* @return Nothing
* @throws SQLException If an error occurs during the execution of the statement.
*/
public Void executeDDL(List<String> inputSql) throws SQLException {
if (!getAutoCommit())
commit();
// Check for IF [NOT] EXISTS statements
List<String> sql = getActualSql(inputSql);
if (!sql.isEmpty()) {
try {
Operation<Void, UpdateDatabaseDdlMetadata> operation =
adminClient.updateDatabaseDdl(database.instance, database.database, sql, null);
if (asyncDdlOperations) {
operations.addOperation(sql, operation);
} else {
do {
operation = operation.waitFor();
} while (!operation.isDone());
}
return operation.getResult();
} catch (SpannerException e) {
throw new CloudSpannerSQLException("Could not execute DDL statement(s) "
+ String.join("\n;\n", sql) + ": " + e.getMessage(), e);
}
}
return null;
}
private List<String> getActualSql(List<String> sql) throws SQLException {
List<DDLStatement> statements = DDLStatement.parseDdlStatements(sql);
List<String> actualSql = new ArrayList<>(sql.size());
for (DDLStatement statement : statements) {
if (statement.shouldExecute(this)) {
actualSql.add(statement.getSql());
}
}
return actualSql;
}
/**
* Clears the asynchronous DDL-operations that have finished.
*
* @return The number of operations that were cleared
*/
public int clearFinishedDDLOperations() {
return operations.clearFinishedOperations();
}
/**
* Waits for all asynchronous DDL-operations that have been issued by this connection to finish.
*
* @throws SQLException If a database exception occurs while waiting for the operations to finish
*
*/
public void waitForDdlOperations() throws SQLException {
operations.waitForOperations();
}
/**
* Returns a ResultSet containing all asynchronous DDL-operations started by this connection. It
* does not contain DDL-operations that have been started by other connections or by other means.
*
* @param statement The statement that requested the operations
* @return A ResultSet with the DDL-operations
* @throws SQLException If a database error occurs
*/
public ResultSet getRunningDDLOperations(CloudSpannerStatement statement) throws SQLException {
return operations.getOperations(statement);
}
@Override
public String getProductName() {
if (getSimulateProductName() != null)
return getSimulateProductName();
return "Google Cloud Spanner";
}
@Override
public CloudSpannerStatement createStatement() throws SQLException {
checkClosed();
return new CloudSpannerStatement(this, dbClient);
}
@Override
public CloudSpannerPreparedStatement prepareStatement(String sql) throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
checkClosed();
throw new SQLFeatureNotSupportedException();
}
@Override
public String nativeSQL(String sql) throws SQLException {
checkClosed();
return sql;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
checkClosed();
if (autoCommit != this.autoCommit && isBatchReadOnly()) {
throw new CloudSpannerSQLException(
"The connection is currently in batch read-only mode. Please turn off batch read-only before changing auto-commit mode.",
Code.FAILED_PRECONDITION);
}
this.autoCommit = autoCommit;
}
@Override
public boolean getAutoCommit() throws SQLException {
checkClosed();
return autoCommit;
}
@Override
public void commit() throws SQLException {
checkClosed();
lastCommitTimestamp = getTransaction().commit();
}
@Override
public void rollback() throws SQLException {
checkClosed();
getTransaction().rollback();
}
public CloudSpannerTransaction getTransaction() {
return transaction;
}
@Override
public void close() throws SQLException {
if (closed)
return;
getTransaction().rollback();
closed = true;
driver.closeConnection(this);
}
@InternalApi
void markClosed() {
closed = true;
}
@Override
public boolean isClosed() throws SQLException {
return closed;
}
@Override
public CloudSpannerDatabaseMetaData getMetaData() throws SQLException {
checkClosed();
return new CloudSpannerDatabaseMetaData(this);
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
checkClosed();
if (readOnly != this.readOnly) {
if (getTransaction().isRunning()) {
throw new CloudSpannerSQLException(
"There is currently a transaction running. Commit or rollback the running transaction before changing read-only mode.",
Code.FAILED_PRECONDITION);
}
if (isBatchReadOnly()) {
throw new CloudSpannerSQLException(
"The connection is currently in batch read-only mode. Please turn off batch read-only before changing read-only mode.",
Code.FAILED_PRECONDITION);
}
}
this.readOnly = readOnly;
}
@Override
public boolean isReadOnly() throws SQLException {
checkClosed();
return readOnly;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
checkClosed();
if (level != Connection.TRANSACTION_SERIALIZABLE) {
throw new CloudSpannerSQLException(
"Transaction level " + level
+ " is not supported. Only Connection.TRANSACTION_SERIALIZABLE is supported",
Code.INVALID_ARGUMENT);
}
}
@Override
public int getTransactionIsolation() throws SQLException {
checkClosed();
return Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
checkClosed();
return new CloudSpannerStatement(this, dbClient);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
checkClosed();
return new CloudSpannerStatement(this, dbClient);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
checkClosed();
return new CloudSpannerPreparedStatement(sql, this, dbClient);
}
@Override
public String getUrl() {
return url;
}
@Override
public String getClientId() {
return clientId;
}
@Override
public boolean isValid(int timeout) throws SQLException {
if (isClosed())
return false;
Statement statement = createStatement();
statement.setQueryTimeout(timeout);
try (ResultSet rs = statement.executeQuery("SELECT 1")) {
if (rs.next())
return true;
}
return false;
}
@Override
public CloudSpannerArray createArrayOf(String typeName, Object[] elements) throws SQLException {
checkClosed();
return CloudSpannerArray.createArray(typeName, elements);
}
public TableKeyMetaData getTable(String name) throws SQLException {
return metaDataStore.getTable(name);
}
@Override
public Properties getSuppliedProperties() {
return suppliedProperties;
}
@Override
public boolean isAllowExtendedMode() {
return allowExtendedMode;
}
@Override
public int setAllowExtendedMode(boolean allowExtendedMode) {
this.allowExtendedMode = allowExtendedMode;
return 1;
}
boolean isOriginalAllowExtendedMode() {
return originalAllowExtendedMode;
}
void setOriginalAllowExtendedMode(boolean allowExtendedMode) {
this.originalAllowExtendedMode = allowExtendedMode;
}
@Override
public boolean isAsyncDdlOperations() {
return asyncDdlOperations;
}
@Override
public int setAsyncDdlOperations(boolean asyncDdlOperations) {
this.asyncDdlOperations = asyncDdlOperations;
return 1;
}
boolean isOriginalAsyncDdlOperations() {
return originalAsyncDdlOperations;
}
void setOriginalAsyncDdlOperations(boolean asyncDdlOperations) {
this.originalAsyncDdlOperations = asyncDdlOperations;
}
@Override
public boolean isAutoBatchDdlOperations() {
return autoBatchDdlOperations;
}
@Override
public int setAutoBatchDdlOperations(boolean autoBatchDdlOperations) {
clearAutoBatchedDdlOperations();
this.autoBatchDdlOperations = autoBatchDdlOperations;
return 1;
}
boolean isOriginalAutoBatchDdlOperations() {
return originalAutoBatchDdlOperations;
}
void setOriginalAutoBatchDdlOperations(boolean autoBatchDdlOperations) {
this.originalAutoBatchDdlOperations = autoBatchDdlOperations;
}
@Override
public boolean isReportDefaultSchemaAsNull() {
return reportDefaultSchemaAsNull;
}
@Override
public int setReportDefaultSchemaAsNull(boolean reportDefaultSchemaAsNull) {
this.reportDefaultSchemaAsNull = reportDefaultSchemaAsNull;
return 1;
}
boolean isOriginalReportDefaultSchemaAsNull() {
return originalReportDefaultSchemaAsNull;
}
void setOriginalReportDefaultSchemaAsNull(boolean reportDefaultSchemaAsNull) {
this.originalReportDefaultSchemaAsNull = reportDefaultSchemaAsNull;
}
/**
* Set a dynamic connection property, such as AsyncDdlOperations
*
* @param propertyName The name of the dynamic connection property
* @param propertyValue The value to set
* @return 1 if the property was set, 0 if not (this complies with the normal behaviour of
* executeUpdate(...) methods)
* @throws SQLException Throws {@link SQLException} if a database error occurs
*/
public int setDynamicConnectionProperty(String propertyName, String propertyValue)
throws SQLException {
return getPropertySetter(propertyName).apply(Boolean.valueOf(propertyValue));
}
/**
* Reset a dynamic connection property to its original value, such as AsyncDdlOperations
*
* @param propertyName The name of the dynamic connection property
* @return 1 if the property was reset, 0 if not (this complies with the normal behaviour of
* executeUpdate(...) methods)
* @throws SQLException Throws {@link SQLException} if a database error occurs
*/
public int resetDynamicConnectionProperty(String propertyName) throws SQLException {
return getPropertySetter(propertyName).apply(getOriginalValueGetter(propertyName).get());
}
private Supplier<Boolean> getOriginalValueGetter(String propertyName) {
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) {
return this::isOriginalAllowExtendedMode;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) {
return this::isOriginalAsyncDdlOperations;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) {
return this::isOriginalAutoBatchDdlOperations;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) {
return this::isOriginalReportDefaultSchemaAsNull;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.BATCH_READ_ONLY_MODE))) {
return this::isOriginalBatchReadOnly;
}
// Return a no-op to avoid null checks
return () -> false;
}
@FunctionalInterface
static interface SqlFunction<T, R> {
R apply(T t) throws SQLException;
}
private SqlFunction<Boolean, Integer> getPropertySetter(String propertyName) {
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) {
return this::setAllowExtendedMode;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) {
return this::setAsyncDdlOperations;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) {
return this::setAutoBatchDdlOperations;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) {
return this::setReportDefaultSchemaAsNull;
}
if (propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.BATCH_READ_ONLY_MODE))) {
return this::setBatchReadOnly;
}
// Return a no-op to avoid null checks
return x -> 0;
}
public ResultSet getDynamicConnectionProperties(CloudSpannerStatement statement)
throws SQLException {
return getDynamicConnectionProperty(statement, null);
}
public ResultSet getDynamicConnectionProperty(CloudSpannerStatement statement,
String propertyName) throws SQLException {
Map<String, String> values = new HashMap<>();
if (propertyName == null || propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) {
values.put(ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE),
String.valueOf(isAllowExtendedMode()));
}
if (propertyName == null || propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) {
values.put(ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS),
String.valueOf(isAsyncDdlOperations()));
}
if (propertyName == null || propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) {
values.put(
ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS),
String.valueOf(isAutoBatchDdlOperations()));
}
if (propertyName == null || propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) {
values.put(
ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL),
String.valueOf(isReportDefaultSchemaAsNull()));
}
if (propertyName == null || propertyName.equalsIgnoreCase(
ConnectionProperties.getPropertyName(ConnectionProperties.BATCH_READ_ONLY_MODE))) {
values.put(ConnectionProperties.getPropertyName(ConnectionProperties.BATCH_READ_ONLY_MODE),
String.valueOf(isBatchReadOnly()));
}
return createResultSet(statement, values);
}
private ResultSet createResultSet(CloudSpannerStatement statement, Map<String, String> values)
throws SQLException {
List<Struct> rows = new ArrayList<>(values.size());
for (Entry<String, String> entry : values.entrySet()) {
rows.add(Struct.newBuilder().set("NAME").to(Value.string(entry.getKey())).set("VALUE")
.to(Value.string(entry.getValue())).build());
}
com.google.cloud.spanner.ResultSet rs = ResultSets.forRows(
Type.struct(StructField.of("NAME", Type.string()), StructField.of("VALUE", Type.string())),
rows);
return new CloudSpannerResultSet(statement, rs, null);
}
public ResultSet getLastCommitTimestamp(CloudSpannerStatement statement) throws SQLException {
com.google.cloud.spanner.ResultSet rs = ResultSets.forRows(
Type.struct(StructField.of("COMMIT_TIMESTAMP", Type.timestamp())),
Arrays.asList(Struct.newBuilder().set("COMMIT_TIMESTAMP").to(lastCommitTimestamp).build()));
return new CloudSpannerResultSet(statement, rs, null);
}
/**
*
* @return The commit timestamp of the last transaction that committed succesfully
*/
@Override
public Timestamp getLastCommitTimestamp() {
return lastCommitTimestamp;
}
/**
*
* @return The read timestamp for the current read-only transaction, or null if there is no
* read-only transaction
*/
@Override
public Timestamp getReadTimestamp() {
return transaction == null ? null : transaction.getReadTimestamp();
}
/**
*
* @return A new connection with the same URL and properties as this connection. You can use this
* method if you want to open a new connection to the same database, for example to run a
* number of statements in a different transaction than the transaction you are currently
* using on this connection.
* @throws SQLException If an error occurs while opening the new connection
*/
public CloudSpannerConnection createCopyConnection() throws SQLException {
return (CloudSpannerConnection) DriverManager.getConnection(getUrl(), getSuppliedProperties());
}
public Logger getLogger() {
return logger;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
checkClosed();
return typeMap;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
checkClosed();
this.typeMap = map;
}
/**
*
* @return The number of nodes of this Cloud Spanner instance
* @throws SQLException If an exception occurs when trying to get the number of nodes
*/
public int getNodeCount() throws SQLException {
try {
if (database != null && database.instance != null) {
Instance instance = getSpanner().getInstanceAdminClient().getInstance(database.instance);
return instance == null ? 0 : instance.getNodeCount();
}
return 0;
} catch (SpannerException e) {
throw new CloudSpannerSQLException(e);
}
}
/**
* Prepare the current transaction by writing the mutations to the XA_TRANSACTIONS table instead
* of persisting them in the actual tables.
*
* @param xid The id of the prepared transaction
* @throws SQLException If an exception occurs while saving the mutations to the database for
* later commit
*/
public void prepareTransaction(String xid) throws SQLException {
getTransaction().prepareTransaction(xid);
}
/**
* Commit a previously prepared transaction.
*
* @param xid The id of the prepared transaction
* @throws SQLException If an error occurs when writing the mutations to the database
*/
public void commitPreparedTransaction(String xid) throws SQLException {
getTransaction().commitPreparedTransaction(xid);
}
/**
* Rollback a previously prepared transaction.
*
* @param xid The id of the prepared transaction to rollback
* @throws SQLException If an error occurs while rolling back the prepared transaction
*/
public void rollbackPreparedTransaction(String xid) throws SQLException {
getTransaction().rollbackPreparedTransaction(xid);
}
public List<String> getAutoBatchedDdlOperations() {
return Collections.unmodifiableList(autoBatchedDdlOperations);
}
public void clearAutoBatchedDdlOperations() {
autoBatchedDdlOperations.clear();
}
public void addAutoBatchedDdlOperation(String sql) {
autoBatchedDdlOperations.add(sql);
}
@Override
public boolean isBatchReadOnly() {
return batchReadOnly;
}
@Override
public int setBatchReadOnly(boolean batchReadOnly) throws SQLException {
checkClosed();
if (batchReadOnly != this.batchReadOnly) {
if (getAutoCommit()) {
throw new CloudSpannerSQLException(
"The connection is currently in auto-commit mode. Please turn off auto-commit before changing batch read-only mode.",
Code.FAILED_PRECONDITION);
}
if (getTransaction().isRunning()) {
throw new CloudSpannerSQLException(
"There is currently a transaction running. Commit or rollback the running transaction before changing batch read-only mode.",
Code.FAILED_PRECONDITION);
}
}
this.batchReadOnly = batchReadOnly;
return 1;
}
boolean isOriginalBatchReadOnly() {
return originalBatchReadOnly;
}
void setOriginalBatchReadOnly(boolean originalBatchReadOnly) {
this.originalBatchReadOnly = originalBatchReadOnly;
}
private void checkSavepointPossible() throws SQLException {
checkClosed();
if (getAutoCommit())
throw new CloudSpannerSQLException("Savepoints are not supported in autocommit mode",
Code.FAILED_PRECONDITION);
if (isReadOnly() || isBatchReadOnly())
throw new CloudSpannerSQLException("Savepoints are not supported in read-only mode",
Code.FAILED_PRECONDITION);
}
@Override
public Savepoint setSavepoint() throws SQLException {
checkSavepointPossible();
CloudSpannerSavepoint savepoint = CloudSpannerSavepoint.generated();
transaction.setSavepoint(savepoint);
return savepoint;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
checkSavepointPossible();
Preconditions.checkNotNull(name);
CloudSpannerSavepoint savepoint = CloudSpannerSavepoint.named(name);
transaction.setSavepoint(savepoint);
return savepoint;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
checkSavepointPossible();
Preconditions.checkNotNull(savepoint);
transaction.rollbackSavepoint(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkSavepointPossible();
Preconditions.checkNotNull(savepoint);
transaction.releaseSavepoint(savepoint);
}
@Override
public boolean isUseCustomHost() {
return useCustomHost;
}
void setUseCustomHost(boolean useCustomHost) {
this.useCustomHost = useCustomHost;
}
} |
package mu.nu.nullpo.game.subsystem.mode;
import mu.nu.nullpo.game.component.Block;
import mu.nu.nullpo.game.component.Controller;
import mu.nu.nullpo.game.component.Piece;
import mu.nu.nullpo.game.event.EventReceiver;
import mu.nu.nullpo.game.play.GameEngine;
import mu.nu.nullpo.game.play.GameManager;
import mu.nu.nullpo.util.CustomProperties;
import mu.nu.nullpo.util.GeneralUtil;
/**
* AVALANCHE FEVER MARATHON mode (Release Candidate 1)
*/
public class AvalancheFeverMode extends DummyMode {
/** Current version */
private static final int CURRENT_VERSION = 0;
/** Enabled piece types */
private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0};
/** Block colors */
private static final int[] BLOCK_COLORS =
{
Block.BLOCK_COLOR_RED,
Block.BLOCK_COLOR_GREEN,
Block.BLOCK_COLOR_BLUE,
Block.BLOCK_COLOR_YELLOW,
Block.BLOCK_COLOR_PURPLE
};
private static final int[] CHAIN_POWERS =
{
4, 10, 18, 22, 30, 48, 80, 120, 160, 240, 280, 288, 342, 400, 440, 480, 520, 560, 600, 640, 680, 720, 760, 800 //Amitie
};
public int[] tableGravityChangeScore =
{
15000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000, 150000, 250000, 400000, Integer.MAX_VALUE
};
public int[] tableGravityValue =
{
1, 2, 3, 4, 6, 8, 10, 20, 30, 60, 120, 180, 300, -1
};
/** Fever map files list */
private static final String[] FEVER_MAPS =
{
"Fever", "15th", "15thDS", "7"
};
/** Names of chain display settings */
private static final String[] CHAIN_DISPLAY_NAMES = {"OFF", "YELLOW", "SIZE"};
/** Number of ranking records */
private static final int RANKING_MAX = 10;
/** Time limit */
private static final int TIME_LIMIT = 3600;
/** GameManager object (Manages entire game status) */
private GameManager owner;
/** EventReceiver object (This receives many game events, can also be used for drawing the fonts.) */
private EventReceiver receiver;
/** Current numbertableGravityChangeLevel level1 */
private int gravityindex;
/** Amount of points earned from most recent clear */
private int lastscore, lastmultiplier;
/** Elapsed time from last line clear (lastscore is displayed to screen until this reaches to 120) */
private int scgettime;
/** Selected game type */
private int mapSet;
/** Outline type */
private int outlinetype;
/** Version number */
private int version;
/** Current round's ranking rank */
private int rankingRank;
/** Rankings' line counts */
private int[][][] rankingScore;
/** Rankings' times */
private int[][][] rankingTime;
/** Flag for all clear */
private int zenKeshiDisplay;
/** Flag set to true if first group in the chain is larger minimum size */
//private boolean firstExtra;
/** Amount of garbage sent */
private int garbageSent, garbageAdd;
/** Number of colors to use */
private int numColors;
/** Time limit left */
private int timeLimit;
/** Time added to limit */
private int timeLimitAdd;
/** Time to display added time */
private int timeLimitAddDisplay;
/** Fever map CustomProperties */
private CustomProperties propFeverMap;
/** Chain levels for Fever Mode */
private int feverChain;
/** Chain level boundaries for Fever Mode */
private int feverChainMin, feverChainMax;
/** Flag set to true when last piece caused a clear */
private boolean cleared;
/** Flag for all-clears */
private boolean zenKeshi;
/** Number of all clears */
private int zenKeshiCount;
/** Max chain */
private int maxChain;
/** List of subsets in selected map */
private String[] mapSubsets;
/** Last chain hit number */
private int chain;
/** Time to display last chain */
private int chainDisplay;
/** Fever chain count when last chain hit occurred */
private int feverChainDisplay;
/** Type of chain display */
private int chainDisplayType;
/** Score before adding zenkeshi bonus and max chain bonus */
private int scoreBeforeBonus;
/** Zenkeshi bonus and max chain bonus amounts */
private int zenKeshiBonus, maxChainBonus;
/** Number of boards played */
private int boardsPlayed;
/** Blocks cleared */
private int blocksCleared;
/** Current level */
private int level;
/** Blocks blocksCleared needed to reach next level */
private int toNextLevel;
/** Level at start of chain */
private int chainLevelMultiplier;
/*
* Mode name
*/
@Override
public String getName() {
return "AVALANCHE 1P FEVER MARATHON (RC1)";
}
/*
* Initialization
*/
@Override
public void playerInit(GameEngine engine, int playerID) {
owner = engine.owner;
receiver = engine.owner.receiver;
lastscore = 0;
lastmultiplier = 0;
scgettime = 0;
outlinetype = 0;
zenKeshiDisplay = 0;
garbageSent = 0;
garbageAdd = 0;
//firstExtra = false;
cleared = false;
zenKeshi = false;
zenKeshiCount = 0;
maxChain = 0;
scoreBeforeBonus = 0;
zenKeshiBonus = 0;
maxChainBonus = 0;
boardsPlayed = 0;
blocksCleared = 0;
timeLimit = TIME_LIMIT;
timeLimitAdd = 0;
timeLimitAddDisplay = 0;
chain = 0;
chainDisplay = 0;
feverChainDisplay = 0;
chainDisplayType = 0;
feverChain = 5;
rankingRank = -1;
rankingScore = new int[3][FEVER_MAPS.length][RANKING_MAX];
rankingTime = new int[3][FEVER_MAPS.length][RANKING_MAX];
if(owner.replayMode == false) {
loadSetting(owner.modeConfig);
loadRanking(owner.modeConfig, engine.ruleopt.strRuleName);
version = CURRENT_VERSION;
} else {
loadSetting(owner.replayProp);
}
engine.framecolor = GameEngine.FRAME_COLOR_PURPLE;
engine.clearMode = GameEngine.CLEAR_COLOR;
engine.garbageColorClear = true;
engine.colorClearSize = 4;
engine.ignoreHidden = true;
engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE;
for(int i = 0; i < Piece.PIECE_COUNT; i++)
engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1);
engine.randomBlockColor = true;
engine.blockColors = BLOCK_COLORS;
engine.connectBlocks = false;
engine.cascadeDelay = 1;
engine.cascadeClearDelay = 10;
/*
engine.fieldWidth = 6;
engine.fieldHeight = 12;
engine.fieldHiddenHeight = 2;
*/
}
/**
* Set the gravity rate
* @param engine GameEngine
*/
public void setSpeed(GameEngine engine) {
if (mapSet == 0) {
int speedlv = engine.statistics.score;
if (speedlv < 0) speedlv = 0;
if (speedlv > 5000) speedlv = 5000;
while(speedlv >= tableGravityChangeScore[gravityindex]) gravityindex++;
engine.speed.gravity = tableGravityValue[gravityindex];
} else {
engine.speed.gravity = 1;
}
engine.speed.denominator = 256;
}
public boolean onReady(GameEngine engine, int playerID) {
if(engine.statc[0] == 0)
{
loadMapSetFever(engine, playerID, mapSet, true);
engine.numColors = numColors;
loadFeverMap(engine, playerID, feverChain);
timeLimit = TIME_LIMIT;
timeLimitAdd = 0;
timeLimitAddDisplay = 0;
if(outlinetype == 0) engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_NORMAL;
if(outlinetype == 1) engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_SAMECOLOR;
if(outlinetype == 2) engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_NONE;
if (numColors == 3) level = 1;
else if (numColors == 4) level = 5;
else if (numColors == 5) level = 10;
chainLevelMultiplier = level;
toNextLevel = 15;
zenKeshiCount = 0;
maxChain = 0;
scoreBeforeBonus = 0;
zenKeshiBonus = 0;
maxChainBonus = 0;
blocksCleared = 0;
}
return false;
}
/*
* Called at settings screen
*/
@Override
public boolean onSetting(GameEngine engine, int playerID) {
// Menu
if(engine.owner.replayMode == false) {
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) {
engine.statc[2]
if(engine.statc[2] < 0) engine.statc[2] = 3;
engine.playSE("cursor");
}
// Down
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) {
engine.statc[2]++;
if(engine.statc[2] > 3) engine.statc[2] = 0;
engine.playSE("cursor");
}
// Configuration changes
int change = 0;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1;
if(change != 0) {
engine.playSE("change");
switch(engine.statc[2]) {
case 0:
mapSet += change;
if(mapSet < 0) mapSet = FEVER_MAPS.length - 1;
if(mapSet > FEVER_MAPS.length - 1) mapSet = 0;
break;
case 1:
outlinetype += change;
if(outlinetype < 0) outlinetype = 2;
if(outlinetype > 2) outlinetype = 0;
break;
case 2:
numColors += change;
if(numColors < 3) numColors = 5;
if(numColors > 5) numColors = 3;
break;
case 3:
chainDisplayType += change;
if(chainDisplayType < 0) chainDisplayType = 2;
if(chainDisplayType > 2) chainDisplayType = 0;
break;
}
}
if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) {
engine.playSE("decide");
saveSetting(owner.modeConfig);
receiver.saveModeConfig(owner.modeConfig);
return false;
}
// Cancel
if(engine.ctrl.isPush(Controller.BUTTON_B)) {
engine.quitflag = true;
}
engine.statc[3]++;
} else {
engine.statc[3]++;
engine.statc[2] = -1;
if(engine.statc[3] >= 60) {
return false;
}
}
return true;
}
/*
* Render the settings screen
*/
@Override
public void renderSetting(GameEngine engine, int playerID) {
if(engine.owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, (engine.statc[2] * 2) + 1, "b", EventReceiver.COLOR_RED);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "MAP SET", EventReceiver.COLOR_BLUE);
receiver.drawMenuFont(engine, playerID, 1, 1, FEVER_MAPS[mapSet].toUpperCase(), (engine.statc[2] == 0));
receiver.drawMenuFont(engine, playerID, 0, 2, "OUTLINE", EventReceiver.COLOR_BLUE);
String strOutline = "";
if(outlinetype == 0) strOutline = "NORMAL";
if(outlinetype == 1) strOutline = "COLOR";
if(outlinetype == 2) strOutline = "NONE";
receiver.drawMenuFont(engine, playerID, 1, 3, strOutline, (engine.statc[2] == 1));
receiver.drawMenuFont(engine, playerID, 0, 4, "COLORS", EventReceiver.COLOR_BLUE);
receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(numColors), (engine.statc[2] == 2));
receiver.drawMenuFont(engine, playerID, 0, 6, "SHOW CHAIN", EventReceiver.COLOR_BLUE);
receiver.drawMenuFont(engine, playerID, 1, 7, CHAIN_DISPLAY_NAMES[chainDisplayType], (engine.statc[2] == 3));
}
/*
* Called for initialization during "Ready" screen
*/
@Override
public void startGame(GameEngine engine, int playerID) {
engine.comboType = GameEngine.COMBO_TYPE_DISABLE;
engine.tspinEnable = false;
engine.useAllSpinBonus = false;
engine.tspinAllowKick = false;
engine.speed.are = 30;
engine.speed.areLine = 30;
engine.speed.das = 10;
engine.speed.lockDelay = 60;
setSpeed(engine);
}
/*
* Render score
*/
@Override
public void renderLast(GameEngine engine, int playerID) {
receiver.drawScoreFont(engine, playerID, 0, 0, "AVALANCHE FEVER MARATHON", EventReceiver.COLOR_DARKBLUE);
receiver.drawScoreFont(engine, playerID, 0, 1, "(" + FEVER_MAPS[mapSet].toUpperCase() + " " +
numColors + " COLORS)", EventReceiver.COLOR_DARKBLUE);
if( (engine.stat == GameEngine.STAT_SETTING) || ((engine.stat == GameEngine.STAT_RESULT) && (owner.replayMode == false)) ) {
if((owner.replayMode == false) && (engine.ai == null)) {
receiver.drawScoreFont(engine, playerID, 3, 3, "SCORE TIME", EventReceiver.COLOR_BLUE);
for(int i = 0; i < RANKING_MAX; i++) {
receiver.drawScoreFont(engine, playerID, 0, 4 + i, String.format("%2d", i + 1), EventReceiver.COLOR_YELLOW);
receiver.drawScoreFont(engine, playerID, 3, 4 + i, String.valueOf(rankingScore[numColors-3][mapSet][i]), (i == rankingRank));
receiver.drawScoreFont(engine, playerID, 14, 4 + i, GeneralUtil.getTime(rankingTime[numColors-3][mapSet][i]), (i == rankingRank));
}
}
} else {
receiver.drawScoreFont(engine, playerID, 0, 3, "SCORE", EventReceiver.COLOR_BLUE);
String strScore;
if((lastscore == 0) || (lastmultiplier == 0) || (scgettime <= 0)) {
strScore = String.valueOf(engine.statistics.score);
} else {
strScore = String.valueOf(engine.statistics.score) + "(+" + String.valueOf(lastscore) + "X" +
String.valueOf(lastmultiplier) + ")";
}
receiver.drawScoreFont(engine, playerID, 0, 4, strScore);
receiver.drawScoreFont(engine, playerID, 0, 6, "LEVEL", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 0, 7, String.valueOf(level));
receiver.drawScoreFont(engine, playerID, 0, 9, "TIME", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 0, 10, GeneralUtil.getTime(engine.statistics.time));
receiver.drawScoreFont(engine, playerID, 0, 12, "LIMIT TIME", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 0, 13, GeneralUtil.getTime(timeLimit));
if (timeLimitAddDisplay > 0)
receiver.drawScoreFont(engine, playerID, 0, 14, "(+" + (timeLimitAdd/60) + " SEC.)");
String timeStr = String.valueOf(timeLimit/60);
if (timeStr.length() == 1)
timeStr = "0" + timeStr;
receiver.drawMenuFont(engine, playerID, 2, 0, timeStr, EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, 11, 6, "BOARDS", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 11, 7, String.valueOf(boardsPlayed));
receiver.drawScoreFont(engine, playerID, 11, 9, "ZENKESHI", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 11, 10, String.valueOf(zenKeshiCount));
receiver.drawScoreFont(engine, playerID, 11, 12, "MAX CHAIN", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 11, 13, String.valueOf(maxChain));
receiver.drawScoreFont(engine, playerID, 11, 15, "OJAMA SENT", EventReceiver.COLOR_BLUE);
String strSent = String.valueOf(garbageSent);
if(garbageAdd > 0) {
strSent = strSent + "(+" + String.valueOf(garbageAdd)+ ")";
}
receiver.drawScoreFont(engine, playerID, 11, 16, strSent);
receiver.drawScoreFont(engine, playerID, 11, 18, "CLEARED", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 11, 19, String.valueOf(blocksCleared));
int textHeight = 13;
if (engine.field != null)
textHeight = engine.field.getHeight()+1;
if (chain > 0 && chainDisplay > 0 && chainDisplayType != 0)
{
int color = EventReceiver.COLOR_YELLOW;
if (chainDisplayType == 2)
{
if (chain >= feverChainDisplay)
color = EventReceiver.COLOR_GREEN;
else if (chain == feverChainDisplay-2)
color = EventReceiver.COLOR_ORANGE;
else if (chain < feverChainDisplay-2)
color = EventReceiver.COLOR_RED;
}
receiver.drawMenuFont(engine, playerID, chain > 9 ? 0 : 1, textHeight, chain + " CHAIN!", color);
}
if (zenKeshiDisplay > 0)
receiver.drawMenuFont(engine, playerID, 0, textHeight+1, "ZENKESHI!", EventReceiver.COLOR_YELLOW);
}
}
public boolean onMove (GameEngine engine, int playerID) {
cleared = false;
zenKeshi = false;
return false;
}
/*
* Called after every frame
*/
@Override
public void onLast(GameEngine engine, int playerID) {
if (scgettime > 0) scgettime
if (engine.timerActive)
{
if (chainDisplay > 0)
chainDisplay
if (zenKeshiDisplay > 0)
zenKeshiDisplay
if (timeLimit > 0)
{
if (timeLimit == 1)
engine.playSE("levelstop");
timeLimit
}
}
if (timeLimitAddDisplay > 0)
timeLimitAddDisplay
// timeMeter
engine.meterValue = (timeLimit * receiver.getMeterMax(engine)) / TIME_LIMIT;
engine.meterColor = GameEngine.METER_COLOR_GREEN;
if(timeLimit <= 1800) engine.meterColor = GameEngine.METER_COLOR_YELLOW;
if(timeLimit <= 900) engine.meterColor = GameEngine.METER_COLOR_ORANGE;
if(timeLimit <=
300) engine.meterColor = GameEngine.METER_COLOR_RED;
}
@Override
public boolean onGameOver(GameEngine engine, int playerID) {
if(engine.statc[0] == 0)
{
scoreBeforeBonus = engine.statistics.score;
if (numColors >= 5)
zenKeshiBonus = zenKeshiCount*zenKeshiCount*1000;
else if (numColors == 4)
zenKeshiBonus = zenKeshiCount*(zenKeshiCount+1)*500;
else
zenKeshiBonus = zenKeshiCount*(zenKeshiCount+3)*250;
maxChainBonus = maxChain*maxChain*2000;
engine.statistics.score += zenKeshiBonus + maxChainBonus;
}
return false;
}
/*
* Hard drop
*/
@Override
public void afterHardDropFall(GameEngine engine, int playerID, int fall) {
engine.statistics.score += fall;
}
/*
* Hard drop
*/
@Override
public void afterSoftDropFall(GameEngine engine, int playerID, int fall) {
engine.statistics.score += fall;
}
/*
* Calculate score
*/
@Override
public void calcScore(GameEngine engine, int playerID, int avalanche) {
// Line clear bonus
int pts = avalanche*10;
if (avalanche > 0) {
cleared = true;
if (engine.field.isEmpty()) {
engine.playSE("bravo");
zenKeshi = true;
zenKeshiDisplay = 120;
zenKeshiCount++;
// engine.statistics.score += 2100;
}
chain = engine.chain;
if (chain == 1)
chainLevelMultiplier = level;
if (chain > maxChain)
maxChain = chain;
blocksCleared += avalanche;
toNextLevel -= avalanche;
if (toNextLevel <= 0)
{
toNextLevel = 15;
if (level < 99)
level++;
}
pts *= chainLevelMultiplier;
chainDisplay = 60;
feverChainDisplay = feverChain;
engine.playSE("combo" + Math.min(chain, 20));
int multiplier = engine.field.colorClearExtraCount;
if (engine.field.colorsCleared > 1)
multiplier += (engine.field.colorsCleared-1)*2;
if (chain > CHAIN_POWERS.length)
multiplier += CHAIN_POWERS[CHAIN_POWERS.length-1];
else
multiplier += CHAIN_POWERS[chain-1];
if (multiplier > 999)
multiplier = 999;
if (multiplier < 1)
multiplier = 1;
lastscore = pts;
lastmultiplier = multiplier;
scgettime = 120;
int score = pts*multiplier;
engine.statistics.scoreFromLineClear += score;
engine.statistics.score += score;
garbageAdd += ((avalanche*10*multiplier)+119)/120;
setSpeed(engine);
}
}
public boolean lineClearEnd(GameEngine engine, int playerID) {
if (garbageAdd > 0)
{
garbageSent += garbageAdd;
garbageAdd = 0;
}
int feverChainNow = feverChain;
if (cleared)
{
boardsPlayed++;
timeLimitAdd = 0;
if (zenKeshi && timeLimit > 0)
{
if (timeLimit > 0)
timeLimitAdd += 180;
feverChain += 2;
if (feverChain > feverChainMax)
feverChain = feverChainMax;
}
if (timeLimit > 0)
{
int addTime = (engine.chain-2)*60;
if (addTime > 0)
timeLimitAdd += addTime;
if (timeLimitAdd > 0)
{
timeLimit += timeLimitAdd;
timeLimitAddDisplay = 120;
}
}
int chainShort = feverChainNow - engine.chain;
if (chainShort <= 0)
{
engine.playSE("cool");
if (feverChain < feverChainMax)
feverChain++;
}
else if(chainShort == 2)
{
engine.playSE("regret");
feverChain
}
else if (chainShort > 2)
{
engine.playSE("regret");
feverChain-=2;
}
if (feverChain < feverChainMin)
feverChain = feverChainMin;
if (timeLimit > 0)
loadFeverMap(engine, playerID, feverChain);
}
else if (engine.field != null)
{
if (!engine.field.getBlockEmpty(2, 0) || !engine.field.getBlockEmpty(3, 0))
{
engine.stat = GameEngine.STAT_GAMEOVER;
engine.gameActive = false;
engine.resetStatc();
engine.statc[1] = 1;
}
}
// time
if((timeLimit <= 0) && (engine.timerActive == true)) {
engine.gameActive = false;
engine.timerActive = false;
engine.resetStatc();
engine.stat = GameEngine.STAT_ENDINGSTART;
}
return false;
}
/*
* Render results screen
*/
@Override
public void renderResult(GameEngine engine, int playerID) {
receiver.drawMenuFont(engine, playerID, 0, 1, "PLAY DATA", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 0, 3, "SCORE", EventReceiver.COLOR_BLUE);
String strScoreBefore = String.format("%10d", scoreBeforeBonus);
receiver.drawMenuFont(engine, playerID, 0, 4, strScoreBefore, EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 0, 5, "ZENKESHI", EventReceiver.COLOR_BLUE);
String strZenKeshi = String.format("%10d", zenKeshiCount);
receiver.drawMenuFont(engine, playerID, 0, 6, strZenKeshi);
String strZenKeshiBonus = "+" + zenKeshiBonus;
receiver.drawMenuFont(engine, playerID, 10-strZenKeshiBonus.length(), 7, strZenKeshiBonus, EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 0, 8, "MAX CHAIN", EventReceiver.COLOR_BLUE);
String strMaxChain = String.format("%10d", maxChain);
receiver.drawMenuFont(engine, playerID, 0, 9, strMaxChain);
String strMaxChainBonus = "+" + maxChainBonus;
receiver.drawMenuFont(engine, playerID, 10-strMaxChainBonus.length(), 10, strMaxChainBonus, EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 0, 11, "TOTAL", EventReceiver.COLOR_BLUE);
String strScore = String.format("%10d", engine.statistics.score);
receiver.drawMenuFont(engine, playerID, 0, 12, strScore, EventReceiver.COLOR_RED);
receiver.drawMenuFont(engine, playerID, 0, 13, "TIME", EventReceiver.COLOR_BLUE);
String strTime = String.format("%10s", GeneralUtil.getTime(engine.statistics.time));
receiver.drawMenuFont(engine, playerID, 0, 14, strTime);
if(rankingRank != -1) {
receiver.drawMenuFont(engine, playerID, 0, 15, "RANK", EventReceiver.COLOR_BLUE);
String strRank = String.format("%10d", rankingRank + 1);
receiver.drawMenuFont(engine, playerID, 0, 16, strRank);
}
}
/*
* Called when saving replay
*/
@Override
public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) {
saveSetting(prop);
// Update rankings
if((owner.replayMode == false) && (engine.ai == null)) {
updateRanking(engine.statistics.score, engine.statistics.time, mapSet, numColors);
if(rankingRank != -1) {
saveRanking(owner.modeConfig, engine.ruleopt.strRuleName);
receiver.saveModeConfig(owner.modeConfig);
}
}
}
/**
* Load settings from property file
* @param prop Property file
*/
private void loadSetting(CustomProperties prop) {
mapSet = prop.getProperty("avalanchefever.gametype", 0);
outlinetype = prop.getProperty("avalanchefever.outlinetype", 0);
numColors = prop.getProperty("avalanchefever.numcolors", 5);
version = prop.getProperty("avalanchefever.version", 0);
chainDisplayType = prop.getProperty("avalanchefever.chainDisplayType", 1);
}
/**
* Save settings to property file
* @param prop Property file
*/
private void saveSetting(CustomProperties prop) {
prop.setProperty("avalanchefever.gametype", mapSet);
prop.setProperty("avalanchefever.outlinetype", outlinetype);
prop.setProperty("avalanchefever.numcolors", numColors);
prop.setProperty("avalanchefever.version", version);
prop.setProperty("avalanchefever.chainDisplayType", chainDisplayType);
}
private void loadMapSetFever(GameEngine engine, int playerID, int id, boolean forceReload) {
if((propFeverMap == null) || (forceReload)) {
propFeverMap = receiver.loadProperties("config/map/avalanche/" +
FEVER_MAPS[id] + "Endless.map");
feverChainMin = propFeverMap.getProperty("minChain", 3);
feverChainMax = propFeverMap.getProperty("maxChain", 15);
String subsets = propFeverMap.getProperty("sets");
mapSubsets = subsets.split(",");
}
}
private void loadFeverMap(GameEngine engine, int playerID, int chain) {
engine.createFieldIfNeeded();
engine.field.reset();
engine.field.stringToField(propFeverMap.getProperty(
mapSubsets[engine.random.nextInt(mapSubsets.length)] +
"." + numColors + "colors." + chain + "chain"));
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT, false);
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN, false);
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP, false);
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT, false);
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE, false);
engine.field.setAllAttribute(Block.BLOCK_ATTRIBUTE_ANTIGRAVITY, false);
engine.field.setAllSkin(engine.getSkin());
engine.field.shuffleColors(BLOCK_COLORS, numColors, engine.random);
}
/**
* Read rankings from property file
* @param prop Property file
* @param ruleName Rule name
*/
private void loadRanking(CustomProperties prop, String ruleName) {
for(int i = 0; i < RANKING_MAX; i++) {
for(int j = 0; j < FEVER_MAPS.length; j++) {
for(int colors = 3; colors <= 5; colors++) {
rankingScore[colors-3][j][i] = prop.getProperty("avalanchefever.ranking." + ruleName + "." + colors +
"colors." + FEVER_MAPS[j] + ".score." + i, 0);
rankingTime[colors-3][j][i] = prop.getProperty("avalanchefever.ranking." + ruleName + "." + colors +
"colors." + FEVER_MAPS[j] + ".time." + i, -1);
}
}
}
}
/**
* Save rankings to property file
* @param prop Property file
* @param ruleName Rule name
*/
private void saveRanking(CustomProperties prop, String ruleName) {
for(int i = 0; i < RANKING_MAX; i++) {
for(int j = 0; j < FEVER_MAPS.length; j++) {
for(int colors = 3; colors <= 5; colors++) {
prop.setProperty("avalanchefever.ranking." + ruleName + "." + colors +
"colors." + FEVER_MAPS[j] + ".score." + i, rankingScore[colors-3][j][i]);
prop.setProperty("avalanchefever.ranking." + ruleName + "." + colors +
"colors." + FEVER_MAPS[j] + ".time." + i, rankingTime[colors-3][j][i]);
}
}
}
}
/**
* Update rankings
* @param sc Score
* @param li Lines
* @param time Time
*/
private void updateRanking(int sc, int time, int type, int colors) {
rankingRank = checkRanking(sc, time, type, colors);
if(rankingRank != -1) {
// Shift down ranking entries
for(int i = RANKING_MAX - 1; i > rankingRank; i
rankingScore[colors-3][type][i] = rankingScore[colors-3][type][i - 1];
rankingTime[colors-3][type][i] = rankingTime[colors-3][type][i - 1];
}
// Add new data
rankingScore[colors-3][type][rankingRank] = sc;
rankingTime[colors-3][type][rankingRank] = time;
}
}
/**
* Calculate ranking position
* @param sc Score
* @param time Time
* @return Position (-1 if unranked)
*/
private int checkRanking(int sc, int time, int type, int colors) {
for(int i = 0; i < RANKING_MAX; i++) {
if(sc > rankingScore[colors-3][type][i]) {
return i;
} else if((sc == rankingScore[colors-3][type][i]) && (time < rankingTime[colors-3][type][i])) {
return i;
}
}
return -1;
}
} |
/*
* ProcessLineOfHapmap
*/
package net.maizegenetics.pal.alignment;
import java.util.LinkedList;
import java.util.Queue;
import net.maizegenetics.baseplugins.FileLoadPlugin;
import net.maizegenetics.util.BitUtil;
import net.maizegenetics.util.OpenBitSet;
/**
*
* @author terry
*/
public class ProcessLineOfHapmap implements Runnable {
private static int myNumInstances = 0;
private static Queue myInstances = new LinkedList();
private String[][] myTokens;
private int mySite;
private int myNumTaxa;
private int myLineInFile;
private boolean myComplete = false;
private OpenBitSet[][] myData;
private byte[][] myAlleles;
private int[][] myAlleleMappings;
private int myNumAlleles;
private int myNumDataRows;
private boolean myRetainRareAlleles;
private boolean myIsSBit;
private int myNumSitesToProcess;
private ProcessLineOfHapmap(byte[][] alleles, OpenBitSet[][] data, boolean retainRareAlleles, String[][] tokens, int numSitesToProcess, int site, int numTaxa, int lineInFile, boolean isSBit) {
setVariables(alleles, data, retainRareAlleles, tokens, numSitesToProcess, site, numTaxa, lineInFile, isSBit);
}
public static ProcessLineOfHapmap getInstance(byte[][] alleles, OpenBitSet[][] data, boolean retainRareAlleles, String[][] tokens, int numSitesToProcess, int site, int numTaxa, int lineInFile, boolean isSBit) {
if (myNumInstances <= 35) {
return new ProcessLineOfHapmap(alleles, data, retainRareAlleles, tokens, numSitesToProcess, site, numTaxa, lineInFile, isSBit);
} else {
ProcessLineOfHapmap result;
while ((result = (ProcessLineOfHapmap) myInstances.poll()) == null) {
}
result.setVariables(alleles, data, retainRareAlleles, tokens, numSitesToProcess, site, numTaxa, lineInFile, isSBit);
return result;
}
}
private void setVariables(byte[][] alleles, OpenBitSet[][] data, boolean retainRareAlleles, String[][] tokens, int numSitesToProcess, int site, int numTaxa, int lineInFile, boolean isSBit) {
myData = data;
myTokens = tokens;
myNumSitesToProcess = numSitesToProcess;
if (myNumSitesToProcess > 64) {
throw new IllegalStateException("ProcessLineOfHapmap: setVariables: Can't process more than 64 sites: " + myNumSitesToProcess);
}
mySite = site;
myNumTaxa = numTaxa;
myLineInFile = lineInFile;
myComplete = false;
myAlleles = alleles;
myNumAlleles = myAlleles[0].length;
myAlleleMappings = new int[myNumSitesToProcess][16];
for (int s = 0; s < myNumSitesToProcess; s++) {
for (int i = 0; i < 16; i++) {
myAlleleMappings[s][i] = -1;
}
}
myRetainRareAlleles = retainRareAlleles;
myNumDataRows = myNumAlleles;
if (myRetainRareAlleles) {
myNumDataRows++;
}
if (myNumDataRows != myData.length) {
throw new IllegalStateException("ProcessLineOfHapmap: setVariables: number of data rows: " + myNumDataRows + " should equal first dimension of data array: " + myData.length);
}
myIsSBit = isSBit;
}
private void clearVariables() {
myData = null;
myTokens = null;
myAlleles = null;
myAlleleMappings = null;
}
public void run() {
try {
if (myComplete) {
throw new IllegalStateException("ImportUtils: ProcessLineOfHapmap: run: trying to run completed instance.");
}
myComplete = true;
byte[][] data = new byte[myNumSitesToProcess][myNumTaxa];
for (int s = 0; s < myNumSitesToProcess; s++) {
for (int i = 0; i < myNumTaxa; i++) {
try {
data[s][i] = NucleotideAlignmentConstants.getNucleotideDiploidByte(myTokens[s][ImportUtils.NUM_HAPMAP_NON_TAXA_HEADERS + i]);
} catch (IndexOutOfBoundsException ex) {
throw new IllegalStateException("Number of Taxa: " + myNumTaxa + " does not match number of values at line in file: " + (myLineInFile + s) + " site: " + mySite + s);
} catch (Exception e) {
throw new IllegalStateException("Problem with line in file: " + (myLineInFile + s), e);
}
}
}
setAlleles(data);
if (myIsSBit) {
setSBits(data);
} else {
setTBits(data);
}
clearVariables();
myInstances.offer(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setAlleles(byte[][] data) {
for (int s = 0; s < myNumSitesToProcess; s++) {
int[][] alleles = AlignmentUtils.getAllelesSortedByFrequency(data[s]);
int resultSize = alleles[0].length;
for (int i = 0; i < myNumAlleles; i++) {
if (i < resultSize) {
myAlleles[mySite + s][i] = (byte) alleles[0][i];
myAlleleMappings[s][myAlleles[mySite + s][i]] = i;
} else {
myAlleles[mySite + s][i] = Alignment.UNKNOWN_ALLELE;
}
}
}
}
private void setSBits(byte[][] data) {
int numLongs = BitUtil.bits2words(myNumTaxa);
for (int s = 0; s < myNumSitesToProcess; s++) {
long[][] bits = new long[myNumDataRows][numLongs];
byte[] cb = new byte[2];
for (int l = 0; l < numLongs - 1; l++) {
long bitmask = 0x1L;
for (int t = l * 64, n = l * 64 + 64; t < n; t++) {
cb[0] = (byte) ((data[s][t] >>> 4) & 0xf);
cb[1] = (byte) (data[s][t] & 0xf);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
int index = myAlleleMappings[s][cb[i]];
if (index == -1) {
if (myRetainRareAlleles) {
bits[myNumAlleles][l] |= bitmask;
}
} else {
bits[index][l] |= bitmask;
}
}
}
bitmask = bitmask << 1;
}
}
int lastLong = numLongs - 1;
int numRemaining = myNumTaxa % 64;
if (numRemaining == 0) {
numRemaining = 64;
}
long bitmask = 0x1L;
for (int t = lastLong * 64, n = lastLong * 64 + numRemaining; t < n; t++) {
cb[0] = (byte) ((data[s][t] >>> 4) & 0xf);
cb[1] = (byte) (data[s][t] & 0xf);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
int index = myAlleleMappings[s][cb[i]];
if (index == -1) {
if (myRetainRareAlleles) {
bits[myNumAlleles][lastLong] |= bitmask;
}
} else {
bits[index][lastLong] |= bitmask;
}
}
}
bitmask = bitmask << 1;
}
for (int i = 0; i < myNumDataRows; i++) {
myData[i][mySite + s] = new OpenBitSet(bits[i], numLongs);
}
}
}
private void setTBits(byte[][] data) {
if (mySite % 64 != 0) {
throw new IllegalStateException("ProcessLineOfHapmap: setTBits: starting site must begin a word: " + mySite);
}
int wordNum = mySite / 64;
long[] bits = new long[myNumDataRows];
for (int t = 0; t < myNumTaxa; t++) {
for (int j = 0; j < myNumDataRows; j++) {
bits[j] = 0;
}
byte[] cb = new byte[2];
long bitmask = 0x1L;
for (int s = 0; s < myNumSitesToProcess; s++) {
cb[0] = (byte) ((data[s][t] >>> 4) & 0xf);
cb[1] = (byte) (data[s][t] & 0xf);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
int index = myAlleleMappings[s][cb[i]];
if (index == -1) {
if (myRetainRareAlleles) {
bits[myNumAlleles] |= bitmask;
}
} else {
bits[index] |= bitmask;
}
}
}
bitmask = bitmask << 1;
}
for (int i = 0; i < myNumDataRows; i++) {
myData[i][t].setLong(wordNum, bits[i]);
}
}
}
} |
package org.appwork.utils.swing.table.columns;
import java.awt.Component;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTable;
import org.appwork.utils.swing.renderer.RenderLabel;
import org.appwork.utils.swing.table.ExtColumn;
import org.appwork.utils.swing.table.ExtDefaultRowSorter;
import org.appwork.utils.swing.table.ExtTableModel;
public abstract class ExtTextColumn<E> extends ExtColumn<E> {
private static final long serialVersionUID = 2114805529462086691L;
protected RenderLabel label;
public ExtTextColumn(final String name, final ExtTableModel<E> table) {
super(name, table);
this.label = new RenderLabel();
this.label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
this.label.setOpaque(false);
this.prepareTableCellRendererComponent(this.label);
this.setRowSorter(new ExtDefaultRowSorter<E>() {
@Override
public int compare(final E o1, final E o2) {
if (this.isSortOrderToggle()) {
return ExtTextColumn.this.getStringValue(o1).compareTo(ExtTextColumn.this.getStringValue(o2));
} else {
return ExtTextColumn.this.getStringValue(o2).compareTo(ExtTextColumn.this.getStringValue(o1));
}
}
});
}
@Override
public Object getCellEditorValue() {
return null;
}
/**
* @param value
* @return
*/
protected Icon getIcon(final E value) {
return null;
}
protected abstract String getStringValue(E value);
@SuppressWarnings("unchecked")
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
this.prepareLabel((E) value);
this.label.setText(this.getStringValue((E) value));
this.label.setToolTipText(this.getToolTip((E) value));
this.label.setEnabled(this.isEnabled((E) value));
this.label.setIcon(this.getIcon((E) value));
return this.label;
}
public String getToolTip(final E obj) {
final String v = this.getStringValue(obj);
if (v != null && v.length()>0) {
return "<html>" + v.replaceAll("\r\n", "<br>") + "</html>";
} else {
return null;
}
}
@Override
public boolean isEditable(final E obj) {
return false;
}
@Override
public boolean isEnabled(final E obj) {
return true;
}
@Override
public boolean isSortable(final E obj) {
return true;
}
@Override
protected boolean matchSearch(final E object, final Pattern pattern) {
return pattern.matcher(this.getStringValue(object)).matches();
}
/**
* @param value
*/
protected void prepareLabel(final E value) {
// TODO Auto-generated method stub
}
/**
* Should be overwritten to prepare the componente for the TableCellRenderer
* (e.g. setting tooltips)
*/
protected void prepareTableCellRendererComponent(final JLabel jlr) {
}
@Override
public void setValue(final Object value, final E object) {
}
} |
package com.pineone.icbms.so.util;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Settings2 {
/**
* broker(kafka) list
*/
public static String brokerList = "localhost:9092";
@Value("${mq.broker.list}")
public void setBrokerList(String _brokerList) {
brokerList = _brokerList;
}
public static String getBrokerList() {
return brokerList;
}
/**
* Zookeeper list
*/
public static String zookeeperList = "localhost:2181";
public static String getZookeeperList() {
return zookeeperList;
}
@Value("${mq.zookeeper.list}")
public void setZookeeperList(String _zookeeperList) {
zookeeperList = _zookeeperList;
}
/**
* consumer Poll timeout
*/
public static long pollTimeout = 3000L;
@Value("${mq.consumer.pool_timeout}")
public void setPollTimeout(long _pollTimeout) {
pollTimeout = _pollTimeout;
}
public static long getPollTimeout() {
return pollTimeout;
}
/**
* ENABLE_AUTO_COMMIT_CONFIG
*/
public static String enableAutoCommitConfig = "true";
@Value("${mq.consumer.enable_auto_commit}")
public void setEnableAutoCommitConfig(String _enableAutoCommitConfig) {
enableAutoCommitConfig = _enableAutoCommitConfig;
}
public static String getEnableAutoCommitConfig() {
return enableAutoCommitConfig;
}
/**
* AUTO_COMMIT_INTERVAL_MS_CONFIG
*/
public static String autoCommitIntervalMsConfig = "1000";
@Value("${mq.consumer.auto_commit_interval_ms}")
public void setAutoCommitIntervalMsConfig(String _autoCommitIntervalMsConfig) {
autoCommitIntervalMsConfig = _autoCommitIntervalMsConfig;
}
public static String getAutoCommitIntervalMsConfig() {
return autoCommitIntervalMsConfig;
}
/**
* SESSION_TIMEOUT_MS_CONFIG
*/
public static String sessionTimeoutMsConfig= "15000";
@Value("${mq.consumer.session_timeout_ms}")
public void setSessionTimeoutMsConfig(String _sessionTimeoutMsConfig) {
sessionTimeoutMsConfig = _sessionTimeoutMsConfig;
}
public static String getSessionTimeoutMsConfig() {
return sessionTimeoutMsConfig;
}
/**
* AUTO_OFFSET_RESET_CONFIG
*/
public static String autoOffsetResetConfig= "earliest";
@Value("${mq.consumer.auto_offset_reset}")
public void setAutoOffsetResetConfig(String _autoOffsetResetConfig) {
autoOffsetResetConfig = _autoOffsetResetConfig;
}
public static String getAutoOffsetResetConfig() {
return autoOffsetResetConfig;
}
/**
* KEY_DESERIALIZER_CLASS_CONFIG
*/
public static String KEY_DESERIALIZER_CLASS_CONFIG = StringDeserializer.class.getName();
/**
* VALUE_DESERIALIZER_CLASS_CONFIG
*/
public static String VALUE_DESERIALIZER_CLASS_CONFIG = StringDeserializer.class.getName();
/**
* ACKS_CONFIG
*/
public static String acksConfig= "1";
@Value("${mq.producer.acks}")
public void setAcksConfig(String _acksConfig) {
acksConfig = _acksConfig;
}
public static String getAcksConfig() {
return acksConfig;
}
/**
* RETRIES_CONFIG
*/
public static int retriesConfig = 0;
@Value("${mq.producer.retries}")
public void setRetriesConfig(int _retriesConfig) {
retriesConfig = _retriesConfig;
}
public static int getRetriesConfig() {
return retriesConfig;
}
/**
* BATCH_SIZE_CONFIG
*/
public static int batchSizeConfig= 16384;
@Value("${mq.producer.batch_size}")
public void setBatchSizeConfig(int _batchSizeConfig) {
batchSizeConfig = _batchSizeConfig;
}
public static int getBatchSizeConfig() {
return batchSizeConfig;
}
/**
* LINGER_MS_CONFIG
*/
public static int lingerMsConfig= 1;
@Value("${mq.producer.linger_ms}")
public void setLingerMsConfig(int _lingerMsConfig) {
lingerMsConfig = _lingerMsConfig;
}
public static int getLingerMsConfig() {
return lingerMsConfig;
}
/**
* BUFFER_MEMORY_CONFIG
*/
public static int bufferMemoryConfig= 33554432;
@Value("${mq.producer.buffer_memory}")
public void setBufferMemoryConfig(int _bufferMemoryConfig) {
bufferMemoryConfig = _bufferMemoryConfig;
}
public static int getBufferMemoryConfig() {
return bufferMemoryConfig;
}
/**
* KEY_SERIALIZER_CLASS_CONFIG
*/
public static String KEY_SERIALIZER_CLASS_CONFIG = StringSerializer.class.getName();
/**
* VALUE_SERIALIZER_CLASS_CONFIG
*/
public static String VALUE_SERIALIZER_CLASS_CONFIG = StringSerializer.class.getName();
/**
* kafka topic: contextmodel<BR/>
*/
public static String TOPIC_CONTEXT_MODEL = "contextmodel";
/**
* kafka topic: orchestrationservice<BR/>
*/
public static String TOPIC_ORCHESTRATION_SERVICE = "orchestrationservice";
/**
* kafka topic: virtual object<BR/>
*/
public static String TOPIC_VIRTUAL_OBJECT = "virtualobject";
/**
* kafka topic: devicecontrol<BR/>
*/
public static String TOPIC_DEVICE_CONTROL = "devicecontrol";
/**
* kafka topic: logging
*/
public static String TOPIC_LOGGING = "logging";
/**
* each serviceprocessor handler count
*/
public static int HANDLER_COUNT = 1;
/**
* CONTEXTMODEL serviceprocessor handler count
*/
public static int HANDLER_CONTEXTMODEL_COUNT = HANDLER_COUNT;
/**
* ORCHESTRATIONSERVICE serviceprocessor handler count
*/
public static int HANDLER_ORCHESTRATIONSERVICE_COUNT = HANDLER_COUNT;
/**
* VIRTUALOBJECT serviceprocessor handler count
*/
public static int HANDELR_VIRTUALOBJECT_COUNT = HANDLER_COUNT;
/**
* DEVICECONTROL serviceprocessor handler count
*/
public static int HANDLER_DEVICECONTROL_COUNT = HANDLER_COUNT;
/**
* class path for class loader
*/
public static String deviceDriverPath= "/";
@Value("${so.device.driver.path}")
public void setDeviceDriverPath(String _deviceDriverPath) {
deviceDriverPath = _deviceDriverPath;
}
public static String getDeviceDriverPath() {
return deviceDriverPath;
}
} |
package org.apache.ibatis.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class EnumTypeHandler extends BaseTypeHandler implements TypeHandler {
private Class type;
public EnumTypeHandler(Class type) {
this.type = type;
}
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
if (jdbcType == null) {
ps.setString(i, parameter.toString());
} else {
ps.setObject(i, parameter.toString(), jdbcType.TYPE_CODE);
}
}
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
String s = rs.getString(columnName);
return s == null ? null : Enum.valueOf(type, s);
}
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String s = cs.getString(columnIndex);
return s == null ? null : Enum.valueOf(type, s);
}
} |
package org.reactfx.util;
import static org.reactfx.util.Either.*;
import static org.reactfx.util.LL.*;
import static org.reactfx.util.Tuples.*;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import org.reactfx.util.LL.Cons;
public abstract class FingerTree<T, S> {
public static abstract class NonEmptyFingerTree<T, S> extends FingerTree<T, S> {
private NonEmptyFingerTree(ToSemigroup<? super T, S> semigroup) {
super(semigroup);
}
@Override
public Either<FingerTree<T, S>, NonEmptyFingerTree<T, S>> caseEmpty() {
return right(this);
}
public abstract S getSummary();
@Override
public BiIndex locate(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position) {
if(navigate.apply(getSummary(), position).isRight()) {
throw new IndexOutOfBoundsException("Position " + position + " is out of bounds");
}
return locate0(navigate, position);
}
@Override
public BiIndex locateProgressively(
ToIntFunction<? super S> metric,
int position) {
Lists.checkPosition(position, measure(metric));
return locateProgressively0(metric, position);
}
@Override
public BiIndex locateRegressively(
ToIntFunction<? super S> metric,
int position) {
Lists.checkPosition(position, measure(metric));
return locateRegressively0(metric, position);
}
public Tuple3<FingerTree<T, S>, T, FingerTree<T, S>> splitAt(int leaf) {
Lists.checkIndex(leaf, getLeafCount());
return split0(leaf).map((l, r0) ->
r0.split0(1).map((m, r) ->
t(l, m.getLeaf0(0), r)));
}
public Tuple3<FingerTree<T, S>, Tuple2<T, Integer>, FingerTree<T, S>> split(
ToIntFunction<? super S> metric, int position) {
Lists.checkPosition(position, measure(metric));
return split((s, i) -> {
int n = metric.applyAsInt(s);
return i <= n ? left(i) : right(i - n);
}, position);
}
public Tuple3<FingerTree<T, S>, Tuple2<T, Integer>, FingerTree<T, S>> split(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position) {
if(navigate.apply(getSummary(), position).isRight()) {
throw new IndexOutOfBoundsException("Position " + position + " is out of bounds");
}
BiIndex loc = locate0(navigate, position);
return splitAt(loc.major).map((l, m, r) -> t(l, t(m, loc.minor), r));
}
@Override
public NonEmptyFingerTree<T, S> join(FingerTree<T, S> rightTree) {
return appendTree(rightTree);
}
final NonEmptyFingerTree<T, S> appendTree(FingerTree<T, S> right) {
if(this.getDepth() >= right.getDepth()) {
return appendLte(right).unify(
Function.identity(),
two -> two.map(this::branch));
} else {
return ((NonEmptyFingerTree<T, S>) right).prependTree(this);
}
}
final NonEmptyFingerTree<T, S> prependTree(FingerTree<T, S> left) {
if(this.getDepth() >= left.getDepth()) {
return prependLte(left).unify(
Function.identity(),
two -> two.map(this::branch));
} else {
return ((NonEmptyFingerTree<T, S>) left).appendTree(this);
}
}
abstract List<T> subList(int from, int to);
abstract BiIndex locate0(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position);
abstract BiIndex locateProgressively0(
ToIntFunction<? super S> metric,
int position);
abstract BiIndex locateRegressively0(
ToIntFunction<? super S> metric,
int position);
abstract Either<? extends NonEmptyFingerTree<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> appendLte(FingerTree<T, S> right);
abstract Either<? extends NonEmptyFingerTree<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> prependLte(FingerTree<T, S> left);
}
private static final class Empty<T, S> extends FingerTree<T, S> {
Empty(ToSemigroup<? super T, S> semigroup) {
super(semigroup);
}
@Override
public String toString() {
return"<emtpy tree>";
}
@Override
public Either<FingerTree<T, S>, NonEmptyFingerTree<T, S>> caseEmpty() {
return left(this);
}
@Override
public
int getDepth() {
return 0;
}
@Override
public
int getLeafCount() {
return 0;
}
@Override
public FingerTree<T, S> join(FingerTree<T, S> rightTree) {
return rightTree;
}
@Override
public List<T> asList() {
return Collections.emptyList();
}
@Override
T getLeaf0(int index) {
throw new IndexOutOfBoundsException();
}
@Override
NonEmptyFingerTree<T, S> updateLeaf0(int index, T data) {
throw new IndexOutOfBoundsException();
}
@Override
T getData() {
throw new NoSuchElementException();
}
@Override
public
Optional<S> getSummaryOpt() {
return Optional.empty();
}
@Override
public <R> R fold(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction) {
return acc;
}
@Override
<R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf, int endLeaf) {
assert Lists.isValidRange(startLeaf, endLeaf, 0);
return acc;
}
@Override
<R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction) {
assert Lists.isValidRange(startPosition, endPosition, 0);
return acc;
}
@Override
S getSummaryBetween0(int startLeaf, int endLeaf) {
throw new AssertionError("Unreachable code");
}
@Override
S getSummaryBetween0(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary) {
throw new AssertionError("Unreachable code");
}
@Override
Tuple2<FingerTree<T, S>, FingerTree<T, S>> split0(
int beforeLeaf) {
assert beforeLeaf == 0;
return t(this, this);
}
}
private static class Leaf<T, S> extends NonEmptyFingerTree<T, S> {
private final T data;
private final S summary;
Leaf(ToSemigroup<? super T, S> semigroup, T data) {
super(semigroup);
this.data = data;
this.summary = semigroup.apply(data);
}
@Override
public String toString() {
return "Leaf(" + data + ")";
}
@Override
public int getDepth() {
return 1;
}
@Override
public int getLeafCount() {
return 1;
}
@Override
public List<T> asList() {
return Collections.singletonList(data);
}
@Override
List<T> subList(int from, int to) {
return from == to
? Collections.emptyList()
: Collections.singletonList(data);
}
@Override
T getLeaf0(int index) {
assert index == 0;
return data;
}
@Override
NonEmptyFingerTree<T, S> updateLeaf0(int index, T data) {
assert index == 0;
return leaf(data);
}
@Override
T getData() {
return data;
}
@Override
public S getSummary() {
return summary;
}
@Override
public Optional<S> getSummaryOpt() {
return Optional.of(summary);
}
@Override
BiIndex locateProgressively0(ToIntFunction<? super S> metric, int position) {
assert Lists.isValidPosition(position, measure(metric));
return new BiIndex(0, position);
}
@Override
BiIndex locateRegressively0(ToIntFunction<? super S> metric, int position) {
assert Lists.isValidPosition(position, measure(metric));
return new BiIndex(0, position);
}
@Override
public <R> R fold(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction) {
return reduction.apply(acc, data);
}
@Override
<R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf, int endLeaf) {
assert 0 <= startLeaf;
assert endLeaf <= 1;
if(startLeaf < endLeaf) {
return reduction.apply(acc, data);
} else {
return acc;
}
}
@Override
<R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction) {
assert Lists.isValidRange(startPosition, endPosition, measure(metric));
return rangeReduction.apply(acc, data, startPosition, endPosition);
}
@Override
S getSummaryBetween0(int startLeaf, int endLeaf) {
assert startLeaf == 0 && endLeaf == 1;
return summary;
}
@Override
S getSummaryBetween0(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary) {
assert Lists.isNonEmptyRange(startPosition, endPosition, measure(metric))
: "Didn't expect empty range [" + startPosition + ", " + endPosition + ")";
if(startPosition == 0 && endPosition == measure(metric)) {
return summary;
} else {
return subSummary.apply(data, startPosition, endPosition);
}
}
@Override
Either<Leaf<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> appendLte(
FingerTree<T, S> right) {
assert right.getDepth() <= this.getDepth();
return right.caseEmpty()
.mapLeft(emptyRight -> this)
.mapRight(nonEmptyRight -> t(this, nonEmptyRight));
}
@Override
Either<Leaf<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> prependLte(
FingerTree<T, S> left) {
assert left.getDepth() <= this.getDepth();
return left.caseEmpty()
.mapLeft(emptyLeft -> this)
.mapRight(nonEmptyLeft -> t(nonEmptyLeft, this));
}
@Override
Tuple2<FingerTree<T, S>, FingerTree<T, S>> split0(int beforeLeaf) {
assert Lists.isValidPosition(beforeLeaf, 1);
if(beforeLeaf == 0) {
return t(empty(), this);
} else {
return t(this, empty());
}
}
@Override
BiIndex locate0(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position) {
return navigate.apply(summary, position).unify(
inl -> new BiIndex(0, inl),
inr -> { throw new AssertionError("Unreachable code"); });
}
}
private static final class Branch<T, S> extends NonEmptyFingerTree<T, S> {
private final Cons<NonEmptyFingerTree<T, S>> children;
private final int depth;
private final int leafCount;
private final S summary;
private Branch(
ToSemigroup<? super T, S> semigroup,
Cons<NonEmptyFingerTree<T, S>> children) {
super(semigroup);
assert children.size() == 2 || children.size() == 3;
FingerTree<T, S> head = children.head();
int headDepth = head.getDepth();
assert children.all(n -> n.getDepth() == headDepth);
this.children = children;
this.depth = 1 + headDepth;
this.leafCount = children.fold(0, (s, n) -> s + n.getLeafCount());
this.summary = children.mapReduce1(
NonEmptyFingerTree<T, S>::getSummary,
semigroup::reduce);
}
@Override
public String toString() {
return "Branch" + children;
}
@Override
public int getDepth() {
return depth;
}
@Override
public int getLeafCount() {
return leafCount;
}
@Override
public List<T> asList() {
return subList0(0, leafCount);
}
@Override
List<T> subList(int from, int to) {
NonEmptyFingerTree<T, S> ch1 = children.head();
int n1 = ch1.getLeafCount();
if(to <= n1) {
return ch1.subList(from, to);
} else if(from >= n1) {
LL<? extends NonEmptyFingerTree<T, S>> tail = children.tail();
NonEmptyFingerTree<T, S> ch2 = tail.head();
int n2 = ch2.getLeafCount();
if(to <= n1 + n2) {
return ch2.subList(from - n1, to - n1);
} else if(from >= n1 + n2) {
return tail.tail().head().subList(from - n1 - n2, to - n1 - n2);
}
}
return subList0(from, to);
}
private List<T> subList0(int from, int to) {
return new AbstractList<T>() {
@Override
public T get(int index) {
Lists.checkIndex(index, to - from);
return getLeaf(from + index);
}
@Override
public int size() {
return to - from;
}
@Override
public List<T> subList(int start, int end) {
Lists.checkRange(start, end, to - from);
return Branch.this.subList(from + start, from + end);
}
};
}
@Override
final T getData() {
throw new UnsupportedOperationException("Only leaf nodes hold data");
}
@Override
final T getLeaf0(int index) {
assert Lists.isValidIndex(index, getLeafCount());
return getLeaf0(index, children);
}
private T getLeaf0(int index, LL<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
int headSize = head.getLeafCount();
if(index < headSize) {
return head.getLeaf0(index);
} else {
return getLeaf0(index - headSize, nodes.tail());
}
}
@Override
NonEmptyFingerTree<T, S> updateLeaf0(int index, T data) {
assert Lists.isValidIndex(index, getLeafCount());
return branch(updateLeaf0(index, data, children));
}
private Cons<NonEmptyFingerTree<T, S>> updateLeaf0(
int index, T data, LL<? extends NonEmptyFingerTree<T, S>> nodes) {
NonEmptyFingerTree<T, S> head = nodes.head();
int headSize = head.getLeafCount();
if(index < headSize) {
return cons(head.updateLeaf0(index, data), nodes.tail());
} else {
return cons(head, updateLeaf0(index - headSize, data, nodes.tail()));
}
}
@Override
final BiIndex locateProgressively0(ToIntFunction<? super S> metric, int position) {
assert Lists.isValidPosition(position, measure(metric));
return locateProgressively0(metric, position, children);
}
private BiIndex locateProgressively0(
ToIntFunction<? super S> metric,
int position,
LL<? extends NonEmptyFingerTree<T, S>> nodes) {
NonEmptyFingerTree<T, S> head = nodes.head();
int headLen = head.measure(metric);
if(position < headLen ||
(position == headLen && nodes.tail().isEmpty())) {
return head.locateProgressively0(metric, position);
} else {
return locateProgressively0(metric, position - headLen, nodes.tail())
.adjustMajor(head.getLeafCount());
}
}
@Override
final BiIndex locateRegressively0(ToIntFunction<? super S> metric, int position) {
assert Lists.isValidPosition(position, measure(metric));
return locateRegressively0(metric, position, children);
}
private BiIndex locateRegressively0(
ToIntFunction<? super S> metric,
int position,
LL<? extends NonEmptyFingerTree<T, S>> nodes) {
NonEmptyFingerTree<T, S> head = nodes.head();
int headLen = head.measure(metric);
if(position <= headLen) {
return head.locateRegressively0(metric, position);
} else {
return locateRegressively0(metric, position - headLen, nodes.tail())
.adjustMajor(head.getLeafCount());
}
}
@Override
public final <R> R fold(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction) {
return children.fold(acc, (r, n) -> n.fold(r, reduction));
}
@Override
final <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf,
int endLeaf) {
assert Lists.isNonEmptyRange(startLeaf, endLeaf, getLeafCount());
return foldBetween0(acc, reduction, startLeaf, endLeaf, children);
}
private <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf,
int endLeaf,
LL<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
int headSize = head.getLeafCount();
int headTo = Math.min(endLeaf, headSize);
int tailFrom = Math.max(startLeaf - headSize, 0);
int tailTo = endLeaf - headSize;
if(startLeaf < headTo) {
acc = head.foldBetween0(acc, reduction, startLeaf, headTo);
}
if(tailFrom < tailTo) {
acc = foldBetween0(acc, reduction, tailFrom, tailTo, nodes.tail());
}
return acc;
}
@Override
final <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction) {
assert Lists.isNonEmptyRange(startPosition, endPosition, measure(metric));
return foldBetween0(acc, reduction, metric, startPosition, endPosition, rangeReduction, children);
}
private <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction,
LL<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
int headLen = head.measure(metric);
int headTo = Math.min(endPosition, headLen);
int tailFrom = Math.max(startPosition - headLen, 0);
int tailTo = endPosition - headLen;
if(startPosition < headTo) {
acc = head.foldBetween0(acc, reduction, metric, startPosition, headTo, rangeReduction);
}
if(tailFrom < tailTo) {
acc = foldBetween0(acc, reduction, metric, tailFrom, tailTo, rangeReduction, nodes.tail());
}
return acc;
}
@Override
public S getSummary() {
return summary;
}
@Override
public Optional<S> getSummaryOpt() {
return Optional.of(summary);
}
@Override
final S getSummaryBetween0(int startLeaf, int endLeaf) {
assert Lists.isNonEmptyRange(startLeaf, endLeaf, getLeafCount());
if(startLeaf == 0 && endLeaf == getLeafCount()) {
return summary;
} else {
return getSummaryBetween0(startLeaf, endLeaf, children);
}
}
private S getSummaryBetween0(
int startLeaf,
int endLeaf,
LL<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
int headSize = head.getLeafCount();
int headTo = Math.min(endLeaf, headSize);
int tailFrom = Math.max(startLeaf - headSize, 0);
int tailTo = endLeaf - headSize;
if(startLeaf < headTo && tailFrom < tailTo) {
return semigroup.reduce(
head.getSummaryBetween0(startLeaf, headTo),
getSummaryBetween0(tailFrom, tailTo, nodes.tail()));
} else if(startLeaf < headTo) {
return head.getSummaryBetween0(startLeaf, headTo);
} else if(tailFrom < tailTo) {
return getSummaryBetween0(tailFrom, tailTo, nodes.tail());
} else {
throw new AssertionError("Didn't expect empty range: "
+ "[" + startLeaf + ", " + endLeaf + ")");
}
}
@Override
final S getSummaryBetween0(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary) {
int len = measure(metric);
assert Lists.isNonEmptyRange(startPosition, endPosition, len);
if(startPosition == 0 && endPosition == len) {
return getSummary();
} else {
return getSummaryBetween0(metric, startPosition, endPosition, subSummary, children);
}
}
private S getSummaryBetween0(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary,
LL<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
int headLen = head.measure(metric);
int headTo = Math.min(endPosition, headLen);
int tailFrom = Math.max(startPosition - headLen, 0);
int tailTo = endPosition - headLen;
if(startPosition < headTo && tailFrom < tailTo) {
return semigroup.reduce(
head.getSummaryBetween0( metric, startPosition, headTo, subSummary),
getSummaryBetween0(metric, tailFrom, tailTo, subSummary, nodes.tail()));
} else if(startPosition < headTo) {
return head.getSummaryBetween0(metric, startPosition, headTo, subSummary);
} else if(tailFrom < tailTo) {
return getSummaryBetween0(metric, tailFrom, tailTo, subSummary, nodes.tail());
} else {
throw new AssertionError("Didn't expect empty range: [" + startPosition + ", " + endPosition + ")");
}
}
@Override
Either<Branch<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> appendLte(
FingerTree<T, S> suffix) {
assert suffix.getDepth() <= this.getDepth();
if(suffix.getDepth() == this.getDepth()) {
return right(t(this, (NonEmptyFingerTree<T, S>) suffix));
} else if(children.size() == 2) {
return children.mapFirst2((left, right) -> {
return right.appendLte(suffix).unify(
r -> left(branch(left, r)),
mr -> left(mr.map((m, r) -> branch(left, m, r))));
});
} else {
assert children.size() == 3;
return children.mapFirst3((left, middle, right) -> {
return right.appendLte(suffix)
.mapLeft(r -> branch(left, middle, r))
.mapRight(mr -> t(branch(left, middle), mr.map(this::branch)));
});
}
}
@Override
Either<Branch<T, S>, Tuple2<NonEmptyFingerTree<T, S>, NonEmptyFingerTree<T, S>>> prependLte(
FingerTree<T, S> prefix) {
assert prefix.getDepth() <= this.getDepth();
if(prefix.getDepth() == this.getDepth()) {
return right(t((NonEmptyFingerTree<T, S>) prefix, this));
} else if(children.size() == 2) {
return children.mapFirst2((left, right) -> {
return left.prependLte(prefix).unify(
l -> left(branch(l, right)),
lm -> left(lm.map((l, m) -> branch(l, m, right))));
});
} else {
assert children.size() == 3;
return children.mapFirst3((left, middle, right) -> {
return left.prependLte(prefix)
.mapLeft(l -> branch(l, middle, right))
.mapRight(lm -> t(lm.map(this::branch), branch(middle, right)));
});
}
}
@Override
Tuple2<FingerTree<T, S>, FingerTree<T, S>> split0(int beforeLeaf) {
assert Lists.isValidPosition(beforeLeaf, getLeafCount());
if(beforeLeaf == 0) {
return t(empty(), this);
} else {
return split0(beforeLeaf, children);
}
}
private Tuple2<FingerTree<T, S>, FingerTree<T, S>> split0(
int beforeLeaf, LL<? extends FingerTree<T, S>> nodes) {
assert beforeLeaf > 0;
FingerTree<T, S> head = nodes.head();
int headSize = head.getLeafCount();
if(beforeLeaf <= headSize) {
return head.split0(beforeLeaf)
.map((l, r) -> t(l, concat(cons(r, nodes.tail()))));
} else {
return split0(beforeLeaf - headSize, nodes.tail())
.map((l, r) -> t(head.join(l), r));
}
}
@Override
BiIndex locate0(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position) {
assert navigate.apply(summary, position).isLeft();
return locate0(navigate, position, children);
}
private BiIndex locate0(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position,
LL<? extends NonEmptyFingerTree<T, S>> nodes) {
NonEmptyFingerTree<T, S> head = nodes.head();
return navigate.apply(head.getSummary(), position).unify(
posInl -> head.locate0(navigate, posInl),
posInr -> locate0(navigate, posInr, nodes.tail())
.adjustMajor(head.getLeafCount()));
}
}
public static <T, S> FingerTree<T, S> empty(
ToSemigroup<? super T, S> statisticsProvider) {
return new Empty<>(statisticsProvider);
}
public static <T, S> FingerTree<T, S> mkTree(
List<? extends T> initialItems,
ToSemigroup<? super T, S> statisticsProvider) {
if(initialItems.isEmpty()) {
return new Empty<>(statisticsProvider);
}
List<NonEmptyFingerTree<T, S>> leafs = new ArrayList<>(initialItems.size());
for(T item: initialItems) {
leafs.add(new Leaf<T, S>(statisticsProvider, item));
}
return mkTree(leafs);
}
private static <T, S> FingerTree<T, S> mkTree(List<NonEmptyFingerTree<T, S>> trees) {
while(trees.size() > 1) {
for(int i = 0; i < trees.size(); ++i) {
if(trees.size() - i >= 5 || trees.size() - i == 3) {
NonEmptyFingerTree<T, S> t1 = trees.get(i);
NonEmptyFingerTree<T, S> t2 = trees.get(i + 1);
NonEmptyFingerTree<T, S> t3 = trees.get(i + 2);
Branch<T, S> branch = t1.branch(t1, t2, t3);
trees.set(i, branch);
trees.subList(i + 1, i + 3).clear();
} else { // (trees.size() - i) is 4 or 2
NonEmptyFingerTree<T, S> t1 = trees.get(i);
NonEmptyFingerTree<T, S> t2 = trees.get(i + 1);
Branch<T, S> b = t1.branch(t1, t2);
trees.set(i, b);
trees.remove(i + 1);
}
}
}
return trees.get(0);
}
private static <T, S> FingerTree<T, S> concat(
Cons<? extends FingerTree<T, S>> nodes) {
FingerTree<T, S> head = nodes.head();
return nodes.tail().fold(
head,
FingerTree::join);
}
final ToSemigroup<? super T, S> semigroup;
private FingerTree(ToSemigroup<? super T, S> semigroup) {
this.semigroup = semigroup;
}
public abstract int getDepth();
public abstract int getLeafCount();
public abstract Optional<S> getSummaryOpt();
public abstract Either<FingerTree<T, S>, NonEmptyFingerTree<T, S>> caseEmpty();
public final boolean isEmpty() {
return getDepth() == 0;
}
public S getSummary(S whenEmpty) {
return getSummaryOpt().orElse(whenEmpty);
}
public T getLeaf(int index) {
Lists.checkIndex(index, getLeafCount());
return getLeaf0(index);
}
abstract T getLeaf0(int index);
public Tuple2<T, BiIndex> get(
ToIntFunction<? super S> metric,
int index) {
return caseEmpty().unify(
emptyTree -> { throw new IndexOutOfBoundsException("empty tree"); },
neTree -> {
int size = metric.applyAsInt(neTree.getSummary());
Lists.checkIndex(index, size);
BiIndex location = locateProgressively(metric, index);
return t(getLeaf(location.major), location);
});
}
public <E> E get(
ToIntFunction<? super S> metric,
int index,
BiFunction<? super T, Integer, ? extends E> leafAccessor) {
return locateProgressively(metric, index)
.map((major, minor) -> leafAccessor.apply(getLeaf(major), minor));
}
public NonEmptyFingerTree<T, S> updateLeaf(int index, T data) {
Lists.checkIndex(index, getLeafCount());
return updateLeaf0(index, data);
}
abstract NonEmptyFingerTree<T, S> updateLeaf0(int index, T data);
public BiIndex locate(
BiFunction<? super S, Integer, Either<Integer, Integer>> navigate,
int position) {
return caseEmpty().unify(
emptyTree -> { throw new IndexOutOfBoundsException("no leafs to locate in"); },
neTree -> { throw new AssertionError("This method must be overridden in non-empty tree"); });
}
public BiIndex locateProgressively(
ToIntFunction<? super S> metric,
int position) {
return caseEmpty().unify(
emptyTree -> { throw new IndexOutOfBoundsException("no leafs to locate in"); },
neTree -> { throw new AssertionError("This method must be overridden in non-empty tree"); });
}
public BiIndex locateRegressively(
ToIntFunction<? super S> metric,
int position) {
return caseEmpty().unify(
emptyTree -> { throw new IndexOutOfBoundsException("no leafs to locate in"); },
neTree -> { throw new AssertionError("This method must be overridden in non-empty tree"); });
}
public abstract <R> R fold(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction);
public <R> R foldBetween(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf,
int endLeaf) {
Lists.checkRange(startLeaf, endLeaf, getLeafCount());
if(startLeaf == endLeaf) {
return acc;
} else {
return foldBetween0(acc, reduction, startLeaf, endLeaf);
}
}
abstract <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
int startLeaf, int endLeaf);
public <R> R foldBetween(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction) {
Lists.checkRange(startPosition, endPosition, measure(metric));
if(startPosition == endPosition) {
return acc;
} else {
return foldBetween0(
acc, reduction, metric, startPosition, endPosition, rangeReduction);
}
}
abstract <R> R foldBetween0(
R acc,
BiFunction<? super R, ? super T, ? extends R> reduction,
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TetraFunction<? super R, ? super T, Integer, Integer, ? extends R> rangeReduction);
public Optional<S> getSummaryBetween(int startLeaf, int endLeaf) {
Lists.checkRange(startLeaf, endLeaf, getLeafCount());
return startLeaf == endLeaf
? Optional.empty()
: Optional.of(getSummaryBetween0(startLeaf, endLeaf));
}
abstract S getSummaryBetween0(
int startLeaf,
int endLeaf);
public Optional<S> getSummaryBetween(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary) {
Lists.checkRange(startPosition, endPosition, measure(metric));
return startPosition == endPosition
? Optional.empty()
: Optional.of(getSummaryBetween0(metric, startPosition, endPosition, subSummary));
}
abstract S getSummaryBetween0(
ToIntFunction<? super S> metric,
int startPosition,
int endPosition,
TriFunction<? super T, Integer, Integer, ? extends S> subSummary);
public Tuple2<FingerTree<T, S>, FingerTree<T, S>> split(int beforeLeaf) {
Lists.checkPosition(beforeLeaf, getLeafCount());
return split0(beforeLeaf);
}
abstract Tuple2<FingerTree<T, S>, FingerTree<T, S>> split0(int beforeLeaf);
public FingerTree<T, S> removeLeafs(int fromLeaf, int toLeaf) {
Lists.checkRange(fromLeaf, toLeaf, getLeafCount());
if(fromLeaf == toLeaf) {
return this;
} else if(fromLeaf == 0 && toLeaf == getLeafCount()) {
return empty();
} else {
FingerTree<T, S> left = split0(fromLeaf)._1;
FingerTree<T, S> right = split0(toLeaf)._2;
return left.join(right);
}
}
public FingerTree<T, S> insertLeaf(int position, T data) {
Lists.checkPosition(position, getLeafCount());
return split0(position)
.map((l, r) -> l.join(leaf(data)).join(r));
}
public abstract FingerTree<T, S> join(FingerTree<T, S> rightTree);
public NonEmptyFingerTree<T, S> append(T data) {
return leaf(data).prependTree(this);
}
public NonEmptyFingerTree<T, S> prepend(T data) {
return leaf(data).appendTree(this);
}
public abstract List<T> asList();
abstract T getData(); // valid for leafs only
Empty<T, S> empty() {
return new Empty<>(semigroup);
}
Leaf<T, S> leaf(T data) {
return new Leaf<>(semigroup, data);
}
Branch<T, S> branch(NonEmptyFingerTree<T, S> left, NonEmptyFingerTree<T, S> right) {
return branch(LL.of(left, right));
}
Branch<T, S> branch(
NonEmptyFingerTree<T, S> left,
NonEmptyFingerTree<T, S> middle,
NonEmptyFingerTree<T, S> right) {
return branch(LL.of(left, middle, right));
}
Branch<T, S> branch(Cons<NonEmptyFingerTree<T, S>> children) {
return new Branch<>(semigroup, children);
}
final int measure(ToIntFunction<? super S> metric) {
return getSummaryOpt().map(metric::applyAsInt).orElse(0);
}
} |
package org.ensembl.healthcheck.testcase.compara;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.Vector;
import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase;
/**
* Check compara taxon table against core meta ones.
*/
public class CheckTaxon extends MultiDatabaseTestCase {
/**
* Create a new instance of MetaCrossSpecies
*/
public CheckTaxon() {
addToGroup("compara_external_foreign_keys");
setDescription("Check that the attributes of the taxon table (genus, species," +
" common_name and classification) correspond to the meta data in the core DB and vice versa.");
setTeamResponsible("Compara");
}
/**
* Check that the attributes of the taxon table (genus, species, common_name and
* classification) correspond to the meta data in the core DB and vice versa.
* NB: A warning message is displayed if some dnafrags cannot be checked because
* there is not any connection to the corresponding core database.
*
* @param dbr
* The database registry containing all the specified databases.
* @return true if the all the taxa in compara.taxon table which have a counterpart in
* the compara.genome_db table match the corresponding core databases.
*/
public boolean run(DatabaseRegistry dbr) {
boolean result = true;
// Get compara DB connection
DatabaseRegistryEntry[] allComparaDBs = dbr.getAll(DatabaseType.COMPARA);
if (allComparaDBs.length == 0) {
result = false;
ReportManager.problem(this, "", "Cannot find compara database");
usage();
return false;
}
Map speciesDbrs = getSpeciesDatabaseMap(dbr, true);
for (int i = 0; i < allComparaDBs.length; i++) {
result &= checkTaxon(allComparaDBs[i], speciesDbrs);
}
return result;
}
/**
* Check that the attributes of the taxon table (genus, species, common_name and
* classification) correspond to the meta data in the core DB and vice versa.
* NB: A warning message is displayed if some dnafrags cannot be checked because
* there is not any connection to the corresponding core database.
*
* @param comparaDbre
* The database registry entry for Compara DB
* @param Map
* HashMap of DatabaseRegistryEntry[], one key/value pair for each Species.
* @return true if the all the taxa in compara.taxon table which have a counterpart in
* the compara.genome_db table match the corresponding core databases.
*/
public boolean checkTaxon(DatabaseRegistryEntry comparaDbre, Map speciesDbrs) {
boolean result = true;
Connection comparaCon = comparaDbre.getConnection();
// Get list of species in compara
Vector comparaSpecies = new Vector();
String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1"
+ " AND name <> 'Ancestral sequences'";
try {
Statement stmt = comparaCon.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
comparaSpecies.add(Species.resolveAlias(rs.getString(1).toLowerCase().replace(' ', '_')));
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
//Check that don't have duplicate entries in the ncbi_taxa_name table
String useful_sql = "SELECT taxon_id,name,name_class,count(*) FROM ncbi_taxa_name GROUP BY taxon_id,name,name_class HAVING count(*) > 1;";
String[] failures = getColumnValues(comparaCon, useful_sql);
if (failures.length > 0) {
ReportManager.problem(this, comparaCon, "FAILED ncbi_taxa_name contains duplicate entries ");
ReportManager.problem(this, comparaCon, "FAILURE DETAILS: There are " + failures.length + " ncbi_taxa_names with more than 1 entry");
ReportManager.problem(this, comparaCon, "USEFUL SQL: " + useful_sql);
result = false;
} else {
result = true;
}
boolean allSpeciesFound = true;
for (int i = 0; i < comparaSpecies.size(); i++) {
Species species = (Species) comparaSpecies.get(i);
DatabaseRegistryEntry[] speciesDbr = (DatabaseRegistryEntry[]) speciesDbrs.get(species);
if (speciesDbr != null) {
Connection speciesCon = speciesDbr[0].getConnection();
String sql1, sql2;
/* Get taxon_id */
String taxon_id = getRowColumnValue(speciesCon,
"SELECT meta_value FROM meta WHERE meta_key = \"species.taxonomy_id\"");
/* Check name */
sql1 = "SELECT \"name\", name " +
" FROM ncbi_taxa_name WHERE name_class = \"scientific name\" AND taxon_id = " + taxon_id;
sql2 = "SELECT \"name\", GROUP_CONCAT(meta_value ORDER BY meta_id DESC SEPARATOR \" \") " +
" FROM (SELECT meta_id, meta_key, meta_value FROM meta " +
" WHERE meta_key = \"species.classification\" ORDER BY meta_id LIMIT 2) AS name " +
" GROUP BY meta_key";
result &= compareQueries(comparaCon, sql1, speciesCon, sql2);
/* Check common_name */
sql1 = "SELECT \"common_name\", name " +
" FROM ncbi_taxa_name WHERE name_class = \"genbank common name\" AND taxon_id = " + taxon_id;
sql2 = "SELECT \"common_name\", meta_value FROM meta" +
" WHERE meta_key = \"species.common_name\" and meta_value != \"\"";
result &= compareQueries(comparaCon, sql1, speciesCon, sql2);
/* Check classification */
/* This check is quite complex as the axonomy is stored in very different ways in compara
and core DBs. In compara, the tree structure is stored in the ncbi_taxa_node table
while the names are in the ncbi_taxa_name table. In the core DB, the taxonomy is
stored in the meta table as values of the key "species.classification" and they
should be sorted by meta_id. In the core DB, only the abbreviated lineage is
described which means that we have to ignore ncbi_taxa_node with the
genbank_hidden_flag set. On top of that, we want to compare the classification
in one single SQL. Therefore, we are getting the results recursivelly and
then execute a dumb SQL query with result itself */
String comparaClassification = new String("");
String values1[] = getRowValues(comparaCon,
"SELECT rank, parent_id, genbank_hidden_flag FROM ncbi_taxa_node WHERE taxon_id = " + taxon_id);
if (values1.length == 0) {
/* if no rows are fetched, this taxon is missing from compara DB */
ReportManager.problem(this, comparaCon, "No taxon for " + species.toString());
} else {
String this_taxon_id = values1[1];
while (!this_taxon_id.equals("0")) {
values1 = getRowValues(comparaCon,
"SELECT rank, parent_id, genbank_hidden_flag FROM ncbi_taxa_node WHERE taxon_id = " + this_taxon_id);
if ( //values1[2].equals("0") &&
!values1[1].equals("1") && !values1[1].equals("0") && !values1[0].equals("subgenus") && !values1[0].equals("subspecies")) {
String taxonName = getRowColumnValue(comparaCon,
"SELECT name FROM ncbi_taxa_name " +
"WHERE name_class = \"scientific name\" AND taxon_id = " + this_taxon_id);
if (!taxonName.equals("Fungi/Metazoa group")) {
comparaClassification += " " + taxonName;
}
}
this_taxon_id = values1[1];
}
sql1 = "SELECT \"classification\", \"" + comparaClassification + "\"";
/* It will be much better to run this using GROUP_CONCAT() but our MySQL server does not support it yet */
sql2 = "SELECT \"classification\", \"";
String[] values2 = getColumnValues(speciesCon,
"SELECT meta_value FROM meta WHERE meta_key = \"species.classification\"" +
" ORDER BY meta_id");
/* Skip first value as it is part of the species name and not the lineage */
for (int a = 1; a < values2.length; a++) {
sql2 += " " + values2[a];
}
sql2 += "\"";
result &= compareQueries(comparaCon, sql1, speciesCon, sql2);
}
} else {
ReportManager.problem(this, comparaCon, "No connection for " + species.toString());
allSpeciesFound = false;
}
}
if (!allSpeciesFound) {
usage();
}
return result;
}
/**
* Prints the usage through the ReportManager
*
* @param
* The database registry containing all the specified databases.
* @return true if the all the dnafrags are top_level seq_regions in their corresponding
* core database.
*/
private void usage() {
ReportManager.problem(this, "USAGE", "run-healthcheck.sh -d ensembl_compara_.+ " +
" -d2 .+_core_.+ CheckTaxon");
}
} // CheckTopLevelDnaFrag |
package hm.binkley.labs;
import reactor.Environment;
import reactor.bus.EventBus;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import static java.lang.System.out;
import static reactor.bus.selector.Selectors.T;
public final class ReagentMain {
public static void main(final String... args)
throws InterruptedException, IOException {
try (final Environment __ = Environment.initialize()) {
// Because main() exits before bus can process, force it to wait
final CountDownLatch done = new CountDownLatch(1);
final EventBus bus = EventBus.create(Environment.get());
bus.on(T(Foo.class), ev -> {
out.println(ev);
done.countDown();
});
bus.notify(new Bar());
done.await();
}
}
public abstract static class Foo {
@Override
public String toString() {
return "I'm a Foo!";
}
}
public static final class Bar
extends Foo {
@Override
public String toString() {
return "I'm a Bar!";
}
}
} |
package api.web.gw2.mapping.v2.guild.id.members;
import api.web.gw2.mapping.core.DateValue;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.OptionalValue;
import java.time.ZonedDateTime;
import java.util.Optional;
public final class JsonpMember implements Member {
@IdValue
private String name = ""; // NOI18N.
@IdValue
private String rank = ""; // NOI18N.
@DateValue
@OptionalValue
private Optional<ZonedDateTime> joined = Optional.empty();
/**
* Creates a new empty instance.
*/
public JsonpMember() {
}
@Override
public String getName() {
return name;
}
@Override
public String getRank() {
return rank;
}
@Override
public Optional<ZonedDateTime> getJoined() {
return joined;
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl;
import org.ensembl.healthcheck.util.MapRowMapper;
import org.ensembl.healthcheck.util.SqlTemplate;
import org.ensembl.healthcheck.util.StringListMapRowMapper;
/**
* Check that all xrefs from a certain source (e.g. HGNC, EntrezGene) are consistently assigned to the same Ensembl object type.
*/
public class XrefLevels extends MultiDatabaseTestCase {
/**
* Creates a new instance of XrefLevels
*/
public XrefLevels() {
addToGroup("release");
addToGroup("core_xrefs");
addToGroup("post-compara-handover");
setDescription("Check that all xrefs from a certain source (e.g. HGNC, EntrezGene) are consistently assigned to the same Ensembl object type across all species");
setPriority(Priority.AMBER);
setEffect("Causes BioMart to require specific workarounds for each case.");
setFix("Manually fix affected xrefs.");
setTeamResponsible(Team.CORE);
}
/**
* This only applies to core and Vega databases.
*/
public void types() {
removeAppliesToType(DatabaseType.OTHERFEATURES);
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.RNASEQ);
}
/**
* Run the test.
*
* @param dbr
* The database registry containing all the specified databases.
*/
public boolean run(DatabaseRegistry dbr) {
boolean result = true;
// easier to do this in SQL than Java
// Create an in-memory SQL database via h2 driver
try {
Class.forName("org.h2.Driver"); // memory:tablename
Connection tempDB = DriverManager.getConnection("jdbc:h2:mem:XrefLevels");
createTempTable(tempDB);
// master list of species, sources and objects
DatabaseRegistryEntry masterDBRE = null;
PreparedStatement masterPrep = null;
String masterTable = "healthcheck_xref";
DatabaseRegistryEntry[] dbres = dbr.getAll();
if (dbres.length == 0) {
return true;
}
for (DatabaseRegistryEntry dbre : dbres) {
if (masterDBRE == null) {
masterDBRE = dbre;
masterPrep = tempDB.prepareStatement("INSERT INTO " + masterTable + " (species, source, object) VALUES (?,?,?)");
}
// fill with the list of sources and object types from each species
logger.fine("Adding sources and objects for " + dbre.getName());
Statement stmt = dbre.getConnection().createStatement();
// can't do this in one query as the databases being written to and read from might be on separate servers
ResultSet rs = stmt
.executeQuery("SELECT e.db_name, ox.ensembl_object_type FROM external_db e, xref x, object_xref ox WHERE e.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id GROUP BY e.db_name, ox.ensembl_object_type");
while (rs.next()) {
String species = dbre.getSpecies().toString();
if (species == null || species.equalsIgnoreCase("unknown")) {
species = dbre.getAlias();
}
masterPrep.setString(1, species);
masterPrep.setString(2, rs.getString("db_name"));
masterPrep.setString(3, rs.getString("ensembl_object_type"));
masterPrep.execute();
}
stmt.close();
}
PreparedStatement sourcePrep = tempDB.prepareStatement("select distinct source from "+masterTable);
ResultSet sources = sourcePrep.executeQuery();
while (sources.next()) {
String source = sources.getString("source");
String query = "select object,species from "+ masterTable +" where source = ?";
MapRowMapper<String,List<String>> mapper = new StringListMapRowMapper();
SqlTemplate template = new ConnectionBasedSqlTemplateImpl(tempDB);
Map<String,List<String>> map = template.queryForMap(query, mapper, source);
if (map.size() != 1) {
// more than one list in the map implies there are at least two object types referenced
// figure out which species are different
String message = "Source:"+source+", types differ between species. ";
int smallest = 1000;
String smallestType = "";
for (Map.Entry<String, List<String>> entry: map.entrySet()) {
List<String> species = entry.getValue();
if (species.size() < smallest) {
smallest = species.size();
smallestType = entry.getKey();
}
message = message.concat(entry.getKey() + " has " + species.size() + " species. ");
}
List<String> minoritySpecies = map.get(smallestType);
message = message.concat("Problem species are:"+ StringUtils.join(minoritySpecies,","));
ReportManager.problem(this, "", message);
result = false;
}
}
dropTempTable(tempDB);
tempDB.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block for making h2 database connection.
// Somebody do this properly!
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
} // run
private void createTempTable(Connection conn) {
// making a temporary table in memory rather than affecting production DB
try {
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE healthcheck_xref (species VARCHAR(255), source VARCHAR(255), object VARCHAR(255))");
logger.fine("Created table healthcheck_xref in temporary H2 DB");
} catch (SQLException se) {
se.printStackTrace();
}
}
private void dropTempTable(Connection conn) {
try {
Statement stmt = conn.createStatement();
stmt.execute("DROP TABLE IF EXISTS healthcheck_xref");
logger.fine("Dropped table healthcheck_xref in temporary DB");
} catch (SQLException se) {
se.printStackTrace();
}
}
} // XrefLevels |
package org.craft.launch.task.tasks;
import java.io.*;
import org.apache.commons.io.*;
import org.craft.launch.*;
public class LWJGLSetup
{
private static boolean loaded;
/**
* Load LWJGL in given folder
*/
public static void load(File folder) throws Exception
{
if(!loaded)
{
if(!folder.exists())
folder.mkdirs();
if(folder.isDirectory())
{
OperatingSystem os = OperatingSystem.getOS();
if(os == OperatingSystem.WINDOWS)
{
if(!new File(folder.getPath() + "/jinput-dx8_64.dll").exists())
{
extractFromClasspath("windows/jinput-dx8_64.dll", folder);
extractFromClasspath("windows/jinput-dx8.dll", folder);
extractFromClasspath("windows/jinput-raw_64.dll", folder);
extractFromClasspath("windows/jinput-raw.dll", folder);
extractFromClasspath("windows/lwjgl.dll", folder);
extractFromClasspath("windows/lwjgl64.dll", folder);
extractFromClasspath("windows/OpenAL32.dll", folder);
extractFromClasspath("windows/OpenAL64.dll", folder);
}
else
{
System.out.println("Natives already exist.");
}
}
else if(os == OperatingSystem.SOLARIS)
{
if(!new File(folder.getPath() + "/liblwjgl.so").exists())
{
extractFromClasspath("solaris/liblwjgl.so", folder);
extractFromClasspath("solaris/liblwjgl64.so", folder);
extractFromClasspath("solaris/libopenal.so", folder);
extractFromClasspath("solaris/libopenal64.so", folder);
}
else
{
System.out.println("Natives already exist.");
}
}
else if(os == OperatingSystem.LINUX)
{
if(!new File(folder.getPath() + "/liblwjgl.so").exists())
{
extractFromClasspath("linux/liblwjgl.so", folder);
extractFromClasspath("linux/liblwjgl64.so", folder);
extractFromClasspath("linux/libopenal.so", folder);
extractFromClasspath("linux/libopenal64.so", folder);
}
else
{
System.out.println("Natives already exist.");
}
}
else if(os == OperatingSystem.MACOSX)
{
if(!new File(folder.getPath() + "/openal.dylib").exists())
{
extractFromClasspath("macosx/liblwjgl.jnilib", folder);
extractFromClasspath("macosx/liblwjgl-osx.jnilib", folder);
extractFromClasspath("macosx/openal.dylib", folder);
}
else
{
System.out.println("Natives already exist.");
}
}
else
{
System.err.println("Operating System couldn't be iditified");
}
System.setProperty("net.java.games.input.librarypath", folder.getAbsolutePath());
System.setProperty("org.lwjgl.librarypath", folder.getAbsolutePath());
}
loaded = true;
}
}
/**
* Extract given file from classpath into given folder
*/
private static void extractFromClasspath(String fileName, File folder)
{
try
{
String[] split = fileName.split("" + File.separatorChar);
FileOutputStream out = new FileOutputStream(new File(folder, split[split.length - 1]));
IOUtils.copy(LWJGLSetup.class.getResourceAsStream("/" + fileName), out);
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
} |
package org.jmist.framework.services;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executor;
import org.jmist.framework.IJob;
import org.jmist.framework.IProgressMonitor;
import org.jmist.framework.ITaskWorker;
import org.jmist.packages.DummyProgressMonitor;
/**
* A job that submits a parallelizable job to a remote
* <code>JobServiceMaster<code>. This class may potentially use multiple
* threads to process tasks.
* @author bkimmel
*/
public final class ThreadServiceWorkerJob implements IJob {
/**
* Initializes the address of the master and the amount of time to idle
* when no task is available.
* @param masterHost The URL of the master.
* @param idleTime The time (in milliseconds) to idle when no task is
* available.
* @param executor The <code>Executor</code> to use to process tasks
* (must not use an unbounded queue).
*/
public ThreadServiceWorkerJob(String masterHost, long idleTime, Executor executor) {
this.masterHost = masterHost;
this.idleTime = idleTime;
this.executor = executor;
}
/* (non-Javadoc)
* @see org.jmist.framework.IJob#go(org.jmist.framework.IProgressMonitor)
*/
@Override
public void go(IProgressMonitor monitor) {
try {
monitor.notifyIndeterminantProgress();
monitor.notifyStatusChanged("Looking up master...");
Registry registry = LocateRegistry.getRegistry(this.masterHost);
this.service = (IJobMasterService) registry.lookup("IJobMasterService");
while (monitor.notifyIndeterminantProgress()) {
this.executor.execute(new Worker(monitor.createChildProgressMonitor()));
}
monitor.notifyStatusChanged("Cancelled.");
} catch (Exception e) {
monitor.notifyStatusChanged("Exception: " + e.toString());
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
} finally {
monitor.notifyCancelled();
}
}
/**
* An entry in the <code>ITaskWorker</code> cache.
* @author bkimmel
*/
private class WorkerCacheEntry {
/**
* The <code>UUID</code> of the job that the <code>ITaskWorker</code>
* processes tasks for.
*/
public final UUID jobId;
/**
* The cached <code>ITaskWorker</code>.
*/
public final ITaskWorker worker;
/**
* Initializes the cache entry.
* @param jobId The <code>UUID</code> of the job that the
* <code>ITaskWorker</code> processes tasks for.
* @param worker The <code>ITaskWorker</code> to be cached.
*/
public WorkerCacheEntry(UUID jobId, ITaskWorker worker) {
this.jobId = jobId;
this.worker = worker;
}
}
/**
* Searches for the <code>ITaskWorker</code> to use to process tasks for
* the job with the specified <code>UUID</code> in the local cache.
* @param jobId The <code>UUID</code> of the job whose
* <code>ITaskWorker</code> to search for.
* @return The <code>ITaskWorker</code> corresponding to the job with the
* specified <code>UUID</code>, or <code>null</code> if the
* <code>ITaskWorker</code> for that job is not in the cache.
*/
private synchronized ITaskWorker getCachedTaskWorker(UUID jobId) {
assert(jobId != null);
Iterator<WorkerCacheEntry> i = this.workerCache.iterator();
/* Search for the worker for the specified job. */
while (i.hasNext()) {
WorkerCacheEntry entry = i.next();
if (entry.jobId.compareTo(jobId) == 0) {
/* Remove the entry and re-insert it at the end of the list.
* This will ensure that when an item is removed from the list,
* the item that is removed will always be the least recently
* used.
*/
i.remove();
this.workerCache.add(entry);
return entry.worker;
}
}
/* cache miss */
return null;
}
/**
* Ensures that the specified <code>ITaskWorker</code> is cached.
* @param jobId The <code>UUID</code> of the job whose tasks are to be
* processed by <code>worker</code>.
* @param worker The <code>ITaskWorker</code> to add to the cache.
*/
private synchronized void addWorkerToCache(UUID jobId, ITaskWorker worker) {
assert(jobId != null);
assert(worker != null);
/* First check to see if the worker for the specified job is already in
* the cache.
*/
if (this.getCachedTaskWorker(jobId) == null) {
/* Add the worker to the cache. */
this.workerCache.add(new WorkerCacheEntry(jobId, worker));
/* If the cache has exceeded capacity, then remove the least
* recently used entry.
*/
assert(this.maxCachedWorkers > 0);
while (this.workerCache.size() > this.maxCachedWorkers) {
this.workerCache.remove(0);
}
}
}
/**
* Obtains the task worker to process tasks for the job with the specified
* <code>UUID</code>.
* @param jobId The <code>UUID</code> of the job to obtain the task worker
* for.
* @return The <code>ITaskWorker</code> to process tasks for the job with
* the specified <code>UUID</code>, or <code>null</code> if the job
* is invalid or has already been completed.
*/
private ITaskWorker getTaskWorker(UUID jobId) {
/* First try to obtain the worker from the cache. */
ITaskWorker worker = this.getCachedTaskWorker(jobId);
if (worker != null) {
return worker;
}
/* If the task worker was not in the cache, then use the service to
* obtain the task worker.
*/
worker = this.service.getTaskWorker(jobId);
/* If we were able to get the worker from the service, add it to the
* cache so that we don't have to call the service next time.
*/
if (worker != null) {
this.addWorkerToCache(jobId, worker);
}
return worker;
}
/**
* Used to process tasks in threads.
* @author bkimmel
*/
private class Worker implements Runnable {
/**
* Initializes the progress monitor to report to.
* @param monitor The <code>IProgressMonitor</code> to report
* the progress of the task to.
*/
public Worker(IProgressMonitor monitor) {
this.monitor = monitor;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
this.monitor.notifyIndeterminantProgress();
this.monitor.notifyStatusChanged("Requesting task...");
TaskDescription taskDesc = service.requestTask();
if (taskDesc != null) {
this.monitor.notifyStatusChanged("Obtaining task worker...");
ITaskWorker worker = getTaskWorker(taskDesc.getJobId());
if (worker == null) {
this.monitor.notifyStatusChanged("Could not obtain worker...");
this.monitor.notifyCancelled();
return;
}
this.monitor.notifyStatusChanged("Performing task...");
Object results = worker.performTask(taskDesc.getTask(), monitor);
this.monitor.notifyStatusChanged("Submitting task results...");
service.submitTaskResults(taskDesc.getJobId(), taskDesc.getTaskId(), results);
} else { /* taskDesc == null */
this.monitor.notifyStatusChanged("Idling...");
try {
Thread.sleep(idleTime);
} catch (InterruptedException e) {
// continue.
}
}
this.monitor.notifyComplete();
}
/**
* The <code>IProgressMonitor</code> to report to.
*/
private final IProgressMonitor monitor;
}
/** The URL of the master. */
private final String masterHost;
/**
* The amount of time (in milliseconds) to idle when no task is available.
*/
private final long idleTime;
/** The <code>Executor</code> to use to process tasks. */
private final Executor executor;
/**
* The <code>IJobMasterService</code> to obtain tasks from and submit
* results to.
*/
private IJobMasterService service = null;
/**
* A list of recently used <code>ITaskWorker</code>s and their associated
* job's <code>UUID</code>s, in order from least recently used to most
* recently used.
*/
private final List<WorkerCacheEntry> workerCache = new LinkedList<WorkerCacheEntry>();
/**
* The maximum number of <code>ITaskWorker</code>s to retain in the cache.
*/
private final int maxCachedWorkers = 5;
} |
package org.egordorichev.lasttry.item;
import org.egordorichev.lasttry.entity.Player;
import org.egordorichev.lasttry.entity.Stat;
import java.util.List;
public class Modifier {
// Accessories
// Defense
public static final Modifier hard = new Modifier("Hard", Type.ACCESSORY, new Stat(Stat.Type.DEFENSE, +1));
public static final Modifier guarding = new Modifier("Guarding", Type.ACCESSORY, new Stat(Stat.Type.DEFENSE, +2));
public static final Modifier armored = new Modifier("Armored", Type.ACCESSORY, new Stat(Stat.Type.DEFENSE, +3));
public static final Modifier warding = new Modifier("Warding", Type.ACCESSORY, new Stat(Stat.Type.DEFENSE, +4));
// Mana
public static final Modifier arcane = new Modifier("Arcane", Type.ACCESSORY, new Stat(Stat.Type.MANA, +20));
// Critical Strike Chance
public static final Modifier precise = new Modifier("Precise", Type.ACCESSORY, new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +2));
public static final Modifier lucky = new Modifier("Lucky", Type.ACCESSORY, new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +4));
// Damage
public static final Modifier jagged = new Modifier("Jagged", Type.ACCESSORY, new Stat(Stat.Type.DAMAGE, +1));
public static final Modifier spiked = new Modifier("Spiked", Type.ACCESSORY, new Stat(Stat.Type.DAMAGE, +2));
public static final Modifier angry = new Modifier("Angry", Type.ACCESSORY, new Stat(Stat.Type.DAMAGE, +3));
public static final Modifier menacing = new Modifier("Menacing", Type.ACCESSORY, new Stat(Stat.Type.DAMAGE, +4));
// Movement Speed
public static final Modifier brisk = new Modifier("Brisk", Type.ACCESSORY, new Stat(Stat.Type.MOVEMENT_SPEED, +1));
public static final Modifier fleeting = new Modifier("Fleeting", Type.ACCESSORY, new Stat(Stat.Type.MOVEMENT_SPEED, +2));
public static final Modifier hasty = new Modifier("Hasty", Type.ACCESSORY, new Stat(Stat.Type.MOVEMENT_SPEED, +3));
public static final Modifier quick = new Modifier("Quick", Type.ACCESSORY, new Stat(Stat.Type.MOVEMENT_SPEED, +4));
// Melee Speed
public static final Modifier wild = new Modifier("Wild", Type.ACCESSORY, new Stat(Stat.Type.MELEE_SPEED, +1));
public static final Modifier rash = new Modifier("Rash", Type.ACCESSORY, new Stat(Stat.Type.MELEE_SPEED, +2));
public static final Modifier intrepid = new Modifier("Intrepid", Type.ACCESSORY, new Stat(Stat.Type.MELEE_SPEED, +3));
public static final Modifier violent = new Modifier("Violent", Type.ACCESSORY, new Stat(Stat.Type.MELEE_SPEED, +4));
// Universal
public static final Modifier keen = new Modifier("Keen", Type.UNIVERSAL, new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +3));
public static final Modifier superior = new Modifier("Superior", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, +10),
new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +3), new Stat(Stat.Type.KNOCKBACK, +10));
public static final Modifier forceful = new Modifier("Forceful", Type.UNIVERSAL, new Stat(Stat.Type.KNOCKBACK, +15));
public static final Modifier broken = new Modifier("Broken", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, -30),
new Stat(Stat.Type.KNOCKBACK, -20));
public static final Modifier damaged = new Modifier("Damaged", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, -15));
public static final Modifier shoddy = new Modifier("Shoddy", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, -10),
new Stat(Stat.Type.KNOCKBACK, -15));
public static final Modifier hurtful = new Modifier("Hurtful", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, +10));
public static final Modifier strong = new Modifier("Strong", Type.UNIVERSAL, new Stat(Stat.Type.KNOCKBACK, +15));
public static final Modifier unpleasant = new Modifier("Unpleasant", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, +5),
new Stat(Stat.Type.KNOCKBACK, +15));
public static final Modifier weak = new Modifier("Weak", Type.UNIVERSAL, new Stat(Stat.Type.KNOCKBACK, -10));
public static final Modifier ruthless = new Modifier("Ruthless", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, +18),
new Stat(Stat.Type.KNOCKBACK, -10));
public static final Modifier demonic = new Modifier("Demonic", Type.UNIVERSAL, new Stat(Stat.Type.DAMAGE, +15),
new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +5));
public static final Modifier zealous = new Modifier("Zealous", Type.UNIVERSAL, new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +5));
// Common
public static final Modifier quick = new Modifier("Quick", Type.COMMON, new Stat(Stat.Type.SPEED, +10));
public static final Modifier deady = new Modifier("Deadly", Type.COMMON, new Stat(Stat.Type.DAMAGE, +10),
new Stat(Stat.Type.SPEED, +10));
public static final Modifier aglie = new Modifier("Aglie", Type.COMMON, new Stat(Stat.Type.SPEED, +10),
new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +3));
public static final Modifier nimble = new Modifier("Nimble", Type.COMMON, new Stat(Stat.Type.SPEED, +5));
public static final Modifier murderous = new Modifier("Murderous", Type.COMMON, new Stat(Stat.Type.DAMAGE, +7),
new Stat(Stat.Type.SPEED, +6), new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +3));
public static final Modifier slow = new Modifier("Slow", Type.COMMON, new Stat(Stat.Type.SPEED, -15));
public static final Modifier sluggish = new Modifier("Sluggish", Type.COMMON, new Stat(Stat.Type.SPEED, -20));
public static final Modifier lazy = new Modifier("Lazy", Type.COMMON, new Stat(Stat.Type.SPEED, -8));
public static final Modifier annoying = new Modifier("Annoying", Type.COMMON, new Stat(Stat.Type.DAMAGE, -20),
new Stat(Stat.Type.SPEED, -15));
// Melee
public static final Modifier large = new Modifier("Large", Type.MELEE, new Stat(Stat.Type.SIZE, +12));
public static final Modifier massive = new Modifier("Massive", Type.MELEE, new Stat(Stat.Type.SIZE, +18));
public static final Modifier dangerous = new Modifier("Dangerous", Type.MELEE, new Stat(Stat.Type.DAMAGE, +5),
new Stat(Stat.Type.CRITICAL_STRIKE_CHANCE, +2), new Stat(Stat.Type.SIZE, +5));
public static final Modifier savage = new Modifier("Savage", Type.MELEE, new Stat(Stat.Type.DAMAGE, +10),
new Stat(Stat.Type.SIZE, 10), new Stat(Stat.Type.KNOCKBACK, +10));
public enum Type {
ACCESSORY,
UNIVERSAL,
COMMON,
MELEE,
RANGED,
MAGIC
}
protected String name;
protected Type type;
protected Stat[] stats;
protected float value;
public Modifier(String name, Type type, Stat... stats) {
this.name = name;
this.type = type;
this.stats = stats;
this.value = value;
}
public void apply(Player player) {
// TODO
}
public void remove(Player player) {
// TODO
}
public String getName() {
return this.name;
}
public Type getType() {
return this.type;
}
public Stat[] getStats() {
return this.stats;
}
public float getValue() {
return this.value;
}
} |
package org.jmist.packages.geometry.primitive;
import org.jmist.framework.IntersectionRecorder;
import org.jmist.framework.Material;
import org.jmist.framework.SingleMaterialGeometry;
import org.jmist.toolkit.Box3;
import org.jmist.toolkit.Point2;
import org.jmist.toolkit.Point3;
import org.jmist.toolkit.Polynomial;
import org.jmist.toolkit.Ray3;
import org.jmist.toolkit.Sphere;
import org.jmist.toolkit.Vector3;
/**
* A torus primitive <code>Geometry</code>.
* @author bkimmel
*/
public final class TorusGeometry extends SingleMaterialGeometry {
/**
* Creates a new <code>TorusGeometry</code>.
* @param major The major radius of the torus (i.e., the distance from the
* center of the torus to a point in the center of the tube.
* @param minor The minor radius of the torus (i.e., the radius of the
* tube).
* @param material The <code>Material</code> to apply to this
* <code>TorusGeometry</code>.
*/
public TorusGeometry(double major, double minor, Material material) {
super(material);
this.major = major;
this.minor = minor;
}
/* (non-Javadoc)
* @see org.jmist.framework.Geometry#intersect(org.jmist.toolkit.Ray3, org.jmist.framework.IntersectionRecorder)
*/
@Override
public void intersect(Ray3 ray, IntersectionRecorder recorder) {
Vector3 orig = ray.origin().vectorFrom(Point3.ORIGIN);
Vector3 dir = ray.direction().unit();
double sqRadius1 = major * major;
double sqRadius2 = minor * minor;
double s2NormOfDir = dir.squaredLength();
double s2NormOfOrig = orig.squaredLength();
double dirDotOrig = dir.dot(orig);
double K = s2NormOfOrig - (sqRadius1 + sqRadius2);
Polynomial f = new Polynomial(
K * K - 4.0 * sqRadius1 * (sqRadius2 - orig.y() * orig.y()),
4.0 * dirDotOrig * (s2NormOfOrig - (sqRadius1 + sqRadius2)) + 8.0 * sqRadius1 * dir.y() * orig.y(),
2.0 * s2NormOfDir * (s2NormOfOrig - (sqRadius1 + sqRadius2)) + 4.0 * ((dirDotOrig * dirDotOrig) + sqRadius1 * dir.y() * dir.y()),
4.0 * dirDotOrig * s2NormOfDir,
s2NormOfDir * s2NormOfDir
);
double[] x = f.roots();
if (x.length > 1)
{
// sort roots
for (int i = 1; i < x.length; i++)
{
if (x[i] < x[i - 1])
{
double temp = x[i];
int j;
for (j = i - 2; j >= 0; j
if (x[i] > x[j]) break;
x[i] = x[++j];
x[j] = temp;
}
}
for (int i = 0; i < x.length; i++)
super.newIntersection(ray, x[i], i % 2 == 0);
}
}
/* (non-Javadoc)
* @see org.jmist.framework.AbstractGeometry#getNormal(org.jmist.framework.AbstractGeometry.GeometryIntersection)
*/
@Override
protected Vector3 getNormal(GeometryIntersection x) {
Point3 p = x.location();
Vector3 rel = new Vector3(p.x(), 0.0, p.z());
double length = rel.length();
if (length > 0.0)
{
rel = rel.times(major / length);
return p.vectorFrom(Point3.ORIGIN.plus(rel));
}
else
return Vector3.K;
}
/* (non-Javadoc)
* @see org.jmist.framework.AbstractGeometry#getTextureCoordinates(org.jmist.framework.AbstractGeometry.GeometryIntersection)
*/
@Override
protected Point2 getTextureCoordinates(GeometryIntersection x) {
Vector3 cp = x.location().vectorFrom(Point3.ORIGIN);
Vector3 R = new Vector3(cp.x(), 0.0, cp.z()).unit();
Vector3 r = cp.minus(R.times(major)).unit();
return new Point2(
(Math.PI + Math.atan2(-cp.z(), cp.x())) / (2.0 * Math.PI),
(Math.PI + Math.atan2(cp.y(), R.dot(r))) / (2.0 * Math.PI)
);
}
/* (non-Javadoc)
* @see org.jmist.framework.Geometry#isClosed()
*/
@Override
public boolean isClosed() {
return true;
}
/* (non-Javadoc)
* @see org.jmist.framework.Bounded3#boundingBox()
*/
@Override
public Box3 boundingBox() {
return new Box3(
-(major + minor), -minor, -(major + minor),
major + minor , minor, major + minor
);
}
/* (non-Javadoc)
* @see org.jmist.framework.Bounded3#boundingSphere()
*/
@Override
public Sphere boundingSphere() {
return new Sphere(Point3.ORIGIN, major + minor);
}
/**
* The major radius of the torus (i.e., the distance from the center of the
* torus to a point in the center of the tube.
*/
private final double major;
/**
* The minor radius of the torus (i.e., the radius of the tube).
*/
private final double minor;
} |
package org.ohmage.request.survey;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ohmage.annotator.ErrorCodes;
import org.ohmage.cache.SurveyResponsePrivacyStateCache;
import org.ohmage.cache.UserBin;
import org.ohmage.dao.SurveyResponseReadDao;
import org.ohmage.domain.configuration.Configuration;
import org.ohmage.domain.survey.read.CustomChoiceItem;
import org.ohmage.domain.survey.read.PromptResponseMetadata;
import org.ohmage.domain.survey.read.SurveyResponseReadIndexedResult;
import org.ohmage.domain.survey.read.SurveyResponseReadResult;
import org.ohmage.exception.DataAccessException;
import org.ohmage.exception.ServiceException;
import org.ohmage.exception.ValidationException;
import org.ohmage.request.InputKeys;
import org.ohmage.request.UserRequest;
import org.ohmage.service.CampaignServices;
import org.ohmage.service.SurveyResponseReadServices;
import org.ohmage.service.UserCampaignServices;
import org.ohmage.util.CookieUtils;
import org.ohmage.util.JsonUtils;
import org.ohmage.util.StringUtils;
import org.ohmage.validator.DateValidators;
import org.ohmage.validator.SurveyResponseReadValidators;
/**
* <p>Allows a requester to read survey responses. Supervisors can read survey
* responses anytime. Survey response owners (i.e., participants) can read
* their own responses anytime. Authors can only read shared responses.
* Analysts can read shared responses only if the campaign is shared.</p>
* <table border="1">
* <tr>
* <td>Parameter Name</td>
* <td>Description</td>
* <td>Required</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#AUTH_TOKEN}</td>
* <td>The requesting user's authentication token.</td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#CLIENT}</td>
* <td>A string describing the client that is making this request.</td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#CAMPAIGN_URN}</td>
* <td>The campaign URN to use when retrieving responses.</td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#USER_LIST}</td>
* <td>A comma-separated list of usernames to retrieve responses for
* or the value {@value URN_SPECIAL_ALL}</td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#COLUMN_LIST}</td>
* <td>A comma-separated list of the columns to retrieve responses for
* or the value {@value #_URN_SPECIAL_ALL}. If {@value #_URN_SPECIAL_ALL}
* is not used, the only allowed values are:
* {@value #_URN_CONTEXT_CLIENT},
* {@value #_URN_CONTEXT_TIMESTAMP},
* {@value #_URN_CONTEXT_URN_CONTEXT_TIMEZONE},
* {@value #_URN_CONTEXT_UTC_TIMESTAMP},
* {@value #_URN_CONTEXT_LAUNCH_CONTEXT_LONG},
* {@value #_URN_CONTEXT_LAUNCH_CONTEXT_SHORT},
* {@value #_URN_CONTEXT_LOCATION_STATUS},
* {@value #_URN_CONTEXT_LOCATION_LATITUDE},
* {@value #_URN_CONTEXT_LOCATION_TIMESTAMP},
* {@value #_URN_CONTEXT_LOCATION_ACCURACY},
* {@value #_URN_CONTEXT_LOCATION_PROVIDER},
* {@value #_URN_USER_ID},
* {@value #_URN_SURVEY_ID},
* {@value #_URN_SURVEY_TITLE},
* {@value #_URN_SURVEY_DESCRIPTION},
* {@value #_URN_SURVEY_PRIVACY_STATE},
* {@value #_URN_REPEATABLE_SET_ID},
* {@value #_URN_REPEATABLE_SET_ITERATION},
* {@value #_URN_PROMPT_RESPONSE}
* </td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#OUTPUT_FORMAT}</td>
* <td>The desired output format of the results. Must be one of
* {@value #_OUTPUT_FORMAT_JSON_ROWS}, {@value #_OUTPUT_FORMAT_JSON_COLUMNS},
* or, {@value #_OUTPUT_FORMAT_CSV}</td>
* <td>true</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#PROMPT_ID_LIST}</td>
* <td>A comma-separated list of prompt ids to retrieve responses for
* or the value {@link #_URN_SPECIAL_ALL}. This key is only
* optional if {@value org.ohmage.request.InputKeys#SURVEY_ID_LIST}
* is not present.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#SURVEY_ID_LIST}</td>
* <td>A comma-separated list of survey ids to retrieve responses for
* or the value {@link #_URN_SPECIAL_ALL}. This key is only
* optional if {@value org.ohmage.request.InputKeys#PROMPT_ID_LIST}
* is not present.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#START_DATE}</td>
* <td>The start date to use for results between dates.
* Required if end date is present.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#END_DATE}</td>
* <td>The end date to use for results between dates.
* Required if start date is present.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#SORT_ORDER}</td>
* <td>The sort order to use i.e., the SQL order by.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#SUPPRESS_METADATA}</td>
* <td>For {@value #_OUTPUT_FORMAT_CSV} output, whether to suppress the
* metadata section from the output</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#PRETTY_PRINT}</td>
* <td>For JSON-based output, whether to pretty print the output</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#RETURN_ID}</td>
* <td>For {@value #_OUTPUT_FORMAT_JSON_ROWS} output, whether to return
* the id on each result. The web front-end uses the id value to perform
* updates.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#PRIVACY_STATE}</td>
* <td>Filters the results by their associated privacy state.</td>
* <td>false</td>
* </tr>
* <tr>
* <td>{@value org.ohmage.request.InputKeys#COLLAPSE}</td>
* <td>Filters the results by uniqueness.</td>
* <td>false</td>
* </tr>
* </table>
*
* @author Joshua Selsky
*/
public final class SurveyResponseReadRequest extends UserRequest {
private static final Logger LOGGER = Logger.getLogger(SurveyResponseReadRequest.class);
private final Date startDate;
private final Date endDate;
private final String campaignUrn;
private final List<String> userList;
private final List<String> promptIdList;
private final List<String> surveyIdList;
private final List<String> columnList;
private final String outputFormat;
private final Boolean prettyPrint;
private final Boolean suppressMetadata;
private final Boolean returnId;
private final String sortOrder;
private final String privacyState;
private final Boolean collapse;
private Configuration configuration;
private List<SurveyResponseReadResult> surveyResponseList;
private static final int MAGIC_CUSTOM_CHOICE_INDEX = 100;
private static final List<String> ALLOWED_COLUMN_URN_LIST;
private static final List<String> ALLOWED_OUTPUT_FORMAT_LIST;
private static final List<String> ALLOWED_SORT_ORDER_LIST;
public static final String URN_SPECIAL_ALL = "urn:ohmage:special:all";
public static final List<String> URN_SPECIAL_ALL_LIST;
public static final String URN_CONTEXT_CLIENT = "urn:ohmage:context:client";
public static final String URN_CONTEXT_TIMESTAMP = "urn:ohmage:context:timestamp";
public static final String URN_CONTEXT_TIMEZONE = "urn:ohmage:context:timezone";
public static final String URN_CONTEXT_UTC_TIMESTAMP = "urn:ohmage:context:utc_timestamp";
public static final String URN_CONTEXT_LAUNCH_CONTEXT_LONG = "urn:ohmage:context:launch_context_long";
public static final String URN_CONTEXT_LAUNCH_CONTEXT_SHORT = "urn:ohmage:context:launch_context_short";
public static final String URN_CONTEXT_LOCATION_STATUS = "urn:ohmage:context:location:status";
public static final String URN_CONTEXT_LOCATION_LATITUDE = "urn:ohmage:context:location:latitude";
public static final String URN_CONTEXT_LOCATION_LONGITUDE = "urn:ohmage:context:location:longitude";
public static final String URN_CONTEXT_LOCATION_TIMESTAMP = "urn:ohmage:context:location:timestamp";
public static final String URN_CONTEXT_LOCATION_ACCURACY = "urn:ohmage:context:location:accuracy";
public static final String URN_CONTEXT_LOCATION_PROVIDER = "urn:ohmage:context:location:provider";
public static final String URN_USER_ID = "urn:ohmage:user:id";
public static final String URN_SURVEY_ID = "urn:ohmage:survey:id";
public static final String URN_SURVEY_TITLE = "urn:ohmage:survey:title";
public static final String URN_SURVEY_DESCRIPTION = "urn:ohmage:survey:description";
public static final String URN_SURVEY_PRIVACY_STATE = "urn:ohmage:survey:privacy_state";
public static final String URN_REPEATABLE_SET_ID = "urn:ohmage:repeatable_set:id";
public static final String URN_REPEATABLE_SET_ITERATION = "urn:ohmage:repeatable_set:iteration";
public static final String URN_PROMPT_RESPONSE = "urn:ohmage:prompt:response";
private static final String URN_PROMPT_ID_PREFIX = "urn:ohmage:prompt:id:";
// output format constants - these are the output formats the requester
// can select from
public static final String OUTPUT_FORMAT_JSON_ROWS = "json-rows";
public static final String OUTPUT_FORMAT_JSON_COLUMNS = "json-columns";
public static final String OUTPUT_FORMAT_CSV = "csv";
// FIXME: some of these constants belong elsewhere with the survey response
// upload prompt type hierarchy where there all still a bunch of hard-coded
// strings
private static final String SKIPPED = "SKIPPED";
private static final String NOT_DISPLAYED = "NOT_DISPLAYED";
private static final String VALUE = "value";
private static final String SINGLE_CHOICE_CUSTOM = "single_choice_custom";
private static final String MULTI_CHOICE_CUSTOM = "multi_choice_custom";
private static final String CUSTOM_CHOICES = "custom_choices";
private static final String CHOICE_ID = "choice_id";
private static final String CHOICE_VALUE = "choice_value";
private static final String GLOBAL = "global";
private static final String CUSTOM = "custom";
static {
ALLOWED_COLUMN_URN_LIST = Arrays.asList(new String[] {
URN_CONTEXT_CLIENT, URN_CONTEXT_TIMESTAMP, URN_CONTEXT_TIMEZONE, URN_CONTEXT_UTC_TIMESTAMP,
URN_CONTEXT_LAUNCH_CONTEXT_LONG, URN_CONTEXT_LAUNCH_CONTEXT_SHORT, URN_CONTEXT_LOCATION_STATUS,
URN_CONTEXT_LOCATION_LATITUDE, URN_CONTEXT_LOCATION_LONGITUDE, URN_CONTEXT_LOCATION_TIMESTAMP,
URN_CONTEXT_LOCATION_ACCURACY, URN_CONTEXT_LOCATION_PROVIDER, URN_USER_ID, URN_SURVEY_ID,
URN_SURVEY_TITLE, URN_SURVEY_DESCRIPTION, URN_SURVEY_PRIVACY_STATE, URN_REPEATABLE_SET_ID,
URN_REPEATABLE_SET_ITERATION, URN_PROMPT_RESPONSE
});
ALLOWED_OUTPUT_FORMAT_LIST = Arrays.asList(new String[] {OUTPUT_FORMAT_JSON_ROWS, OUTPUT_FORMAT_JSON_COLUMNS, OUTPUT_FORMAT_CSV});
ALLOWED_SORT_ORDER_LIST = Arrays.asList(new String[] {InputKeys.SORT_ORDER_SURVEY, InputKeys.SORT_ORDER_TIMESTAMP, InputKeys.SORT_ORDER_USER});
URN_SPECIAL_ALL_LIST = Collections.unmodifiableList(Arrays.asList(new String[]{URN_SPECIAL_ALL}));
}
/**
* Creates a survey response read request.
*
* @param httpRequest The request to retrieve parameters from.
*/
public SurveyResponseReadRequest(HttpServletRequest httpRequest) {
// Handle user-password or token-based authentication
super(httpRequest, TokenLocation.EITHER, false);
Date tStartDateAsDate = null;
Date tEndDateAsDate = null;
String tCampaignUrn = getParameter(InputKeys.CAMPAIGN_URN);
String tOutputFormat = getParameter(InputKeys.OUTPUT_FORMAT);
String tSortOrder = getParameter(InputKeys.SORT_ORDER);
String tPrivacyState = getParameter(InputKeys.PRIVACY_STATE);
List<String> tUserListAsList = null;
List<String> tPromptIdListAsList = null;
List<String> tSurveyIdListAsList = null;
List<String> tColumnListAsList = null;
Boolean tPrettyPrintAsBoolean = null;
Boolean tSuppressMetadataAsBoolean = null;
Boolean tReturnIdAsBoolean = null;
Boolean tCollapseAsBoolean = null;
if(! isFailed()) {
LOGGER.info("Creating a survey response read request.");
try {
// FIXME constant-ify the hard-coded strings, maybe even for
// logging messages (possibly AOP-ify logging)
// Also, move validation to the SurveyResponseReadValidators
// And check for multiple copies of params
LOGGER.info("Making sure campaign_urn parameter is present.");
if(tCampaignUrn == null) {
setFailed(ErrorCodes.CAMPAIGN_INVALID_ID, "The required campaign URN was not present.");
throw new ValidationException("The required campaign URN was not present.");
}
LOGGER.info("Validating start_date and end_date parameters.");
try {
if(! StringUtils.isEmptyOrWhitespaceOnly(getParameter(InputKeys.START_DATE))) {
tStartDateAsDate = DateValidators.validateISO8601Date(getParameter(InputKeys.START_DATE));
}
else {
tStartDateAsDate = null;
}
if(! StringUtils.isEmptyOrWhitespaceOnly(getParameter(InputKeys.END_DATE))) {
tEndDateAsDate = DateValidators.validateISO8601Date(getParameter(InputKeys.END_DATE));
}
else {
tEndDateAsDate = null;
}
if((tStartDateAsDate != null && tEndDateAsDate == null) || (tStartDateAsDate == null && tEndDateAsDate != null)) {
setFailed(ErrorCodes.SERVER_INVALID_DATE, "Missing start_date or end_date");
}
}
catch (ValidationException e) { // FIXME the DateValidators methods should take a Request parameter to fail
setFailed(ErrorCodes.SERVER_INVALID_DATE, "Invalid start_date or end_date");
throw e;
}
LOGGER.info("Validating privacy_state parameter.");
if(! StringUtils.isEmptyOrWhitespaceOnly(tPrivacyState) &&
! SurveyResponsePrivacyStateCache.instance().getKeys().contains(tPrivacyState)) {
setFailed(ErrorCodes.SURVEY_INVALID_PRIVACY_STATE, "Found unknown privacy_state: " + tPrivacyState);
throw new ValidationException("Found unknown privacy_state: " + tPrivacyState);
}
LOGGER.info("Validating user_list parameter.");
tUserListAsList = SurveyResponseReadValidators.validateUserList(this, getParameter(InputKeys.USER_LIST));
LOGGER.info("Validating prompt_id_list and survey_id_list parameters.");
List<String> tList = SurveyResponseReadValidators.validatePromptIdSurveyIdLists(this, getParameter(InputKeys.PROMPT_ID_LIST), getParameter(InputKeys.SURVEY_ID_LIST));
// Now check whether it's a prompt id list or a survey id list
if(StringUtils.isEmptyOrWhitespaceOnly(getParameter(InputKeys.PROMPT_ID_LIST))) {
LOGGER.info("Found " + tList.size() + " survey ids to query against.");
tSurveyIdListAsList = tList;
tPromptIdListAsList = Collections.emptyList();
}
else {
LOGGER.info("Found " + tList.size() + " prompt ids to query against.");
tSurveyIdListAsList = Collections.emptyList();
tPromptIdListAsList = tList;
}
LOGGER.info("Validating column_list parameter.");
tColumnListAsList = SurveyResponseReadValidators.validateColumnList(this, getParameter(InputKeys.COLUMN_LIST), ALLOWED_COLUMN_URN_LIST);
LOGGER.info("Validating output_format parameter.");
tOutputFormat = SurveyResponseReadValidators.validateOutputFormat(this, tOutputFormat, ALLOWED_OUTPUT_FORMAT_LIST);
LOGGER.info("Validating sort_order parameter.");
tSortOrder = SurveyResponseReadValidators.validateSortOrder(this, tSortOrder, ALLOWED_SORT_ORDER_LIST);
LOGGER.info("Validating suppress_metadata parameter.");
tSuppressMetadataAsBoolean = SurveyResponseReadValidators.validateSuppressMetadata(this, getParameter(InputKeys.SUPPRESS_METADATA));
LOGGER.info("Validating pretty_print parameter.");
tPrettyPrintAsBoolean = SurveyResponseReadValidators.validatePrettyPrint(this, getParameter(InputKeys.PRETTY_PRINT));
LOGGER.info("Validating return_id parameter.");
tReturnIdAsBoolean = SurveyResponseReadValidators.validateReturnId(this, getParameter(InputKeys.RETURN_ID));
LOGGER.info("Validating collapse parameter.");
tCollapseAsBoolean = SurveyResponseReadValidators.validateCollapse(this, getParameter(InputKeys.COLLAPSE));
}
catch (ValidationException e) {
LOGGER.info(e);
}
}
this.campaignUrn = tCampaignUrn;
this.collapse = tCollapseAsBoolean;
this.columnList = tColumnListAsList;
this.endDate = tEndDateAsDate;
this.outputFormat = tOutputFormat;
this.prettyPrint = tPrettyPrintAsBoolean;
this.privacyState = tPrivacyState;
this.promptIdList = tPromptIdListAsList;
this.returnId = tReturnIdAsBoolean;
this.sortOrder = tSortOrder;
this.startDate = tStartDateAsDate;
this.suppressMetadata = tSuppressMetadataAsBoolean;
this.surveyIdList = tSurveyIdListAsList;
this.userList = tUserListAsList;
}
/**
* Services this request.
*/
@Override
public void service() {
LOGGER.info("Servicing a survey response read request.");
if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) {
return;
}
try {
LOGGER.info("Populating the requester with their associated campaigns and roles.");
UserCampaignServices.populateUserWithCampaignRoleInfo(this, this.getUser());
LOGGER.info("Verifying that requester belongs to the campaign specified by campaign ID.");
UserCampaignServices.campaignExistsAndUserBelongs(this, this.getUser(), this.campaignUrn);
LOGGER.info("Verifying that the requester has a role that allows reading of survey responses for each of the users in the list.");
UserCampaignServices.requesterCanViewUsersSurveyResponses(this, this.campaignUrn, this.getUser().getUsername(), (String[]) userList.toArray());
if(! this.userList.equals(URN_SPECIAL_ALL_LIST)) {
LOGGER.info("Checking the user list to make sure all of the users belong to the campaign ID.");
UserCampaignServices.verifyUsersExistInCampaign(this, this.campaignUrn, this.userList);
}
LOGGER.info("Retrieving campaign configuration.");
this.configuration = CampaignServices.findCampaignConfiguration(this, this.campaignUrn);
if(! this.promptIdList.isEmpty() && ! this.promptIdList.equals(URN_SPECIAL_ALL_LIST)) {
LOGGER.info("Verifying that the prompt ids in the query belong to the campaign.");
SurveyResponseReadServices.verifyPromptIdsBelongToConfiguration(this, this.promptIdList, this.configuration);
}
if(! this.surveyIdList.isEmpty() && ! this.surveyIdList.equals(URN_SPECIAL_ALL_LIST)) {
LOGGER.info("Verifying that the survey ids in the query belong to the campaign.");
SurveyResponseReadServices.verifySurveyIdsBelongToConfiguration(this, this.surveyIdList, this.configuration);
}
LOGGER.info("Dispatching to the data layer.");
this.surveyResponseList = SurveyResponseReadDao.retrieveSurveyResponses(this, this.userList,
this.campaignUrn, this.promptIdList, this.surveyIdList, this.startDate, this.endDate, this.sortOrder,
this.configuration);
LOGGER.info("Filtering survey response results according to our privacy rules and the requester's role.");
SurveyResponseReadServices.performPrivacyFilter(this.getUser(), this.campaignUrn, surveyResponseList, this.privacyState);
}
catch(ServiceException e) {
e.logException(LOGGER);
}
catch(DataAccessException e) {
e.logException(LOGGER);
}
}
/**
* Builds the output depending on the state of this request and whatever
* output format the requester selected.
*/
@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
Writer writer = null;
try {
// Prepare for sending the response to the client
writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse)));
String responseText = null;
// Sets the HTTP headers to disable caching
expireResponse(httpResponse);
final String token = this.getUser().getToken();
if(token != null) {
CookieUtils.setCookieValue(httpResponse, InputKeys.AUTH_TOKEN, token, (int) (UserBin.getTokenRemainingLifetimeInMillis(token) / MILLIS_IN_A_SECOND));
}
// Set the content type depending on the output format the
// requester requested.
if(OUTPUT_FORMAT_CSV.equals(this.outputFormat)) {
httpResponse.setContentType("text/csv");
httpResponse.setHeader("Content-Disposition", "attachment; f.txt");
} else {
httpResponse.setContentType("application/json");
}
// Build the appropriate response
if(! isFailed()) {
List<String> columnList = this.columnList;
List<String> outputColumns = new ArrayList<String>();
List<SurveyResponseReadIndexedResult> indexedResultList = new ArrayList<SurveyResponseReadIndexedResult>();
// Build the column headers
// Each column is a Map with a list containing the values for each row
if(URN_SPECIAL_ALL.equals(columnList.get(0))) {
outputColumns.addAll(ALLOWED_COLUMN_URN_LIST);
} else {
outputColumns.addAll(columnList);
}
if(columnList.contains(URN_PROMPT_RESPONSE) || URN_SPECIAL_ALL.equals(columnList.get(0))) {
// The logic here is that if the user is requesting results for survey ids, they want all of the prompts
// for those survey ids
// So, loop through the results and find all of the unique prompt ids by forcing them into a Set
Set<String> promptIdSet = new HashSet<String>();
if(0 != surveyResponseList.size()) {
for(SurveyResponseReadResult result : surveyResponseList) {
promptIdSet.add(URN_PROMPT_ID_PREFIX + result.getPromptId());
}
outputColumns.addAll(promptIdSet);
}
}
// get rid of urn:ohmage:prompt:response because it has been replaced with specific prompt ids
// the list will be unchanged if it didn't already contain urn:ohmage:prompt:response
outputColumns.remove(URN_PROMPT_RESPONSE);
// For every result found by the query, the prompt responses need to be rolled up so they are all stored
// with their associated survey response and metadata. Each prompt response is returned from the db in its
// own row and the rows can have different sort orders.
boolean isCsv = OUTPUT_FORMAT_CSV.equals(this.outputFormat);
for(SurveyResponseReadResult result : surveyResponseList) {
if(indexedResultList.isEmpty()) { // first time thru
indexedResultList.add(new SurveyResponseReadIndexedResult(result, isCsv));
}
else {
int numberOfIndexedResults = indexedResultList.size();
boolean found = false;
for(int i = 0; i < numberOfIndexedResults; i++) {
if(indexedResultList.get(i).getKey().keysAreEqual(result.getUsername(),
result.getTimestamp(),
result.getSurveyId(),
result.getRepeatableSetId(),
result.getRepeatableSetIteration())) {
found = true;
indexedResultList.get(i).addPromptResponse(result, isCsv);
}
}
if(! found) {
indexedResultList.add(new SurveyResponseReadIndexedResult(result, isCsv));
}
}
}
// For csv and json-columns output, the custom choices need to be converted
// into unique-ified list in order for visualiztions and export to work
// properly. The key is the prompt id.
Map<String, List<CustomChoiceItem>> uniqueCustomChoiceMap = null; // will be converted into a choice glossary
// for the custom types
Map<String, Integer> uniqueCustomChoiceIndexMap = null;
// Now find the custom choice prompts (if there are any) and
// unique-ify the entries for their choice glossaries, create
// their choice glossaries, and clean up the display value
// (i.e., remove all the custom_choices stuff and leave only
// the value or values the user selected).
for(SurveyResponseReadIndexedResult result : indexedResultList) {
Map<String, PromptResponseMetadata> promptResponseMetadataMap = result.getPromptResponseMetadataMap();
Iterator<String> responseMetadataKeyIterator = promptResponseMetadataMap.keySet().iterator();
while(responseMetadataKeyIterator.hasNext()) {
String promptId = (responseMetadataKeyIterator.next());
PromptResponseMetadata metadata = promptResponseMetadataMap.get(promptId);
if(SINGLE_CHOICE_CUSTOM.equals(metadata.getPromptType()) || MULTI_CHOICE_CUSTOM.equals(metadata.getPromptType())) {
List<CustomChoiceItem> customChoiceItems = null;
if(null == uniqueCustomChoiceMap) { // lazily initialized in case there are no custom choices
uniqueCustomChoiceMap = new HashMap<String, List<CustomChoiceItem>>();
}
if(! uniqueCustomChoiceMap.containsKey(promptId)) {
customChoiceItems = new ArrayList<CustomChoiceItem>();
uniqueCustomChoiceMap.put(promptId, customChoiceItems);
}
else {
customChoiceItems = uniqueCustomChoiceMap.get(promptId);
}
String tmp = (String) result.getPromptResponseMap().get(promptId);
if(! (SKIPPED.equals(tmp) || NOT_DISPLAYED.equals(tmp))) {
// All of the data for the choice_glossary for custom types is stored in its JSON response
JSONObject customChoiceResponse = new JSONObject((String) result.getPromptResponseMap().get(promptId));
// Since the glossary will not contain the custom choices, the result's display value
// can simply be the values the user chose.
// The value will either be a string (single_choice_custom) or an array (multi_choice_custom)
Integer singleChoiceValue = JsonUtils.getIntegerFromJsonObject(customChoiceResponse, VALUE);
if(null != singleChoiceValue) {
result.getPromptResponseMap().put(promptId, singleChoiceValue);
}
else {
result.getPromptResponseMap().put(promptId, JsonUtils.getJsonArrayFromJsonObject(customChoiceResponse, VALUE));
}
JSONArray customChoices = JsonUtils.getJsonArrayFromJsonObject(customChoiceResponse, CUSTOM_CHOICES);
for(int i = 0; i < customChoices.length(); i++) {
JSONObject choice = JsonUtils.getJsonObjectFromJsonArray(customChoices, i);
// If the choice_id is >= 100, it means that is it a choice that the user added
// In the current system, users cannot remove choices
int originalId = choice.getInt(CHOICE_ID);
CustomChoiceItem cci = null;
boolean isGlobal = false;
if(originalId < MAGIC_CUSTOM_CHOICE_INDEX) {
cci = new CustomChoiceItem(originalId, result.getUsername(), choice.getString(CHOICE_VALUE), GLOBAL);
isGlobal = true;
}
else {
cci = new CustomChoiceItem(originalId, result.getUsername(), choice.getString(CHOICE_VALUE), CUSTOM);
}
if(! customChoiceItems.contains(cci)) {
if(isGlobal) {
cci.setId(cci.getOriginalId());
customChoiceItems.add(cci);
}
else {
if(null == uniqueCustomChoiceIndexMap) {
uniqueCustomChoiceIndexMap = new HashMap<String, Integer>();
}
if(! uniqueCustomChoiceIndexMap.containsKey(promptId)) {
uniqueCustomChoiceIndexMap.put(promptId, MAGIC_CUSTOM_CHOICE_INDEX - 1);
}
int uniqueId = uniqueCustomChoiceIndexMap.get(promptId) + 1;
cci.setId(uniqueId);
customChoiceItems.add(cci);
uniqueCustomChoiceIndexMap.put(promptId, uniqueId);
}
}
}
}
}
}
}
int numberOfSurveys = indexedResultList.size();
int numberOfPrompts = this.surveyResponseList.size();
// Delete the original result list
this.surveyResponseList.clear();
this.surveyResponseList = null;
if(OUTPUT_FORMAT_JSON_ROWS.equals(this.outputFormat)) {
responseText = SurveyResponseReadServices.generateJsonRowsOutput(this, numberOfSurveys, numberOfPrompts, indexedResultList, outputColumns, uniqueCustomChoiceMap);
}
else if(OUTPUT_FORMAT_JSON_COLUMNS.equals(this.outputFormat)) {
if(indexedResultList.isEmpty()) {
responseText = SurveyResponseReadServices.generateZeroResultJsonColumnOutput(this, outputColumns);
} else {
responseText = SurveyResponseReadServices.generateMultiResultJsonColumnOutput(this, numberOfSurveys, numberOfPrompts, indexedResultList, outputColumns, uniqueCustomChoiceMap);
}
}
else if(OUTPUT_FORMAT_CSV.equals(this.outputFormat)) {
if(indexedResultList.isEmpty()) {
responseText = SurveyResponseReadServices.generateZeroResultCsvOutput(this, outputColumns);
} else {
responseText = SurveyResponseReadServices.generateMultiResultCsvOutput(this, numberOfSurveys, numberOfPrompts, indexedResultList, outputColumns, uniqueCustomChoiceMap);
}
}
}
else {
// Even for CSV output, the error messages remain JSON
responseText = getFailureMessage();
}
LOGGER.info("Writing survey response read output.");
writer.write(responseText);
}
// FIXME and catch the actual exceptions
catch(Exception e) {
LOGGER.error("An unrecoverable exception occurred while generating a survey response read response", e);
try {
writer.write(getFailureMessage());
} catch (Exception ee) {
LOGGER.error("Caught Exception when attempting to write to HTTP output stream", ee);
}
}
finally {
if(null != writer) {
try {
writer.flush();
writer.close();
writer = null;
} catch (IOException ioe) {
LOGGER.error("Caught IOException when attempting to free resources", ioe);
}
}
}
}
/* Methods for retrieving output formatting variables */
// FIXME: these should just be passed (within one object) to the methods that write the output
public Boolean getPrettyPrint() {
return prettyPrint;
}
public Boolean getSuppressMetadata() {
return suppressMetadata;
}
public Boolean getReturnId() {
return returnId;
}
public Boolean getCollapse() {
return collapse;
}
public Configuration getConfiguration() {
return configuration;
}
public String getCampaignUrn() {
return campaignUrn;
}
} |
package org.ihtsdo.otf.snomedboot;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
class ReleaseFiles {
private Path conceptPath;
private Path descriptionPath;
private Path textDefinitionPath;
private Path relationshipPath;
private Path statedRelationshipPath;
private List<Path> refsetPaths;
public ReleaseFiles() {
refsetPaths = new ArrayList<>();
}
public Path getConceptPath() {
return conceptPath;
}
public void setConceptPath(Path conceptPath) {
this.conceptPath = conceptPath;
}
public Path getDescriptionPath() {
return descriptionPath;
}
public void setDescriptionPath(Path descriptionPath) {
this.descriptionPath = descriptionPath;
}
public Path getTextDefinitionPath() {
return textDefinitionPath;
}
public void setTextDefinitionPath(Path textDefinitionPath) {
this.textDefinitionPath = textDefinitionPath;
}
public Path getRelationshipPath() {
return relationshipPath;
}
public void setRelationshipPath(Path relationshipPath) {
this.relationshipPath = relationshipPath;
}
public Path getStatedRelationshipPath() {
return statedRelationshipPath;
}
public void setStatedRelationshipPath(Path statedRelationshipPath) {
this.statedRelationshipPath = statedRelationshipPath;
}
public List<Path> getRefsetPaths() {
return refsetPaths;
}
public void setRefsetPaths(List<Path> refsetPaths) {
this.refsetPaths = refsetPaths;
}
public void assertFullSet() throws FileNotFoundException {
if (conceptPath == null) {
throw new FileNotFoundException("Concept RF2 file not found.");
} else if (descriptionPath == null) {
throw new FileNotFoundException("Description RF2 file not found.");
} else if (relationshipPath == null) {
throw new FileNotFoundException("Relationship RF2 file not found.");
}
}
@Override
public String toString() {
return "ReleaseFiles{" +
"conceptPath=" + conceptPath +
", descriptionPath=" + descriptionPath +
", textDefinitionPath=" + textDefinitionPath +
", relationshipPath=" + relationshipPath +
", statedRelationshipPath=" + statedRelationshipPath +
", refsetPaths=" + refsetPaths +
'}';
}
} |
package org.influxdb.impl;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.influxdb.InfluxDBMapperException;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;
import org.influxdb.dto.QueryResult;
/**
* Main class responsible for mapping a QueryResult to a POJO.
*
* @author fmachado
*/
public class InfluxDBResultMapper {
/**
* Data structure used to cache classes used as measurements.
*/
private static final
ConcurrentMap<String, ConcurrentMap<String, Field>> CLASS_FIELD_CACHE = new ConcurrentHashMap<>();
private static final int FRACTION_MIN_WIDTH = 0;
private static final int FRACTION_MAX_WIDTH = 9;
private static final boolean ADD_DECIMAL_POINT = true;
/**
* When a query is executed without {@link TimeUnit}, InfluxDB returns the <tt>time</tt>
* column as an ISO8601 date.
*/
private static final DateTimeFormatter ISO8601_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, FRACTION_MIN_WIDTH, FRACTION_MAX_WIDTH, ADD_DECIMAL_POINT)
.appendPattern("X")
.toFormatter();
/**
* <p>
* Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
* data structure and creating the respective object instances based on the Class passed as
* parameter.
* </p>
*
* @param queryResult the InfluxDB result object
* @param clazz the Class that will be used to hold your measurement data
* @param <T> the target type
* @return a {@link List} of objects from the same Class passed as parameter and sorted on the
* same order as received from InfluxDB.
* @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
* <tt>clazz</tt> parameter is not annotated with @Measurement or it was not
* possible to define the values of your POJO (e.g. due to an unsupported field type).
*/
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz) throws InfluxDBMapperException {
Objects.requireNonNull(queryResult, "queryResult");
Objects.requireNonNull(clazz, "clazz");
throwExceptionIfMissingAnnotation(clazz);
throwExceptionIfResultWithError(queryResult);
cacheMeasurementClass(clazz);
List<T> result = new LinkedList<T>();
String measurementName = getMeasurementName(clazz);
queryResult.getResults().stream()
.filter(internalResult -> Objects.nonNull(internalResult) && Objects.nonNull(internalResult.getSeries()))
.forEach(internalResult -> {
internalResult.getSeries().stream()
.filter(series -> series.getName().equals(measurementName))
.forEachOrdered(series -> {
parseSeriesAs(series, clazz, result);
});
});
return result;
}
void throwExceptionIfMissingAnnotation(final Class<?> clazz) {
if (!clazz.isAnnotationPresent(Measurement.class)) {
throw new IllegalArgumentException(
"Class " + clazz.getName() + " is not annotated with @" + Measurement.class.getSimpleName());
}
}
void throwExceptionIfResultWithError(final QueryResult queryResult) {
if (queryResult.getError() != null) {
throw new InfluxDBMapperException("InfluxDB returned an error: " + queryResult.getError());
}
queryResult.getResults().forEach(seriesResult -> {
if (seriesResult.getError() != null) {
throw new InfluxDBMapperException("InfluxDB returned an error with Series: " + seriesResult.getError());
}
});
}
void cacheMeasurementClass(final Class<?>... classVarAgrs) {
for (Class<?> clazz : classVarAgrs) {
if (CLASS_FIELD_CACHE.containsKey(clazz.getName())) {
continue;
}
ConcurrentMap<String, Field> initialMap = new ConcurrentHashMap<>();
ConcurrentMap<String, Field> influxColumnAndFieldMap = CLASS_FIELD_CACHE.putIfAbsent(clazz.getName(), initialMap);
if (influxColumnAndFieldMap == null) {
influxColumnAndFieldMap = initialMap;
}
for (Field field : clazz.getDeclaredFields()) {
Column colAnnotation = field.getAnnotation(Column.class);
if (colAnnotation != null) {
influxColumnAndFieldMap.put(colAnnotation.name(), field);
}
}
}
}
String getMeasurementName(final Class<?> clazz) {
return ((Measurement) clazz.getAnnotation(Measurement.class)).name();
}
<T> List<T> parseSeriesAs(final QueryResult.Series series, final Class<T> clazz, final List<T> result) {
int columnSize = series.getColumns().size();
ConcurrentMap<String, Field> colNameAndFieldMap = CLASS_FIELD_CACHE.get(clazz.getName());
try {
T object = null;
for (List<Object> row : series.getValues()) {
for (int i = 0; i < columnSize; i++) {
Field correspondingField = colNameAndFieldMap.get(series.getColumns().get(i)/*InfluxDB columnName*/);
if (correspondingField != null) {
if (object == null) {
object = clazz.newInstance();
}
setFieldValue(object, correspondingField, row.get(i));
}
}
// When the "GROUP BY" clause is used, "tags" are returned as Map<String,String> and
// accordingly with InfluxDB documentation
// https://docs.influxdata.com/influxdb/v1.2/concepts/glossary/#tag-value
// "tag" values are always String.
if (series.getTags() != null && !series.getTags().isEmpty()) {
for (Entry<String, String> entry : series.getTags().entrySet()) {
Field correspondingField = colNameAndFieldMap.get(entry.getKey()/*InfluxDB columnName*/);
if (correspondingField != null) {
// I don't think it is possible to reach here without a valid "object"
setFieldValue(object, correspondingField, entry.getValue());
}
}
}
if (object != null) {
result.add(object);
object = null;
}
}
} catch (InstantiationException | IllegalAccessException e) {
throw new InfluxDBMapperException(e);
}
return result;
}
<T> void setFieldValue(final T object, final Field field, final Object value)
throws IllegalArgumentException, IllegalAccessException {
if (value == null) {
return;
}
Class<?> fieldType = field.getType();
try {
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (fieldValueModified(fieldType, field, object, value)
|| fieldValueForPrimitivesModified(fieldType, field, object, value)
|| fieldValueForPrimitiveWrappersModified(fieldType, field, object, value)) {
return;
}
String msg = "Class '%s' field '%s' is from an unsupported type '%s'.";
throw new InfluxDBMapperException(
String.format(msg, object.getClass().getName(), field.getName(), field.getType()));
} catch (ClassCastException e) {
String msg = "Class '%s' field '%s' was defined with a different field type and caused a ClassCastException. "
+ "The correct type is '%s' (current field value: '%s').";
throw new InfluxDBMapperException(
String.format(msg, object.getClass().getName(), field.getName(), value.getClass().getName(), value));
}
}
<T> boolean fieldValueModified(final Class<?> fieldType, final Field field, final T object, final Object value)
throws IllegalArgumentException, IllegalAccessException {
if (String.class.isAssignableFrom(fieldType)) {
field.set(object, String.valueOf(value));
return true;
}
if (Instant.class.isAssignableFrom(fieldType)) {
Instant instant;
if (value instanceof String) {
instant = Instant.from(ISO8601_FORMATTER.parse(String.valueOf(value)));
} else if (value instanceof Long) {
instant = Instant.ofEpochMilli((Long) value);
} else if (value instanceof Double) {
instant = Instant.ofEpochMilli(((Double) value).longValue());
} else {
throw new InfluxDBMapperException("Unsupported type " + field.getClass() + " for field " + field.getName());
}
field.set(object, instant);
return true;
}
return false;
}
<T> boolean fieldValueForPrimitivesModified(final Class<?> fieldType, final Field field, final T object,
final Object value) throws IllegalArgumentException, IllegalAccessException {
if (double.class.isAssignableFrom(fieldType)) {
field.setDouble(object, ((Double) value).doubleValue());
return true;
}
if (long.class.isAssignableFrom(fieldType)) {
field.setLong(object, ((Double) value).longValue());
return true;
}
if (int.class.isAssignableFrom(fieldType)) {
field.setInt(object, ((Double) value).intValue());
return true;
}
if (boolean.class.isAssignableFrom(fieldType)) {
field.setBoolean(object, Boolean.valueOf(String.valueOf(value)).booleanValue());
return true;
}
return false;
}
<T> boolean fieldValueForPrimitiveWrappersModified(final Class<?> fieldType, final Field field, final T object,
final Object value) throws IllegalArgumentException, IllegalAccessException {
if (Double.class.isAssignableFrom(fieldType)) {
field.set(object, value);
return true;
}
if (Long.class.isAssignableFrom(fieldType)) {
field.set(object, Long.valueOf(((Double) value).longValue()));
return true;
}
if (Integer.class.isAssignableFrom(fieldType)) {
field.set(object, Integer.valueOf(((Double) value).intValue()));
return true;
}
if (Boolean.class.isAssignableFrom(fieldType)) {
field.set(object, Boolean.valueOf(String.valueOf(value)));
return true;
}
return false;
}
} |
package org.javarosa.core.model;
import org.javarosa.core.model.condition.IConditionExpr;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.util.restorable.RestoreUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
public class ItemsetBinding implements Externalizable {
/**
* note that storing both the ref and expr for everything is kind of redundant, but we're forced
* to since it's nearly impossible to convert between the two w/o having access to the underlying
* xform/xpath classes, which we don't from the core model project
*/
public TreeReference nodesetRef; //absolute ref of itemset source nodes
public IConditionExpr nodesetExpr; //path expression for source nodes; may be relative, may contain predicates
public TreeReference contextRef; //context ref for nodesetExpr; ref of the control parent (group/formdef) of itemset question
//note: this is only here because its currently impossible to both (a) get a form control's parent, and (b)
//convert expressions into refs while preserving predicates. once these are fixed, this field can go away
public TreeReference labelRef; //absolute ref of label
public IConditionExpr labelExpr; //path expression for label; may be relative, no predicates
public boolean labelIsItext; //if true, content of 'label' is an itext id
public boolean copyMode; //true = copy subtree; false = copy string value
public TreeReference copyRef; //absolute ref to copy
public TreeReference valueRef; //absolute ref to value
public IConditionExpr valueExpr; //path expression for value; may be relative, no predicates (must be relative if copy mode)
public TreeReference sortRef; //absolute ref to sort
public IConditionExpr sortExpr; //path expression for sort; may be relative, no predicates (must be relative if copy mode)
private TreeReference destRef; //ref that identifies the repeated nodes resulting from this itemset
// dynamic choices, not serialized
private Vector<SelectChoice> choices;
public Vector<SelectChoice> getChoices() {
return choices;
}
public void setChoices(Vector<SelectChoice> choices) {
if (this.choices != null) {
clearChoices();
}
this.choices = choices;
sortChoices();
}
private void sortChoices() {
if (this.sortRef != null) {
// Perform sort
Collections.sort(choices, new Comparator<SelectChoice>() {
@Override
public int compare(SelectChoice choice1, SelectChoice choice2) {
return choice1.evaluatedSortProperty.compareTo(choice2.evaluatedSortProperty);
}
});
// Re-set indices after sorting
for (int i = 0; i < choices.size(); i++) {
choices.get(i).setIndex(i);
}
}
}
public void clearChoices() {
this.choices = null;
}
public void setDestRef(QuestionDef q) {
destRef = FormInstance.unpackReference(q.getBind()).clone();
if (copyMode) {
destRef.add(copyRef.getNameLast(), TreeReference.INDEX_UNBOUND);
}
}
public TreeReference getDestRef() {
return destRef;
}
public IConditionExpr getRelativeValue() {
TreeReference relRef = null;
if (copyRef == null) {
relRef = valueRef; //must be absolute in this case
} else if (valueRef != null) {
relRef = valueRef.relativize(copyRef);
}
return relRef != null ? RestoreUtils.refToPathExpr(relRef) : null;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
nodesetRef = (TreeReference)ExtUtil.read(in, TreeReference.class, pf);
nodesetExpr = (IConditionExpr)ExtUtil.read(in, new ExtWrapTagged(), pf);
contextRef = (TreeReference)ExtUtil.read(in, TreeReference.class, pf);
labelRef = (TreeReference)ExtUtil.read(in, TreeReference.class, pf);
labelExpr = (IConditionExpr)ExtUtil.read(in, new ExtWrapTagged(), pf);
valueRef = (TreeReference)ExtUtil.read(in, new ExtWrapNullable(TreeReference.class), pf);
valueExpr = (IConditionExpr)ExtUtil.read(in, new ExtWrapNullable(new ExtWrapTagged()), pf);
copyRef = (TreeReference)ExtUtil.read(in, new ExtWrapNullable(TreeReference.class), pf);
labelIsItext = ExtUtil.readBool(in);
copyMode = ExtUtil.readBool(in);
sortRef = (TreeReference)ExtUtil.read(in, new ExtWrapNullable(TreeReference.class), pf);
sortExpr = (IConditionExpr)ExtUtil.read(in, new ExtWrapNullable(new ExtWrapTagged()), pf);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.write(out, nodesetRef);
ExtUtil.write(out, new ExtWrapTagged(nodesetExpr));
ExtUtil.write(out, contextRef);
ExtUtil.write(out, labelRef);
ExtUtil.write(out, new ExtWrapTagged(labelExpr));
ExtUtil.write(out, new ExtWrapNullable(valueRef));
ExtUtil.write(out, new ExtWrapNullable(valueExpr == null ? null : new ExtWrapTagged(valueExpr)));
ExtUtil.write(out, new ExtWrapNullable(copyRef));
ExtUtil.writeBool(out, labelIsItext);
ExtUtil.writeBool(out, copyMode);
ExtUtil.write(out, new ExtWrapNullable(sortRef));
ExtUtil.write(out, new ExtWrapNullable(sortExpr == null ? null : new ExtWrapTagged(sortExpr)));
}
} |
package org.jboss.netty.handler.ssl;
import static org.jboss.netty.channel.Channels.*;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.util.internal.ImmediateExecutor;
public class SslHandler extends FrameDecoder {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(SslHandler.class);
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
private static SslBufferPool defaultBufferPool;
/**
* Returns the default {@link SslBufferPool} used when no pool is
* specified in the constructor.
*/
public static synchronized SslBufferPool getDefaultBufferPool() {
if (defaultBufferPool == null) {
defaultBufferPool = new SslBufferPool();
}
return defaultBufferPool;
}
private final SSLEngine engine;
private final SslBufferPool bufferPool;
private final Executor delegatedTaskExecutor;
private final boolean startTls;
final Object handshakeLock = new Object();
private boolean initialHandshake;
private boolean handshaking;
private volatile boolean handshaken;
private volatile ChannelFuture handshakeFuture;
private final AtomicBoolean sentFirstMessage = new AtomicBoolean();
private final AtomicBoolean sentCloseNotify = new AtomicBoolean();
final Queue<ChannelFuture> closeFutures = new ConcurrentLinkedQueue<ChannelFuture>();
private final Queue<PendingWrite> pendingUnencryptedWrites = new LinkedList<PendingWrite>();
private final Queue<MessageEvent> pendingEncryptedWrites = new LinkedList<MessageEvent>();
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
*/
public SslHandler(SSLEngine engine) {
this(engine, getDefaultBufferPool(), ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param bufferPool the {@link SslBufferPool} where this handler will
* acquire the buffers required by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool) {
this(engine, bufferPool, ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, boolean startTls) {
this(engine, getDefaultBufferPool(), startTls);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param bufferPool the {@link SslBufferPool} where this handler will
* acquire the buffers required by the {@link SSLEngine}
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls) {
this(engine, bufferPool, startTls, ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) {
this(engine, getDefaultBufferPool(), delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param bufferPool
* the {@link SslBufferPool} where this handler will acquire
* the buffers required by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, Executor delegatedTaskExecutor) {
this(engine, bufferPool, false, delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param startTls
* {@code true} if the first write request shouldn't be encrypted
* by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) {
this(engine, getDefaultBufferPool(), startTls, delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param bufferPool
* the {@link SslBufferPool} where this handler will acquire
* the buffers required by the {@link SSLEngine}
* @param startTls
* {@code true} if the first write request shouldn't be encrypted
* by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) {
if (engine == null) {
throw new NullPointerException("engine");
}
if (bufferPool == null) {
throw new NullPointerException("bufferPool");
}
if (delegatedTaskExecutor == null) {
throw new NullPointerException("delegatedTaskExecutor");
}
this.engine = engine;
this.bufferPool = bufferPool;
this.delegatedTaskExecutor = delegatedTaskExecutor;
this.startTls = startTls;
}
/**
* Returns the {@link SSLEngine} which is used by this handler.
*/
public SSLEngine getEngine() {
return engine;
}
/**
* Starts an SSL / TLS handshake for the specified channel.
*
* @return a {@link ChannelFuture} which is notified when the handshake
* succeeds or fails.
*/
public ChannelFuture handshake(Channel channel) throws SSLException {
ChannelFuture handshakeFuture;
synchronized (handshakeLock) {
if (handshaking) {
return this.handshakeFuture;
} else {
engine.beginHandshake();
runDelegatedTasks();
handshakeFuture = this.handshakeFuture = newHandshakeFuture(channel);
handshaking = true;
}
}
wrapNonAppData(context(channel), channel);
return handshakeFuture;
}
/**
* Sends an SSL {@code close_notify} message to the specified channel and
* destroys the underlying {@link SSLEngine}.
*/
public ChannelFuture close(Channel channel) throws SSLException {
ChannelHandlerContext ctx = context(channel);
engine.closeOutbound();
return wrapNonAppData(ctx, channel);
}
private ChannelHandlerContext context(Channel channel) {
return channel.getPipeline().getContext(getClass());
}
@Override
public void handleDownstream(
final ChannelHandlerContext context, final ChannelEvent evt) throws Exception {
if (evt instanceof ChannelStateEvent) {
ChannelStateEvent e = (ChannelStateEvent) evt;
switch (e.getState()) {
case OPEN:
case CONNECTED:
case BOUND:
if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) {
closeOutboundAndChannel(context, e);
return;
}
}
}
if (!(evt instanceof MessageEvent)) {
context.sendDownstream(evt);
return;
}
MessageEvent e = (MessageEvent) evt;
if (!(e.getMessage() instanceof ChannelBuffer)) {
context.sendDownstream(evt);
return;
}
// Do not encrypt the first write request if this handler is
// created with startTLS flag turned on.
if (startTls && sentFirstMessage.compareAndSet(false, true)) {
context.sendDownstream(evt);
return;
}
// Otherwise, all messages are encrypted.
ChannelBuffer msg = (ChannelBuffer) e.getMessage();
PendingWrite pendingWrite =
new PendingWrite(evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes()));
synchronized (pendingUnencryptedWrites) {
boolean offered = pendingUnencryptedWrites.offer(pendingWrite);
assert offered;
}
wrap(context, evt.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// Make sure the handshake future is notified when a connection has
// been closed during handshake.
synchronized (handshakeLock) {
if (handshaking) {
handshakeFuture.setFailure(new ClosedChannelException());
}
}
try {
super.channelDisconnected(ctx, e);
} finally {
unwrap(ctx, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
engine.closeOutbound();
if (!sentCloseNotify.get() && handshaken) {
try {
engine.closeInbound();
} catch (SSLException ex) {
logger.debug("Failed to clean up SSLEngine.", ex);
}
}
}
}
@Override
protected Object decode(
ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readableBytes() < 2) {
return null;
}
int packetLength = buffer.getShort(buffer.readerIndex()) & 0xFFFF;
if ((packetLength & 0x8000) != 0) {
// Detected a SSLv2 packet
packetLength &= 0x7FFF;
packetLength += 2;
} else if (buffer.readableBytes() < 5) {
return null;
} else {
// Detected a SSLv3 / TLSv1 packet
packetLength = (buffer.getShort(buffer.readerIndex() + 3) & 0xFFFF) + 5;
}
if (buffer.readableBytes() < packetLength) {
return null;
}
ChannelBuffer frame;
try {
frame = unwrap(ctx, channel, buffer, buffer.readerIndex(), packetLength);
} finally {
buffer.skipBytes(packetLength);
}
if (frame == null && engine.isInboundDone()) {
synchronized (closeFutures) {
for (;;) {
ChannelFuture future = closeFutures.poll();
if (future == null) {
break;
}
Channels.close(ctx, future);
}
}
}
return frame;
}
private ChannelFuture wrap(ChannelHandlerContext context, Channel channel)
throws SSLException {
ChannelFuture future = null;
ChannelBuffer msg;
ByteBuffer outNetBuf = bufferPool.acquire();
boolean success = true;
boolean offered = false;
boolean needsUnwrap = false;
try {
loop:
for (;;) {
// Acquire a lock to make sure unencrypted data is polled
// in order and their encrypted counterpart is offered in
// order.
synchronized (pendingUnencryptedWrites) {
PendingWrite pendingWrite = pendingUnencryptedWrites.peek();
if (pendingWrite == null) {
break;
}
ByteBuffer outAppBuf = pendingWrite.outAppBuf;
SSLEngineResult result;
try {
synchronized (handshakeLock) {
result = engine.wrap(outAppBuf, outNetBuf);
}
} finally {
if (!outAppBuf.hasRemaining()) {
pendingUnencryptedWrites.remove();
}
}
if (result.bytesProduced() > 0) {
outNetBuf.flip();
msg = ChannelBuffers.buffer(outNetBuf.remaining());
msg.writeBytes(outNetBuf.array(), 0, msg.capacity());
outNetBuf.clear();
if (pendingWrite.outAppBuf.hasRemaining()) {
// pendingWrite's future shouldn't be notified if
// only partial data is written.
future = succeededFuture(channel);
} else {
future = pendingWrite.future;
}
MessageEvent encryptedWrite = new DownstreamMessageEvent(
channel, future, msg, channel.getRemoteAddress());
if (Thread.holdsLock(pendingEncryptedWrites)) {
offered = pendingEncryptedWrites.offer(encryptedWrite);
} else {
synchronized (pendingEncryptedWrites) {
offered = pendingEncryptedWrites.offer(encryptedWrite);
}
}
assert offered;
} else {
HandshakeStatus handshakeStatus = result.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_WRAP:
if (outAppBuf.hasRemaining()) {
break;
} else {
break loop;
}
case NEED_UNWRAP:
needsUnwrap = true;
break loop;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
case NOT_HANDSHAKING:
if (handshakeStatus == HandshakeStatus.FINISHED) {
setHandshakeSuccess(channel);
}
if (result.getStatus() == Status.CLOSED) {
success = false;
}
break loop;
default:
throw new IllegalStateException(
"Unknown handshake status: " +
result.getHandshakeStatus());
}
}
}
}
} catch (SSLException e) {
success = false;
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outNetBuf);
if (offered) {
flushPendingEncryptedWrites(context);
}
if (!success) {
// Mark all remaining pending writes as failure if anything
// wrong happened before the write requests are wrapped.
// Please note that we do not call setFailure while a lock is
// acquired, to avoid a potential dead lock.
for (;;) {
PendingWrite pendingWrite;
synchronized (pendingUnencryptedWrites) {
pendingWrite = pendingUnencryptedWrites.poll();
if (pendingWrite == null) {
break;
}
}
pendingWrite.future.setFailure(
new IllegalStateException("SSLEngine already closed"));
}
}
}
if (needsUnwrap) {
unwrap(context, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0);
}
if (future == null) {
future = succeededFuture(channel);
}
return future;
}
private void flushPendingEncryptedWrites(ChannelHandlerContext ctx) {
// Avoid possible dead lock and data integrity issue
// which is caused by cross communication between more than one channel
// in the same VM.
if (Thread.holdsLock(pendingEncryptedWrites)) {
return;
}
synchronized (pendingEncryptedWrites) {
if (pendingEncryptedWrites.isEmpty()) {
return;
}
}
synchronized (pendingEncryptedWrites) {
MessageEvent e;
while ((e = pendingEncryptedWrites.poll()) != null) {
ctx.sendDownstream(e);
}
}
}
private ChannelFuture wrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException {
ChannelFuture future = null;
ByteBuffer outNetBuf = bufferPool.acquire();
SSLEngineResult result;
try {
for (;;) {
synchronized (handshakeLock) {
result = engine.wrap(EMPTY_BUFFER, outNetBuf);
}
if (result.bytesProduced() > 0) {
outNetBuf.flip();
ChannelBuffer msg = ChannelBuffers.buffer(outNetBuf.remaining());
msg.writeBytes(outNetBuf.array(), 0, msg.capacity());
outNetBuf.clear();
if (channel.isConnected()) {
future = future(channel);
write(ctx, future, msg);
}
}
switch (result.getHandshakeStatus()) {
case FINISHED:
setHandshakeSuccess(channel);
runDelegatedTasks();
break;
case NEED_TASK:
runDelegatedTasks();
break;
case NEED_UNWRAP:
if (!Thread.holdsLock(handshakeLock)) {
// unwrap shouldn't be called when this method was
// called by unwrap - unwrap will keep running after
// this method returns.
unwrap(ctx, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0);
}
break;
case NOT_HANDSHAKING:
case NEED_WRAP:
break;
default:
throw new IllegalStateException(
"Unexpected handshake status: " +
result.getHandshakeStatus());
}
if (result.bytesProduced() == 0) {
break;
}
}
} catch (SSLException e) {
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outNetBuf);
}
if (future == null) {
future = succeededFuture(channel);
}
return future;
}
private ChannelBuffer unwrap(
ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, int offset, int length) throws SSLException {
ByteBuffer inNetBuf = buffer.toByteBuffer(offset, length);
ByteBuffer outAppBuf = bufferPool.acquire();
try {
boolean needsWrap = false;
loop:
for (;;) {
SSLEngineResult result;
synchronized (handshakeLock) {
if (initialHandshake && !engine.getUseClientMode() &&
!engine.isInboundDone() && !engine.isOutboundDone()) {
handshake(channel);
initialHandshake = false;
}
try {
result = engine.unwrap(inNetBuf, outAppBuf);
} catch (SSLException e) {
throw e;
}
switch (result.getHandshakeStatus()) {
case NEED_UNWRAP:
if (inNetBuf.hasRemaining()) {
break;
} else {
break loop;
}
case NEED_WRAP:
wrapNonAppData(ctx, channel);
break;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess(channel);
needsWrap = true;
break loop;
case NOT_HANDSHAKING:
needsWrap = true;
break loop;
default:
throw new IllegalStateException(
"Unknown handshake status: " +
result.getHandshakeStatus());
}
}
}
if (needsWrap) {
wrap(ctx, channel);
}
outAppBuf.flip();
if (outAppBuf.hasRemaining()) {
ChannelBuffer frame = ChannelBuffers.buffer(outAppBuf.remaining());
frame.writeBytes(outAppBuf.array(), 0, frame.capacity());
return frame;
} else {
return null;
}
} catch (SSLException e) {
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outAppBuf);
}
}
private void runDelegatedTasks() {
for (;;) {
final Runnable task;
synchronized (handshakeLock) {
task = engine.getDelegatedTask();
}
if (task == null) {
break;
}
delegatedTaskExecutor.execute(new Runnable() {
public void run() {
synchronized (handshakeLock) {
task.run();
}
}
});
}
}
private void setHandshakeSuccess(Channel channel) {
synchronized (handshakeLock) {
handshaking = false;
handshaken = true;
if (handshakeFuture == null) {
handshakeFuture = newHandshakeFuture(channel);
}
}
handshakeFuture.setSuccess();
}
private void setHandshakeFailure(Channel channel, SSLException cause) {
synchronized (handshakeLock) {
if (!handshaking) {
return;
}
handshaking = false;
handshaken = false;
if (handshakeFuture == null) {
handshakeFuture = newHandshakeFuture(channel);
}
}
handshakeFuture.setFailure(cause);
}
private void closeOutboundAndChannel(
final ChannelHandlerContext context, final ChannelStateEvent e) throws SSLException {
unwrap(context, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
if (!engine.isInboundDone()) {
if (sentCloseNotify.compareAndSet(false, true)) {
engine.closeOutbound();
synchronized (closeFutures) {
ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel());
closeNotifyFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception {
boolean offered = closeFutures.offer(e.getFuture());
assert offered;
}
});
}
return;
}
}
context.sendDownstream(e);
}
private static ChannelFuture newHandshakeFuture(Channel channel) {
ChannelFuture future = future(channel);
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future)
throws Exception {
if (!future.isSuccess()) {
fireExceptionCaught(future.getChannel(), future.getCause());
}
}
});
return future;
}
private static final class PendingWrite {
final ChannelFuture future;
final ByteBuffer outAppBuf;
PendingWrite(ChannelFuture future, ByteBuffer outAppBuf) {
this.future = future;
this.outAppBuf = outAppBuf;
}
}
} |
package com.intellij.psi;
import com.intellij.lang.*;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.SharedPsiElementImplUtil;
import com.intellij.psi.impl.source.LightPsiFileImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.jsp.CompositeLanguageParsingUtil;
import com.intellij.psi.impl.source.jsp.JspImplUtil;
import com.intellij.psi.impl.source.jsp.jspJava.JspWhileStatement;
import com.intellij.psi.impl.source.jsp.jspJava.OuterLanguageElement;
import com.intellij.psi.impl.source.parsing.ChameleonTransforming;
import com.intellij.psi.impl.source.parsing.ParseUtil;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlText;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ReflectionCache;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class CompositeLanguageFileViewProvider extends SingleRootFileViewProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.CompositeLanguageFileViewProvider");
public static final Key<Object> UPDATE_IN_PROGRESS = new Key<Object>("UPDATE_IN_PROGRESS");
public static final Key<Object> DO_NOT_UPDATE_AUX_TREES = new Key<Object>("DO_NOT_UPDATE_AUX_TREES");
public static final Key<Integer> OUTER_LANGUAGE_MERGE_POINT = new Key<Integer>("OUTER_LANGUAGE_MERGE_POINT");
private final Map<Language, PsiFile> myRoots = new HashMap<Language, PsiFile>();
private Set<Language> myRelevantLanguages;
public Set<Language> getRelevantLanguages() {
if (myRelevantLanguages != null) return myRelevantLanguages;
Set<Language> relevantLanguages = new HashSet<Language>();
final Language baseLanguage = getBaseLanguage();
relevantLanguages.add(baseLanguage);
relevantLanguages.addAll(myRoots.keySet());
return myRelevantLanguages = new LinkedHashSet<Language>(relevantLanguages);
}
public void contentsSynchronized() {
super.contentsSynchronized();
myRelevantLanguages = null;
}
private final Map<PsiFile, Set<OuterLanguageElement>> myOuterLanguageElements =
new HashMap<PsiFile, Set<OuterLanguageElement>>();
private Set<PsiFile> myRootsInUpdate = new HashSet<PsiFile>(4);
public CompositeLanguageFileViewProvider(final PsiManager manager, final VirtualFile file) {
super(manager, file);
}
public CompositeLanguageFileViewProvider(final PsiManager manager, final VirtualFile virtualFile, final boolean physical) {
super(manager, virtualFile, physical);
}
public CompositeLanguageFileViewProvider clone() {
final CompositeLanguageFileViewProvider viewProvider = cloneInner();
final PsiFileImpl psiFile = (PsiFileImpl)viewProvider.getPsi(getBaseLanguage());
// copying main tree
final FileElement treeClone = (FileElement)psiFile.calcTreeElement().clone(); // base language tree clone
psiFile.setTreeElementPointer(treeClone); // should not use setTreeElement here because cloned file still have VirtualFile (SCR17963)
treeClone.setPsiElement(psiFile);
final XmlText[] xmlTexts = JspImplUtil.gatherTexts((XmlFile)psiFile);
for (Map.Entry<Language, PsiFile> entry : myRoots.entrySet()) {
final PsiFile root = entry.getValue();
if (root != psiFile) {
if (root instanceof PsiFileImpl) {
final PsiFileImpl copy = (PsiFileImpl)viewProvider.getPsi(entry.getKey());
if (copy == null) continue; // Unreleivant language due to partial parsing.
JspImplUtil.copyRoot((PsiFileImpl)root, xmlTexts, copy);
}
else {
if (root instanceof LightPsiFileImpl) {
final LightPsiFileImpl lightFile = (LightPsiFileImpl)root;
final LightPsiFileImpl clone = lightFile.copyLight(viewProvider);
clone.setOriginalFile(root);
viewProvider.myRoots.put(entry.getKey(), clone);
}
}
}
}
return viewProvider;
}
protected CompositeLanguageFileViewProvider cloneInner() {
return new CompositeLanguageFileViewProvider(getManager(), new LightVirtualFile(getVirtualFile().getName(),
getVirtualFile().getFileType(), getContents(),
getModificationStamp()), false);
}
@Nullable
protected PsiFile getPsiInner(Language target) {
PsiFile file = super.getPsiInner(target);
if (file != null) return file;
file = myRoots.get(target);
if (file == null) {
synchronized (PsiLock.LOCK) {
file = createFile(target);
myRoots.put(target, file);
}
}
return file;
}
public synchronized PsiFile getCachedPsi(Language target) {
if (target == getBaseLanguage()) return super.getCachedPsi(target);
return myRoots.get(target);
}
public void checkAllTreesEqual() {
final String psiText = getPsi(getBaseLanguage()).getText();
for (Map.Entry<Language, PsiFile> entry : myRoots.entrySet()) {
final PsiFile psiFile = entry.getValue();
LOG.assertTrue(psiFile.getTextLength() == psiText.length(), entry.getKey().getID() + " tree text differs from base!");
LOG.assertTrue(psiFile.getText().equals(psiText), entry.getKey().getID() + " tree text differs from base!");
}
}
public void registerOuterLanguageElement(OuterLanguageElement element, PsiFile root) {
if (myRoots.get(root.getLanguage()) != root) {
return; // Not mine. Probably comes from air elements parsing.
}
Set<OuterLanguageElement> outerLanguageElements = myOuterLanguageElements.get(root);
if (outerLanguageElements == null) {
outerLanguageElements = new TreeSet<OuterLanguageElement>(new Comparator<OuterLanguageElement>() {
public int compare(final OuterLanguageElement languageElement, final OuterLanguageElement languageElement2) {
if (languageElement.equals(languageElement2)) return 0;
final int result = languageElement.getTextRange().getStartOffset() - languageElement2.getTextRange().getStartOffset();
if (result != 0) return result;
return languageElement.getTextRange().getEndOffset() - languageElement2.getTextRange().getEndOffset();
}
});
myOuterLanguageElements.put(root, outerLanguageElements);
}
outerLanguageElements.add(element);
}
public void reparseRoots(final Set<Language> rootsToReparse) {
for (final Language lang : rootsToReparse) {
final PsiFile cachedRoot = myRoots.get(lang);
if (cachedRoot != null) {
if (myRootsInUpdate.contains(cachedRoot)) continue;
try {
myRootsInUpdate.add(cachedRoot);
reparseRoot(lang, cachedRoot);
}
finally {
myRootsInUpdate.remove(cachedRoot);
}
}
}
}
public FileElement[] getKnownTreeRoots() {
final List<FileElement> knownRoots = new ArrayList<FileElement>();
knownRoots.addAll(Arrays.asList(super.getKnownTreeRoots()));
for (PsiFile psiFile : myRoots.values()) {
if (psiFile == null || !(psiFile instanceof PsiFileImpl)) continue;
final FileElement fileElement = ((PsiFileImpl)psiFile).getTreeElement();
if (fileElement == null) continue;
knownRoots.add(fileElement);
}
return knownRoots.toArray(new FileElement[knownRoots.size()]);
}
protected void reparseRoot(final Language lang, final PsiFile cachedRoot) {
LOG.debug("JspxFile: reparseRoot " + getVirtualFile().getName());
final ASTNode oldFileTree = cachedRoot.getNode();
if (oldFileTree == null || oldFileTree.getFirstChildNode()instanceof ChameleonElement) {
if (cachedRoot instanceof PsiFileImpl) ((PsiFileImpl)cachedRoot).setTreeElementPointer(null);
cachedRoot.subtreeChanged();
return;
}
final PsiFile fileForNewText = createFile(lang);
assert fileForNewText != null;
final ASTNode newFileTree = fileForNewText.getNode();
if (LOG.isDebugEnabled()) {
LOG.debug("Old Tree:\n" + DebugUtil.treeToString(oldFileTree, false, true));
LOG.debug("New Tree:\n" + DebugUtil.treeToString(newFileTree, false, true));
}
ChameleonTransforming.transformChildren(newFileTree, true);
ChameleonTransforming.transformChildren(oldFileTree, true);
CompositeLanguageParsingUtil.mergeTreeElements((TreeElement)newFileTree.getFirstChildNode(),
(TreeElement)oldFileTree.getFirstChildNode(), (CompositeElement)oldFileTree);
checkConsistensy(cachedRoot);
}
public void updateOuterLanguageElements(final Set<Language> languagesToSkip) {
for (Map.Entry<Language, PsiFile> entry : myRoots.entrySet()) {
final PsiFile psiFile = entry.getValue();
final Language updatedLanguage = entry.getKey();
if (languagesToSkip.contains(updatedLanguage)) continue;
Set<OuterLanguageElement> outerSet = myOuterLanguageElements.get(psiFile);
if (outerSet == null) // not parsed yet
{
continue;
}
try {
myRootsInUpdate.add(psiFile);
Set<OuterLanguageElement> languageElements = outerSet;
if (languageElements == null) {
languageElements = recalcOuterElements(psiFile);
}
for (final OuterLanguageElement outerElement : languageElements) {
final FileElement file = TreeUtil.getFileElement(outerElement);
if (file == null) {
languageElements.clear();
languageElements = recalcOuterElements(psiFile);
break;
}
}
Iterator<OuterLanguageElement> i = languageElements.iterator();
while (i.hasNext()) {
final OuterLanguageElement outerElement = i.next();
final FileElement file = TreeUtil.getFileElement(outerElement);
if (file == null || file.getPsi() != psiFile) {
i.remove();
}
}
XmlText prevText = null;
int outerCount = 0;
i = languageElements.iterator();
while (i.hasNext()) {
final OuterLanguageElement outerElement = i.next();
XmlText nextText = outerElement.getFollowingText();
final int start =
prevText != null ? prevText.getTextRange().getEndOffset() : outerCount != 0 ? outerElement.getTextRange().getStartOffset() : 0;
if (nextText != null && !nextText.isValid()) {
final PsiElement nextSibiling = outerElement.getNextSibling();
assert nextSibiling == null || nextSibiling instanceof OuterLanguageElement;
nextText = nextSibiling != null ? ((OuterLanguageElement)nextSibiling).getFollowingText() : null;
final int end = nextText != null ? nextText.getTextRange().getStartOffset() : getContents().length();
assert start <= end;
final TextRange textRange = new TextRange(start, end);
outerElement.setRange(textRange);
if (nextSibiling != null) {
outerElement.putUserData(OUTER_LANGUAGE_MERGE_POINT, end - nextSibiling.getTextRange().getLength() - start);
TreeUtil.remove(((OuterLanguageElement)nextSibiling));
final OuterLanguageElement next = i.next();
assert next == nextSibiling;
i.remove();
}
}
else {
int end;
if (nextText != null) {
end = nextText.getTextRange().getStartOffset();
end += nextText.displayToPhysical(0);
}
else {
end = i.hasNext() ? outerElement.getTextRange().getEndOffset() : getContents().length();
}
assert start <= end;
final TextRange textRange = new TextRange(start, end);
if (!textRange.equals(outerElement.getTextRange())) {
outerElement.setRange(textRange);
}
}
prevText = nextText;
++outerCount;
}
}
finally {
myRootsInUpdate.remove(psiFile);
}
checkConsistensy(psiFile);
}
}
private Set<OuterLanguageElement> recalcOuterElements(final PsiFile psiFile) {
psiFile.accept(new PsiElementVisitor() {
public void visitReferenceExpression(PsiReferenceExpression expression) {
}
public void visitElement(PsiElement element) {
if (element instanceof OuterLanguageElement) {
final OuterLanguageElement outerLanguageElement = ((OuterLanguageElement)element);
final FileElement file = TreeUtil.getFileElement(outerLanguageElement);
if (file.getPsi() == psiFile) {
registerOuterLanguageElement(outerLanguageElement, psiFile);
}
}
else {
element.acceptChildren(this);
}
}
});
return myOuterLanguageElements.get(psiFile);
}
@Nullable
public PsiElement findElementAt(int offset, Class<? extends Language> lang) {
final PsiFile mainRoot = getPsi(getBaseLanguage());
PsiElement ret = null;
for (final Language language : getRelevantLanguages()) {
if (!ReflectionCache.isAssignable(lang, language.getClass())) continue;
if (lang.equals(Language.class) && !getPrimaryLanguages().contains(language)) continue;
final PsiFile psiRoot = getPsi(language);
final PsiElement psiElement;
psiElement = findElementAt(psiRoot, offset);
if (psiElement == null || psiElement instanceof OuterLanguageElement) continue;
if (ret == null || psiRoot != mainRoot) {
ret = psiElement;
}
}
return ret;
}
@Nullable
public PsiElement findElementAt(int offset) {
return findElementAt(offset, Language.class);
}
@Nullable
public PsiReference findReferenceAt(int offset) {
TextRange minRange = new TextRange(0, getContents().length());
PsiReference ret = null;
for (final Language language : getPrimaryLanguages()) {
final PsiElement psiRoot = getPsi(language);
final PsiReference reference = SharedPsiElementImplUtil.findReferenceAt(psiRoot, offset);
if (reference == null) continue;
final TextRange textRange = reference.getRangeInElement().shiftRight(reference.getElement().getTextRange().getStartOffset());
if (minRange.contains(textRange)) {
minRange = textRange;
ret = reference;
}
}
return ret;
}
protected void checkConsistensy(final PsiFile oldFile) {
if (oldFile.getNode().getTextLength() != getContents().length() ||
!oldFile.getNode().getText().equals(getContents().toString())) {
String message = "Check consistency failed for: " + oldFile;
message += "\n oldFile.getNode().getTextLength() = " + oldFile.getNode().getTextLength();
message += "\n getContents().length() = " + getContents().length();
if (ApplicationManagerEx.getApplicationEx().isInternal()) {
message += "\n oldFileText:\n" + oldFile.getNode().getText();
message += "\n contentsText:\n" + getContents().toString();
message += "\n jspText:\n" + getPsi(getBaseLanguage()).getNode().getText();
}
LOG.assertTrue(false, message);
}
}
public LanguageExtension[] getLanguageExtensions() {
return new LanguageExtension[0];
}
@Nullable
protected PsiFile createFile(Language lang) {
final PsiFile psiFile = super.createFile(lang);
if (psiFile != null) return psiFile;
if (getRelevantLanguages().contains(lang)) {
final ParserDefinition parserDefinition = lang.getParserDefinition();
assert parserDefinition != null;
return parserDefinition.createFile(this);
}
return null;
}
public void rootChanged(PsiFile psiFile) {
if (myRootsInUpdate.contains(psiFile)) return;
if (psiFile.getLanguage() == getBaseLanguage()) {
super.rootChanged(psiFile);
// rest of sync mechanism is now handled by JspxAspect
}
else if (!myRootsInUpdate.contains(getPsi(getBaseLanguage()))) doHolderToXmlChanges(psiFile);
}
private void doHolderToXmlChanges(final PsiFile psiFile) {
putUserData(UPDATE_IN_PROGRESS, Boolean.TRUE);
boolean buffersDiffer = false;
final Language language = getBaseLanguage();
final List<Pair<OuterLanguageElement, Pair<StringBuffer, StringBuffer>>> javaFragments =
new ArrayList<Pair<OuterLanguageElement, Pair<StringBuffer, StringBuffer>>>();
try {
StringBuffer currentBuffer = null;
StringBuffer currentDecodedBuffer = null;
LeafElement element = TreeUtil.findFirstLeaf(psiFile.getNode());
if (element == null) return;
do {
if (element instanceof OuterLanguageElement) {
currentDecodedBuffer = new StringBuffer();
currentBuffer = new StringBuffer();
javaFragments.add(Pair.create((OuterLanguageElement)element, Pair.create(currentBuffer, currentDecodedBuffer)));
}
else {
String text = element.getText();
if (element instanceof PsiWhiteSpace && text.endsWith("]]>")) {
text = text.substring(0, text.length() - "]]>".length());
}
final String decoded = language != StdLanguages.JSP ? XmlUtil.decode(text) : text;
assert currentDecodedBuffer != null;
currentDecodedBuffer.append(decoded);
currentBuffer.append(text);
}
if (!buffersDiffer && !Comparing.equal(currentBuffer, currentDecodedBuffer)) {
buffersDiffer = true;
}
}
while ((element = ParseUtil.nextLeaf(element, null)) != null);
if (!buffersDiffer) {
myRootsInUpdate.add(psiFile);
}
for (final Pair<OuterLanguageElement, Pair<StringBuffer, StringBuffer>> pair : javaFragments) {
final XmlText followingText = pair.getFirst().getFollowingText();
final String newText = pair.getSecond().getSecond().toString();
if (followingText != null && followingText.isValid() && !followingText.getValue().equals(newText)) {
followingText.setValue(newText);
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
finally {
updateOuterLanguageElementsIn(psiFile);
if (!buffersDiffer) {
myRootsInUpdate.remove(psiFile);
}
putUserData(UPDATE_IN_PROGRESS, null);
}
}
private void updateOuterLanguageElementsIn(final PsiFile psiFile) {
final HashSet<Language> set = new HashSet<Language>(getRelevantLanguages());
set.remove(psiFile.getLanguage());
updateOuterLanguageElements(set);
}
public void normalizeOuterLanguageElements(PsiFile root) {
if (!myRootsInUpdate.contains(root)) {
try {
myRootsInUpdate.add(root);
normalizeOuterLanguageElementsInner(root);
}
finally {
myRootsInUpdate.remove(root);
}
}
else {
normalizeOuterLanguageElementsInner(root);
}
}
private void normalizeOuterLanguageElementsInner(final PsiFile lang) {
final Set<OuterLanguageElement> outerElements = myOuterLanguageElements.get(lang);
if (outerElements == null) return;
final Iterator<OuterLanguageElement> iterator = outerElements.iterator();
final List<OuterLanguageElement> toRemove = new ArrayList<OuterLanguageElement>();
OuterLanguageElement prev = null;
while (iterator.hasNext()) {
final OuterLanguageElement outer = iterator.next();
if (outer == null) {
iterator.remove();
continue;
}
if (prev != null && prev.getFollowingText() == null && outer.getTextRange().getStartOffset() == prev.getTextRange().getEndOffset()) {
final CompositeElement prevParent = prev.getTreeParent();
final JspWhileStatement outerWhile = PsiTreeUtil.getParentOfType(outer, JspWhileStatement.class);
if (prevParent != null && prevParent.getElementType() == JspElementType.JSP_TEMPLATE_EXPRESSION || outerWhile != null) {
final JspWhileStatement prevWhile = PsiTreeUtil.getParentOfType(prev, JspWhileStatement.class);
if (prevWhile == null || prevWhile == outerWhile || prevWhile.getStartOffset() != prev.getStartOffset()) {
toRemove.add(prev);
prev = mergeOuterLanguageElements(outer, prev);
}
else {
prev = outer;
}
}
else {
toRemove.add(outer);
prev = mergeOuterLanguageElements(prev, outer);
}
}
else {
prev = outer;
}
}
outerElements.removeAll(toRemove);
}
private static OuterLanguageElement mergeOuterLanguageElements(final OuterLanguageElement prev, final OuterLanguageElement outer) {
final TextRange textRange = new TextRange(Math.min(prev.getTextRange().getStartOffset(), outer.getTextRange().getStartOffset()),
Math.max(prev.getTextRange().getEndOffset(), outer.getTextRange().getEndOffset()));
prev.setRange(textRange);
if (prev.getFollowingText() == null) prev.setFollowingText(outer.getFollowingText());
final CompositeElement parent = prev.getTreeParent();
if (parent != null) parent.subtreeChanged();
final CompositeElement removedParent = outer.getTreeParent();
TreeUtil.remove(outer);
if (removedParent != null) removedParent.subtreeChanged();
return prev;
}
public Set<PsiFile> getRootsInUpdate() {
return myRootsInUpdate;
}
} |
package org.jtrfp.trcl;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.VisibleEverywhere;
public class GridCubeProximitySorter extends AbstractSubmitter<List<PositionedRenderable>> {
private double [] center = new double[]{0,0,0};
public GridCubeProximitySorter setCenter(double [] center){
this.center=center;
return this;
}
private final TreeSet<List<PositionedRenderable>> sortedSet =
new TreeSet<List<PositionedRenderable>>(new Comparator<List<PositionedRenderable>>(){
@Override
public int compare(List<PositionedRenderable> _left, List<PositionedRenderable> _right) {
synchronized(_left){
synchronized(_right){
if(_left.isEmpty()&&_right.isEmpty())
return 0;
if(_left.isEmpty())
return -1;
if(_right.isEmpty())
return 1;
double [] left=_left.get(0).getPosition();
double [] right=_right.get(0).getPosition();
if((left==right)&&left==null)return Integer.MAX_VALUE;
if(left==null)return Integer.MIN_VALUE;
if(right==null)return Integer.MAX_VALUE;
if(_left.get(0) instanceof VisibleEverywhere)
left=new double[]{center[0],center[1],center[2]+left[2]*1114112};
if(_right.get(0) instanceof VisibleEverywhere)
right=new double[]{center[0],center[1],center[2]+right[2]*1114112};
final int diff = (int)(Vect3D.taxicabDistance(center,left)-Vect3D.taxicabDistance(center,right));
return diff!=0?diff:_left.hashCode()-_right.hashCode();
}}//end sync()
}//end compare()
@Override
public boolean equals(Object o){
return o.getClass()==this.getClass();
}
});
@Override
public void submit(List<PositionedRenderable> item) {
if(item==null)return;
if(item.isEmpty())return;
synchronized(sortedSet){sortedSet.add(item);}
}
public GridCubeProximitySorter reset(){
synchronized(sortedSet){sortedSet.clear();}
return this;
}
public GridCubeProximitySorter dumpPositionedRenderables(Submitter<PositionedRenderable> sub){
synchronized(sortedSet){
for(List<PositionedRenderable> gc:sortedSet){
sub.submit(gc);
}//end for(...)
}//end sync(sortedSet)
return this;
}//end dumpPositionedRenderables(...)
}//end GridCubeProximitySorter |
package org.jtrfp.trcl.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import org.jtrfp.jfdt.Parser;
import org.jtrfp.jtrfp.FileLoadException;
import org.jtrfp.jtrfp.pod.PodFile;
import org.jtrfp.trcl.coll.CollectionActionDispatcher;
import org.jtrfp.trcl.conf.TRConfigurationFactory.TRConfiguration;
import org.jtrfp.trcl.core.Feature;
import org.jtrfp.trcl.core.FeatureFactory;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.core.GraphStabilizationListener;
import org.jtrfp.trcl.core.PODRegistry;
import org.jtrfp.trcl.core.TRConfigRootFactory.TRConfigRoot;
import org.jtrfp.trcl.core.TRFactory.TR;
import org.jtrfp.trcl.file.VOXFile;
import org.jtrfp.trcl.snd.SoundSystem;
import org.springframework.stereotype.Component;
@Component
public class ConfigWindowFactory implements FeatureFactory<TR>{
/*
public static void main(String [] args){
new ConfigWindow().setVisible(true);
}//end main()
*/
public class ConfigWindow extends JFrame implements GraphStabilizationListener, Feature<TR>{
//private TRConfiguration config;
//private JComboBox audioBufferSizeCB;
//private JSlider modStereoWidthSlider;
private JList podList,missionList;
private DefaultListModel podLM=new DefaultListModel(), missionLM=new DefaultListModel();
private boolean needRestart=false;
private final JFileChooser fileChooser = new JFileChooser();
private final Collection<ConfigurationTab> tabs;
//private final TRConfigRoot cMgr;
private final JTabbedPane tabbedPane;
private PODRegistry podRegistry;
private PodCollectionListener podCollectionListener = new PodCollectionListener();
private TR tr;
private TRConfigRoot trConfigRoot;
private TRConfiguration trConfiguration;
private JLabel lblConfigpath = new JLabel("[config path not set]");
public ConfigWindow(){
this(new ArrayList<ConfigurationTab>());
}
public ConfigWindow(Collection<ConfigurationTab> tabs){
setTitle("Settings");
setSize(340,540);
final TR tr = getTr();
//this.cMgr = Features.get(tr, TRConfigRoot.class);
this.tabs = tabs;
//config = Features.get(tr, TRConfiguration.class);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel generalTab = new JPanel();
tabbedPane.addTab("General", new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/22x22/mimetypes/application-x-executable.png")), generalTab, null);
GridBagLayout gbl_generalTab = new GridBagLayout();
gbl_generalTab.columnWidths = new int[]{0, 0};
gbl_generalTab.rowHeights = new int[]{0, 188, 222, 0};
gbl_generalTab.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_generalTab.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
generalTab.setLayout(gbl_generalTab);
JPanel settingsLoadSavePanel = new JPanel();
GridBagConstraints gbc_settingsLoadSavePanel = new GridBagConstraints();
gbc_settingsLoadSavePanel.insets = new Insets(0, 0, 5, 0);
gbc_settingsLoadSavePanel.anchor = GridBagConstraints.WEST;
gbc_settingsLoadSavePanel.gridx = 0;
gbc_settingsLoadSavePanel.gridy = 0;
generalTab.add(settingsLoadSavePanel, gbc_settingsLoadSavePanel);
settingsLoadSavePanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Overall Settings", TitledBorder.LEADING, TitledBorder.TOP, null, null));
FlowLayout flowLayout_1 = (FlowLayout) settingsLoadSavePanel.getLayout();
flowLayout_1.setAlignment(FlowLayout.LEFT);
JButton btnSave = new JButton("Export...");
btnSave.setToolTipText("Export these settings to an external file");
settingsLoadSavePanel.add(btnSave);
btnSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
exportSettings();
}});
JButton btnLoad = new JButton("Import...");
btnLoad.setToolTipText("Import an external settings file");
settingsLoadSavePanel.add(btnLoad);
btnLoad.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
importSettings();
}});
JButton btnConfigReset = new JButton("Reset");
btnConfigReset.setToolTipText("Reset all settings to defaults");
settingsLoadSavePanel.add(btnConfigReset);
btnConfigReset.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
defaultSettings();
}});
JPanel registeredPODsPanel = new JPanel();
registeredPODsPanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Registered PODs", TitledBorder.LEFT, TitledBorder.TOP, null, null));
GridBagConstraints gbc_registeredPODsPanel = new GridBagConstraints();
gbc_registeredPODsPanel.insets = new Insets(0, 0, 5, 0);
gbc_registeredPODsPanel.fill = GridBagConstraints.BOTH;
gbc_registeredPODsPanel.gridx = 0;
gbc_registeredPODsPanel.gridy = 1;
generalTab.add(registeredPODsPanel, gbc_registeredPODsPanel);
GridBagLayout gbl_registeredPODsPanel = new GridBagLayout();
gbl_registeredPODsPanel.columnWidths = new int[]{272, 0};
gbl_registeredPODsPanel.rowHeights = new int[]{76, 0, 0};
gbl_registeredPODsPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_registeredPODsPanel.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
registeredPODsPanel.setLayout(gbl_registeredPODsPanel);
JPanel podListPanel = new JPanel();
GridBagConstraints gbc_podListPanel = new GridBagConstraints();
gbc_podListPanel.insets = new Insets(0, 0, 5, 0);
gbc_podListPanel.fill = GridBagConstraints.BOTH;
gbc_podListPanel.gridx = 0;
gbc_podListPanel.gridy = 0;
registeredPODsPanel.add(podListPanel, gbc_podListPanel);
podListPanel.setLayout(new BorderLayout(0, 0));
JScrollPane podListScrollPane = new JScrollPane();
podListPanel.add(podListScrollPane, BorderLayout.CENTER);
podList = new JList(podLM);
podList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
podListScrollPane.setViewportView(podList);
JPanel podListOpButtonPanel = new JPanel();
podListOpButtonPanel.setBorder(null);
GridBagConstraints gbc_podListOpButtonPanel = new GridBagConstraints();
gbc_podListOpButtonPanel.anchor = GridBagConstraints.NORTH;
gbc_podListOpButtonPanel.gridx = 0;
gbc_podListOpButtonPanel.gridy = 1;
registeredPODsPanel.add(podListOpButtonPanel, gbc_podListOpButtonPanel);
FlowLayout flowLayout = (FlowLayout) podListOpButtonPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
JButton addPodButton = new JButton("Add...");
addPodButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-add.png")));
addPodButton.setToolTipText("Add a POD to the registry to be considered when running a game.");
podListOpButtonPanel.add(addPodButton);
addPodButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
notifyNeedRestart();
addPOD();
}});
JButton removePodButton = new JButton("Remove");
removePodButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-remove.png")));
removePodButton.setToolTipText("Remove a POD file from being considered when playing a game");
podListOpButtonPanel.add(removePodButton);
removePodButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
//podLM.removeElement(podList.getSelectedValue());
notifyNeedRestart();
getPodRegistry().getPodCollection().remove(podList.getSelectedValue());
}});
JButton podEditButton = new JButton("Edit...");
podEditButton.setIcon(null);
podEditButton.setToolTipText("Edit the selected POD path");
podListOpButtonPanel.add(podEditButton);
podEditButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
notifyNeedRestart();
editPODPath();
}});
JPanel missionPanel = new JPanel();
GridBagConstraints gbc_missionPanel = new GridBagConstraints();
gbc_missionPanel.fill = GridBagConstraints.BOTH;
gbc_missionPanel.gridx = 0;
gbc_missionPanel.gridy = 2;
generalTab.add(missionPanel, gbc_missionPanel);
missionPanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Missions", TitledBorder.LEADING, TitledBorder.TOP, null, null));
GridBagLayout gbl_missionPanel = new GridBagLayout();
gbl_missionPanel.columnWidths = new int[]{0, 0};
gbl_missionPanel.rowHeights = new int[]{0, 0, 0};
gbl_missionPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_missionPanel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
missionPanel.setLayout(gbl_missionPanel);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
missionPanel.add(scrollPane, gbc_scrollPane);
missionList = new JList(missionLM);
missionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(missionList);
JPanel missionListOpButtonPanel = new JPanel();
GridBagConstraints gbc_missionListOpButtonPanel = new GridBagConstraints();
gbc_missionListOpButtonPanel.anchor = GridBagConstraints.NORTH;
gbc_missionListOpButtonPanel.gridx = 0;
gbc_missionListOpButtonPanel.gridy = 1;
missionPanel.add(missionListOpButtonPanel, gbc_missionListOpButtonPanel);
JButton addVOXButton = new JButton("Add...");
addVOXButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-add.png")));
addVOXButton.setToolTipText("Add an external VOX file as a mission");
missionListOpButtonPanel.add(addVOXButton);
addVOXButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
addVOX();
}});
final JButton removeVOXButton = new JButton("Remove");
removeVOXButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-remove.png")));
removeVOXButton.setToolTipText("Remove the selected mission");
missionListOpButtonPanel.add(removeVOXButton);
removeVOXButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
//TODO:
missionLM.remove(missionList.getSelectedIndex());
}});
final JButton editVOXButton = new JButton("Edit...");
editVOXButton.setToolTipText("Edit the selected Mission's VOX path");
missionListOpButtonPanel.add(editVOXButton);
editVOXButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
editVOXPath();
}});
missionList.addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent evt) {
final String val = (String)missionList.getSelectedValue();
if(val == null)
missionList.setSelectedIndex(0);
else if(isBuiltinVOX(val)){
removeVOXButton.setEnabled(false);
editVOXButton.setEnabled(false);
}else{
removeVOXButton.setEnabled(true);
editVOXButton.setEnabled(true);
}
}});
JPanel okCancelPanel = new JPanel();
getContentPane().add(okCancelPanel, BorderLayout.SOUTH);
okCancelPanel.setLayout(new BorderLayout(0, 0));
JButton btnOk = new JButton("OK");
btnOk.setToolTipText("Apply these settings and close the window");
okCancelPanel.add(btnOk, BorderLayout.WEST);
btnOk.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
//Keep settings, save to disk
try {getTrConfigRoot().saveConfigurations();}
catch(Exception e){e.printStackTrace();}
applySettingsEDT();
ConfigWindow.this.setVisible(false);
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.setToolTipText("Close the window without applying settings");
okCancelPanel.add(btnCancel, BorderLayout.EAST);
//final TRConfigRoot cfgRoot = getTrConfigRoot();
//final String cFilePath = cfgRoot.getConfigSaveURI();
//JLabel lblConfigpath = new JLabel(cFilePath);
lblConfigpath.setIcon(null);
lblConfigpath.setToolTipText("Default config file path");
lblConfigpath.setHorizontalAlignment(SwingConstants.CENTER);
lblConfigpath.setFont(new Font("Dialog", Font.BOLD, 6));
okCancelPanel.add(lblConfigpath, BorderLayout.CENTER);
btnCancel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
//dispatchComponentConfigs();
//Revert to original
getTrConfigRoot().loadConfigurations();
ConfigWindow.this.setVisible(false);
}});
}//end constructor
@Override
public void setVisible(boolean isVisible){
if(isVisible)
try {getTrConfigRoot().saveConfigurations();}
catch(Exception e){e.printStackTrace();}
super.setVisible(isVisible);
}//end setVisible(...)
private void applySettingsEDT(){
final TRConfigRoot configRoot = getTrConfigRoot();
final TRConfiguration config = getTrConfiguration();
config.setVoxFile((String)missionList.getSelectedValue());
//config.setModStereoWidth((double)modStereoWidthSlider.getValue()/100.);
//config.setAudioLinearFiltering(chckbxLinearInterpolation.isSelected());
//config.setAudioBufferLag(chckbxBufferLag.isSelected());
{HashSet<String>pList=new HashSet<String>();
//for(int i=0; i<podLM.getSize();i++)
// pList.add((String)podLM.getElementAt(i));
//podLM.clear();//Clear so we don't get a double-copy when the dispatcher populates it.
//final Collection<String> podCollection = getPodRegistry().getPodCollection();
//podCollection.clear();
//for(String pod:pList)
//podCollection.add(pod);
HashSet<String>vxList=new HashSet<String>();
for(int i=0; i<missionLM.getSize();i++)
vxList.add((String)missionLM.getElementAt(i));
config.setMissionList(vxList);}
//soundOutputSelectorGUI.applySettings(config);
try{configRoot.saveConfigurations();}
catch(Exception e){e.printStackTrace();}
//writeSettingsTo(cMgr.getConfigFilePath());
if(needRestart)
notifyOfRestart();
//final AudioBufferSize abs = (AudioBufferSize)audioBufferSizeCB.getSelectedItem();
//config.setAudioBufferSize(abs.getSizeInFrames());
//Apply the component configs
//gatherComponentConfigs();
}//end applySettings()
/*
private void gatherComponentConfigs(){
Map<String,Object> configs = config.getComponentConfigs();
for(ConfigurationTab tab:tabs){
System.out.println("Putting tab "+tab.getTabName()+" With entries:");
System.out.print("\t");
ControllerConfigTabConf conf = (ControllerConfigTabConf)tab.getConfigBean();
for(Entry ent: conf.getControllerConfigurations().entrySet()){
System.out.print(" "+ent.getKey());
} System.out.println();
configs.put(tab.getConfigBeanClass().getName(), tab.getConfigBean());}
}//end gatherComponentConfigs()
*/
/*
private void dispatchComponentConfigs(){
Map<String,Object> configs = config.getComponentConfigs();
for(ConfigurationTab tab:tabs)
tab.setConfigBean(configs.get(tab.getConfigBeanClass().getName()));
}//end dispatchComponentConfigs()
*/
private void readSettingsToPanel(){
final TRConfiguration config = getTrConfiguration();
//Initial settings - These do not listen to the config states!
final SoundSystem soundSystem = Features.get(getTr(), SoundSystem.class);
//modStereoWidthSlider.setValue((int)(config.getModStereoWidth()*100.));
//chckbxLinearInterpolation.setSelected(soundSystem.isLinearFiltering());
//chckbxBufferLag.setSelected(soundSystem.isBufferLag());
/*final int bSize = config.getAudioBufferSize();
for(AudioBufferSize abs:AudioBufferSize.values())
if(abs.getSizeInFrames()==bSize)
audioBufferSizeCB.setSelectedItem(abs);
*/
missionLM.removeAllElements();
for(String vox:config.getMissionList()){
if(isBuiltinVOX(vox))
missionLM.addElement(vox);
else if(checkVOX(new File(vox)))
missionLM.addElement(vox);
}//end for(vox)
String missionSelection = config.getVoxFile();
for(int i=0; i<missionLM.getSize(); i++){
if(((String)missionLM.get(i)).contentEquals(missionSelection))missionList.setSelectedIndex(i);}
/*
podLM.removeAllElements();
final Collection<String> podRegistryCollection = getPodRegistry().getPodCollection();
//final DefaultListModel podList = config.getPodList();
for(String path : podRegistryCollection){
if(path!=null)
if(checkPOD(new File(path)))
podLM.addElement(path);}
*/
//soundOutputSelectorGUI.readToPanel(config);
//Undo any flags set by the listeners.
needRestart=false;
}//end readSettings()
private boolean isBuiltinVOX(String vox){
return vox.contentEquals(TRConfiguration.AUTO_DETECT) ||
vox.contentEquals("Fury3") || vox.contentEquals("TV") ||
vox.contentEquals("FurySE");
}//end isBuiltinVOX
private void notifyOfRestart(){
JOptionPane.showMessageDialog(this, "Some changes won't take effect until the program is restarted.");
needRestart=false;
}
private void addPOD(){
fileChooser.setFileFilter(new FileFilter(){
@Override
public boolean accept(File file) {
return file.getName().toUpperCase().endsWith(".POD")||file.isDirectory();
}
@Override
public String getDescription() {
return "Terminal Reality .POD files";
}});
if(fileChooser.showOpenDialog(this)!=JFileChooser.APPROVE_OPTION)
return;
final File file = fileChooser.getSelectedFile();
if(!checkPOD(file))
return;
//podLM.addElement(file.getAbsolutePath());
getPodRegistry().getPodCollection().add(file.getAbsolutePath());
}//end addPOD()
private void addVOX() {
fileChooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().toUpperCase().endsWith(".VOX")||file.isDirectory();
}
@Override
public String getDescription() {
return "Terminal Reality .VOX files";
}
});
if (fileChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
return;
final File file = fileChooser.getSelectedFile();
if(file!=null)
missionLM.addElement(file.getAbsolutePath());
}//end addVOX()
private boolean writeSettingsToNormalConf(){
try{
//cMgr.saveConfigurations(f);
final TRConfigRoot configRoot = getTrConfigRoot();
//configRoot.setConfigSaveURI(f.getPath());
configRoot.saveConfigurations();
return true;
}catch(Exception e){JOptionPane.showMessageDialog(
this,
"Failed to write the config file.\n"
+ e.getLocalizedMessage()+"\n"+e.getClass().getName(),
"File write failure", JOptionPane.ERROR_MESSAGE);
return false;}
}//end writeSettings()
private boolean writeSettingsTo(File f){
try{/*
//cMgr.saveConfigurations(f);
final TRConfigRoot configRoot = getTrConfigRoot();
configRoot.setConfigSaveURI(f.getPath());
configRoot.saveConfigurations();
*/
getTrConfigRoot().saveConfigurations(f);
return true;
}catch(Exception e){JOptionPane.showMessageDialog(
this,
"Failed to write the config file.\n"
+ e.getLocalizedMessage()+"\n"+e.getClass().getName(),
"File write failure", JOptionPane.ERROR_MESSAGE);
return false;}
}//end writeSettingsTo(...)
private void exportSettings(){
fileChooser.setFileFilter(new FileFilter(){
@Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".config.trcl.xml")||file.isDirectory();
}
@Override
public String getDescription() {
return "Terminal Recall Config Files";
}});
fileChooser.showSaveDialog(this);
File f = fileChooser.getSelectedFile();
if(f==null)return;
writeSettingsTo(f);
}//end exportSettings()
private void editVOXPath(){
JOptionPane.showMessageDialog(this, "Not yet implemented.");
//TODO
/*
final String result = JOptionPane.showInputDialog(this, "Edit VOX Path", missionLM.get(missionList.getSelectedIndex()));
if(result==null)// Clicked Cancel
return;// Do nothing
if(checkVOX(new File(result)))
missionLM.set(missionList.getSelectedIndex(), result);
*/
}//end editVOXPath()
private void editPODPath(){
JOptionPane.showMessageDialog(this, "Not yet implemented.");
//TODO
/*
final String result = JOptionPane.showInputDialog(this, "Edit POD Path", podLM.get(missionList.getSelectedIndex()));
if(result==null)// Clicked Cancel
return;// Do nothing
if(checkPOD(new File(result)))
podLM.set(podList.getSelectedIndex(), result);
*/
}//end editPODPath()
private boolean readSettingsFromFile(File f){
try{/*
FileInputStream is = new FileInputStream(f);
XMLDecoder xmlDec = new XMLDecoder(is);
xmlDec.setExceptionListener(new ExceptionListener(){
@Override
public void exceptionThrown(Exception e) {
e.printStackTrace();
}});
TRConfiguration src =(TRConfiguration)xmlDec.readObject();
xmlDec.close();
TRConfiguration config = getTrConfiguration();
*/
this.getTrConfigRoot().loadConfigurations(f);
/*if(config!=null)
BeanUtils.copyProperties(config, src);
else setTrConfiguration(config = src);*/
}catch(Exception e){JOptionPane.showMessageDialog(
this,
"Failed to read the specified file:\n"
+ e.getLocalizedMessage(),
"File read failure", JOptionPane.ERROR_MESSAGE);return false;}
return true;
}//end readSettingsFromFile(...)
private void importSettings(){
fileChooser.setFileFilter(new FileFilter(){
@Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".config.trcl.xml")||file.isDirectory();
}
@Override
public String getDescription() {
return "Terminal Recall Config Files";
}});
fileChooser.showOpenDialog(this);
File f = fileChooser.getSelectedFile();
if(f==null)return;
readSettingsFromFile(f);
readSettingsToPanel();
}//end exportSettings()
private void defaultSettings(){
JOptionPane.showMessageDialog(this, "Not yet implemented.");
//TODO
/*
try{BeanUtils.copyProperties(config, new TRConfiguration());}
catch(Exception e){e.printStackTrace();}
readSettingsToPanel();
*/
}
private boolean checkFile(File f){
if(f.exists())
return true;
JOptionPane.showMessageDialog(this, "The specified path could not be opened from disk:\n"+f.getAbsolutePath(), "File Not Found", JOptionPane.ERROR_MESSAGE);
return false;
}//end checkFile
private boolean checkPOD(File file){
if(!checkFile(file))
return false;
try{new PodFile(file).getData();}
catch(FileLoadException e){
JOptionPane.showMessageDialog(this, "Failed to parse the specified POD: \n"+e.getLocalizedMessage(), "POD failed format check.", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;}
return true;
}//end checkPOD(...)
private boolean checkVOX(File file){
if (!checkFile(file))
return false;
try {
FileInputStream fis = new FileInputStream(file);
new Parser().readToNewBean(fis, VOXFile.class);
fis.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(
this,
"Failed to parse the specified VOX: \n"
+ e.getLocalizedMessage(),
"VOX failed format check", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;
}
return true;
}//end checkVOX(...)
@Override
public void apply(TR target) {
setPodRegistry(Features.get(target, PODRegistry.class));
final TR tr;
setTr (tr = Features.get(Features.getSingleton(), TR.class));
setTrConfigRoot (Features.get(Features.getSingleton(), TRConfigRoot.class ));
setTrConfiguration(Features.get(tr, TRConfiguration.class));
final CollectionActionDispatcher<String> podRegistryCollection = getPodRegistry().getPodCollection();
podRegistryCollection.addTarget(podCollectionListener, true);
}
@Override
public void destruct(TR target) {
// TODO Auto-generated method stub
}
public void registerConfigTab(final ConfigurationTab configTab) {
final String name = configTab.getTabName();
final ImageIcon icon = configTab.getTabIcon();
final JComponent content = configTab.getContent();
try{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
tabbedPane.addTab(name,icon,content);
}});
}catch(Exception e){e.printStackTrace();}
//dispatchComponentConfigs();
}//end registerConfigTab(...)
public PODRegistry getPodRegistry() {
return podRegistry;
}
public void setPodRegistry(PODRegistry podRegistry) {
this.podRegistry = podRegistry;
}
private class PodCollectionListener implements List<String> {
@Override
public boolean add(final String element) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.addElement(element);
}});
return true;//Meh.
}
@Override
public void add(final int index, final String element) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.add(index, element);
}});
}
@Override
public boolean addAll(final Collection<? extends String> arg0) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
for(String s : arg0 )
podLM.addElement(s);
}});
return true;//Meh.
}
@Override
public boolean addAll(int arg0, Collection<? extends String> arg1) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.clear();
}});
}
@Override
public boolean contains(Object arg0) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> arg0) {
throw new UnsupportedOperationException();
}
@Override
public String get(int arg0) {
throw new UnsupportedOperationException();
}
@Override
public int indexOf(Object arg0) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator() {
throw new UnsupportedOperationException();
}
@Override
public int lastIndexOf(Object arg0) {
throw new UnsupportedOperationException();
}
@Override
public ListIterator<String> listIterator() {
throw new UnsupportedOperationException();
}
@Override
public ListIterator<String> listIterator(int arg0) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(final Object elementToRemove) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.removeElement(elementToRemove);
}});
return true; //Meh.
}
@Override
public String remove(final int indexOfElementToRemove) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.remove(indexOfElementToRemove);
}});
return null;//Meh.
}
@Override
public boolean removeAll(final Collection<?> elementsToRemove) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
boolean result = false;
for(Object o : elementsToRemove)
result |= podLM.removeElement(o);
}});
return true;//Meh.
}
@Override
public boolean retainAll(Collection<?> arg0) {
throw new UnsupportedOperationException();
}
@Override
public String set(final int index, final String element) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
podLM.set(index, element);
}});
return null;//Meh.
}
@Override
public int size() {
return podLM.size();
}
@Override
public List<String> subList(int arg0, int arg1) {
throw new UnsupportedOperationException();
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] arg0) {
throw new UnsupportedOperationException();
}
}//end PodCollectionListener
public TR getTr() {
return tr;
}
public void setTr(TR tr) {
this.tr = tr;
}
public TRConfigRoot getTrConfigRoot() {
return trConfigRoot;
}
public void setTrConfigRoot(TRConfigRoot trConfigRoot) {
this.trConfigRoot = trConfigRoot;
final String cFilePath = trConfigRoot.getConfigSaveURI();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
lblConfigpath.setText(cFilePath);
}});
}//end setTrConfigRoot(...)
public TRConfiguration getTrConfiguration() {
return trConfiguration;
}
public void setTrConfiguration(TRConfiguration trConfiguration) {
this.trConfiguration = trConfiguration;
}
public void notifyNeedRestart(){
needRestart = true;
}
@Override
public void graphStabilized(Object target) {
if(getTrConfiguration() != null)
readSettingsToPanel();
}
}//end ConfigWindow
@Override
public Feature<TR> newInstance(TR target) {
final ConfigWindow result = new ConfigWindow();
return result;
}
@Override
public Class<TR> getTargetClass() {
return TR.class;
}
@Override
public Class<? extends Feature> getFeatureClass() {
return ConfigWindow.class;
}
}//end ConfigWindowFactory |
package org.encuestame.core.persistence.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
/**
* SecUsers.
*
* @author Picado, Juan juan@encuestame.org
* @since October 17, 2009
*/
@Entity
@Table(name = "sec_users", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class SecUsers implements Serializable {
private Integer uid;
private String name;
private String email;
private String username;
private String password;
private Boolean status;
private String inviteCode;
private Date dateNew;
private String publisher;
private String owner;
private String twitter;
private Set<SecGroupUser> secGroupUsers = new HashSet<SecGroupUser>(0);
private Set<SecUserPermission> secUserPermissions = new HashSet<SecUserPermission>(
0);
private Set<CatLocationUser> catLocationUsers = new HashSet<CatLocationUser>(
0);
private Set<SurveyResultMod> surveyResultMods = new HashSet<SurveyResultMod>(
0);
private Set<ProjectUser> projectUsers = new HashSet<ProjectUser>(0);
private Set<QuestionColettion> questionColettions = new HashSet<QuestionColettion>(
0);
private Set<Surveys> surveyses = new HashSet<Surveys>(0);
public SecUsers() {
}
public SecUsers(String name, String email, String password, boolean status,
Date dateNew, String publisher) {
this.name = name;
this.email = email;
this.password = password;
this.status = status;
this.dateNew = dateNew;
this.publisher = publisher;
}
public SecUsers(String name, String email, String username,
String password, Boolean status, String inviteCode, Date dateNew,
String publisher, String owner, String twitter,
Set<SecGroupUser> secGroupUsers,
Set<SecUserPermission> secUserPermissions, Set catLocationUsers,
Set surveyResultMods, Set<ProjectUser> projectUsers,
Set<QuestionColettion> questionColettions, Set<Surveys> surveyses) {
this.name = name;
this.email = email;
this.username = username;
this.password = password;
this.status = status;
this.inviteCode = inviteCode;
this.dateNew = dateNew;
this.publisher = publisher;
this.owner = owner;
this.twitter = twitter;
this.secGroupUsers = secGroupUsers;
this.secUserPermissions = secUserPermissions;
this.catLocationUsers = catLocationUsers;
this.surveyResultMods = surveyResultMods;
this.projectUsers = projectUsers;
this.questionColettions = questionColettions;
this.surveyses = surveyses;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "uid", unique = true, nullable = false)
public Integer getUid() {
return this.uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
@Column(name = "name", nullable = false, length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "email", unique = true, nullable = false, length = 100)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "username")
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "status", nullable = false)
public Boolean isStatus() {
return this.status;
}
public void setStatus(boolean status) {
this.status = status;
}
@Column(name = "invite_code")
public String getInviteCode() {
return this.inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date_new", nullable = false, length = 0)
public Date getDateNew() {
return this.dateNew;
}
public void setDateNew(Date dateNew) {
this.dateNew = dateNew;
}
@Column(name = "publisher", nullable = true, length = 2)
public String getPublisher() {
return this.publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
@Column(name = "owner", length = 2)
public String getOwner() {
return this.owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Column(name = "twitter", length = 2)
public String getTwitter() {
return this.twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<SecGroupUser> getSecGroupUsers() {
return this.secGroupUsers;
}
public void setSecGroupUsers(Set<SecGroupUser> secGroupUsers) {
this.secGroupUsers = secGroupUsers;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<SecUserPermission> getSecUserPermissions() {
return this.secUserPermissions;
}
public void setSecUserPermissions(Set<SecUserPermission> secUserPermissions) {
this.secUserPermissions = secUserPermissions;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<CatLocationUser> getCatLocationUsers() {
return this.catLocationUsers;
}
public void setCatLocationUsers(Set<CatLocationUser> catLocationUsers) {
this.catLocationUsers = catLocationUsers;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<SurveyResultMod> getSurveyResultMods() {
return this.surveyResultMods;
}
public void setSurveyResultMods(Set<SurveyResultMod> surveyResultMods) {
this.surveyResultMods = surveyResultMods;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<ProjectUser> getProjectUsers() {
return this.projectUsers;
}
public void setProjectUsers(Set<ProjectUser> projectUsers) {
this.projectUsers = projectUsers;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<QuestionColettion> getQuestionColettions() {
return this.questionColettions;
}
public void setQuestionColettions(Set<QuestionColettion> questionColettions) {
this.questionColettions = questionColettions;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "secUsers")
public Set<Surveys> getSurveyses() {
return this.surveyses;
}
public void setSurveyses(Set<Surveys> surveyses) {
this.surveyses = surveyses;
}
} |
package org.lightmare.deploy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.ObjectUtils;
/**
* Manager class for application deployment
*
* @author levan
*
*/
public class LoaderPoolManager {
// Amount of deployment thread pool
private static final int LOADER_POOL_SIZE = 5;
// Name prefix of deployment threads
private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-%s";
/**
* Gets class loader for existing {@link org.lightmare.deploy.MetaCreator}
* instance
*
* @return {@link ClassLoader}
*/
protected static ClassLoader getCurrent() {
ClassLoader current;
MetaCreator creator = MetaContainer.getCreator();
ClassLoader creatorLoader;
if (ObjectUtils.notNull(creator)) {
// Gets class loader for this deployment
creatorLoader = creator.getCurrent();
if (ObjectUtils.notNull(creatorLoader)) {
current = creatorLoader;
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
} else {
current = LibraryLoader.getContextClassLoader();
}
return current;
}
/**
* Implementation of {@link ThreadFactory} interface for application loading
*
* @author levan
*
*/
private static final class LoaderThreadFactory implements ThreadFactory {
/**
* Constructs and sets thread name
*
* @param thread
*/
private void nameThread(Thread thread) {
String name = String.format(LOADER_THREAD_NAME, thread.getId());
thread.setName(name);
}
/**
* Sets priority of {@link Thread} instance
*
* @param thread
*/
private void setPriority(Thread thread) {
thread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Sets {@link ClassLoader} to passed {@link Thread} instance
*
* @param thread
*/
private void setContextClassLoader(Thread thread) {
ClassLoader parent = getCurrent();
thread.setContextClassLoader(parent);
}
/**
* Configures (sets name, priority and {@link ClassLoader}) passed
* {@link Thread} instance
*
* @param thread
*/
private void configureThread(Thread thread) {
nameThread(thread);
setPriority(thread);
setContextClassLoader(thread);
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
configureThread(thread);
return thread;
}
}
// Thread pool for deploying and removal of beans and temporal resources
private static ExecutorService LOADER_POOL = Executors.newFixedThreadPool(
LOADER_POOL_SIZE, new LoaderThreadFactory());
private static boolean invalid() {
return LOADER_POOL == null || LOADER_POOL.isShutdown()
|| LOADER_POOL.isTerminated();
}
/**
* Checks and if not valid reopens deploy {@link ExecutorService} instance
*
* @return {@link ExecutorService}
*/
protected static ExecutorService getLoaderPool() {
if (invalid()) {
synchronized (LoaderPoolManager.class) {
if (invalid()) {
LOADER_POOL = Executors.newFixedThreadPool(
LOADER_POOL_SIZE, new LoaderThreadFactory());
}
}
}
return LOADER_POOL;
}
public static void submit(Runnable runnable) {
getLoaderPool().submit(runnable);
}
public static <T> Future<T> submit(Callable<T> callable) {
Future<T> future = getLoaderPool().submit(callable);
return future;
}
/**
* Clears existing {@link ExecutorService}s from loader threads
*/
public static void reload() {
synchronized (LoaderPoolManager.class) {
LOADER_POOL.shutdown();
LOADER_POOL = null;
}
getLoaderPool();
}
} |
package com.akjava.gwt.three.client.gwt.model;
import com.akjava.gwt.lib.client.LogUtils;
import com.akjava.gwt.three.client.js.core.Face3;
import com.akjava.gwt.three.client.js.math.UV;
import com.akjava.gwt.three.client.js.math.Vector2;
import com.akjava.gwt.three.client.js.math.Vector4;
import com.akjava.gwt.three.client.js.math.Vertex;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayNumber;
import com.google.gwt.json.client.JSONObject;
public class JSONModelFile extends JavaScriptObject{
protected JSONModelFile(){}
public static JSONModelFile create(){
return create("GWT JSONModelFile r63");
}
@SuppressWarnings("unchecked")
public static JSONModelFile create(String generatedBy){
JSONModelFile f=(JSONModelFile) JSONModelFile.createObject();
MetaData mdata=(MetaData) MetaData.createObject();
mdata.setFormatVersion(3.1);
f.setMetaData(mdata);
f.setNormals((JsArrayNumber) JavaScriptObject.createArray());
f.setColors((JsArrayNumber) JavaScriptObject.createArray());
f.setVertices((JsArrayNumber) JavaScriptObject.createArray());
f.setFaces((JsArrayNumber) JavaScriptObject.createArray());
f.setUvs((JsArray<JsArrayNumber>) JsArray.createArray());
f.setMaterials((JsArray<ModelMaterials>) JsArray.createArray());
f.setSkinIndices((JsArrayNumber) JavaScriptObject.createArray());
f.setSkinWeights((JsArrayNumber) JavaScriptObject.createArray());
f.getMaterials().push(ModelMaterials.createDefault());
return f;
}
public final String getJsonText(){
return new JSONObject(this).toString();
}
public native final void setVertices (JsArrayNumber vertices)/*-{
this["vertices"]=vertices;
}-*/;
public native final double getScale()/*-{
return this["scale"];
}-*/;
public native final void setScale(double scale)/*-{
this["scale"]=scale;
}-*/;
public native final JsArrayNumber getVertices ()/*-{
return this["vertices"];
}-*/;
public native final void setFaces (JsArrayNumber faces)/*-{
this["faces"]=faces;
}-*/;
public native final JsArrayNumber getFaces ()/*-{
return this["faces"];
}-*/;
public native final void setNormals (JsArrayNumber normals)/*-{
this["normals"]=normals;
}-*/;
public native final JsArrayNumber getNormals ()/*-{
return this["normals"];
}-*/;
public native final void setColors (JsArrayNumber colors)/*-{
this["colors"]=colors;
}-*/;
public native final JsArrayNumber getColors ()/*-{
return this["colors"];
}-*/;
public native final JsArrayNumber getSkinWeights ()/*-{
return this["skinWeights"];
}-*/;
public native final void setSkinWeights(JsArrayNumber skinWeights)/*-{
this["skinWeights"]=skinWeights;
}-*/;
public native final void setSkinIndices (JsArrayNumber skinIndices)/*-{
this["skinIndices"]=skinIndices;
}-*/;
public native final JsArrayNumber getSkinIndices ()/*-{
return this["skinIndices"];
}-*/;
public native final void setUvs (JsArray<JsArrayNumber> uvs)/*-{
this["uvs"]=uvs;
}-*/;
public native final JsArray<JsArrayNumber> getUvs ()/*-{
return this["uvs"];
}-*/;
public native final void setMaterials (JsArray<ModelMaterials> materials)/*-{
this["materials"]=materials;
}-*/;
public native final JsArray<ModelMaterials> getMaterials ()/*-{
return this["materials"];
}-*/;
public native final JavaScriptObject getAnimation ()/*-{
return this["animation"];
}-*/;
public native final void setAnimation (JavaScriptObject animation)/*-{
this["animation"]=animation;
}-*/;
public native final JsArray<JavaScriptObject> getBones ()/*-{
return this["bones"];
}-*/;
public native final void setBones (JsArray<JavaScriptObject> bones)/*-{
this["bones"]=bones;
}-*/;
public native final JsArray<JavaScriptObject> getMorphTargets ()/*-{
return this["morphTargets"];
}-*/;
public native final void setMorphTargets (JsArray<JavaScriptObject> morphTargets)/*-{
this["morphTargets"]=morphTargets;
}-*/;
public native final JsArray<JavaScriptObject> getMorphColors ()/*-{
return this["morphColors"];
}-*/;
public native final void setMorphColors (JsArray<JavaScriptObject> morphColors)/*-{
this["morphColors"]=morphColors;
}-*/;
public final void setSkinIndicesAndWeights(JsArray<Vector4> indices,JsArray<Vector4> weights){
JsArrayNumber indicesArray=(JsArrayNumber) JsArrayNumber.createArray();
for(int i=0;i<indices.length();i++){
indicesArray.push(indices.get(i).getX());
indicesArray.push(indices.get(i).getY());
}
JsArrayNumber weightsArray=(JsArrayNumber) JsArrayNumber.createArray();
for(int i=0;i<weights.length();i++){
weightsArray.push(weights.get(i).getX());
weightsArray.push(weights.get(i).getY());
}
LogUtils.log("indicesArray.length"+indicesArray.length());
LogUtils.log("weightsArray.length"+weightsArray.length());
setSkinIndices(indicesArray);
setSkinWeights(weightsArray);
}
public final void setVertices(JsArray<Vertex> vx){
JsArrayNumber nums=(JsArrayNumber) JsArrayNumber.createArray();
for(int i=0;i<vx.length();i++){
nums.push(vx.get(i).getPosition().getX());
nums.push(vx.get(i).getPosition().getY());
nums.push(vx.get(i).getPosition().getZ());
}
setVertices(nums);
}
/*
* single uv only
*/
public final void setGeometryUvs(JsArray<JsArray<Vector2>> uvs){
@SuppressWarnings("unchecked")
JsArray<JsArrayNumber> uvArray=(JsArray<JsArrayNumber>) JsArray.createArray();
JsArrayNumber nums=(JsArrayNumber) JsArrayNumber.createArray();
uvArray.push(nums);
//LogUtils.log("uvs:"+uvs.length());
for(int i=0;i<uvs.length();i++){
JsArray<Vector2> u=uvs.get(i);
//LogUtils.log("uvs:-u"+u.length());
for(int j=0;j<u.length();j++){
Vector2 uv=u.get(j);
nums.push(uv.getX());
nums.push(uv.getY());
}
}
setUvs(uvArray);
}
/**
* call setUvs first
* @param faces
*/
public final void setFaces(JsArray<Face3> faces){
boolean hasUv=getUvs().length()>0;
JsArrayNumber nums=(JsArrayNumber) JsArrayNumber.createArray();
int faceIndex=0;
for(int i=0;i<faces.length();i++){
Face3 face=faces.get(i);
if(face.isFace4()){
int v=1;if(hasUv){v=8+1;};
nums.push(v); // quad
nums.push(face.getA());
nums.push(face.getB());
nums.push(face.getC());
nums.push(face.getD());
if(hasUv){//uv is same as vx
nums.push(faceIndex);
nums.push(faceIndex+1);
nums.push(faceIndex+2);
nums.push(faceIndex+3);
}
faceIndex+=4;
}else{
int v=0;if(hasUv){v=8+0;};
nums.push(v); // triangle
nums.push(face.getA());
nums.push(face.getB());
nums.push(face.getC());
if(hasUv){//uv is same as vx
nums.push(faceIndex);
nums.push(faceIndex+1);
nums.push(faceIndex+2);
}
faceIndex+=3;
}
}
setFaces(nums);
}
public native final void setMetaData(MetaData meta)/*-{
this["metadata"]=meta;
}-*/;
public native final MetaData getMetaData()/*-{
return this["metadata"];
}-*/;
public final JSONModelFile clone(){
JSONModelFile newFile=create();
//metadata
newFile.setMetaData(this.getMetaData().clone());
newFile.setScale(this.getScale());
//TODO clone completly
newFile.setMaterials(this.getMaterials());//warning shared
if(this.getMorphTargets()!=null){
newFile.setMorphTargets(this.getMorphTargets());
}
if(this.getMorphColors()!=null){
newFile.setMorphColors(this.getMorphColors());
}
if(this.getBones()!=null){
newFile.setBones(this.getBones());
}
if(this.getAnimation()!=null){
newFile.setAnimation(this.getAnimation());
}
//clone uvs
if(this.getUvs()!=null){
JsArray<JsArrayNumber> valuesUvs=this.getUvs();
for(int i=0;i<valuesUvs.length();i++){
JsArrayNumber uvs=valuesUvs.get(i);
JsArrayNumber array=(JsArrayNumber) JavaScriptObject.createArray();
for(int j=0;j<uvs.length();j++){
array.push(uvs.get(j));
}
newFile.getUvs().push(array);
}
}
//clone faces,normals,colors,vertices,skinIndices,skinWeights
if(this.getFaces()!=null){
JsArrayNumber values=this.getFaces();
for(int i=0;i<values.length();i++){
newFile.getFaces().push(values.get(i));
}
}
if(this.getNormals()!=null){
JsArrayNumber values=this.getNormals();
for(int i=0;i<values.length();i++){
newFile.getNormals().push(values.get(i));
}
}
if(this.getColors()!=null){
JsArrayNumber values=this.getColors();
for(int i=0;i<values.length();i++){
newFile.getColors().push(values.get(i));
}
}
if(this.getVertices()!=null){
JsArrayNumber values=this.getVertices();
for(int i=0;i<values.length();i++){
newFile.getVertices().push(values.get(i));
}
}
if(this.getSkinIndices()!=null){
JsArrayNumber values=this.getSkinIndices();
for(int i=0;i<values.length();i++){
newFile.getSkinIndices().push(values.get(i));
}
}
if(this.getSkinWeights()!=null){
JsArrayNumber values=this.getSkinWeights();
for(int i=0;i<values.length();i++){
newFile.getSkinWeights().push(values.get(i));
}
}
return newFile;
}
} |
package org.lightmare.utils.fs.codecs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.lightmare.utils.IOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.lightmare.utils.fs.FileType;
/**
* Implementation of {@link DirUtils} for ear files
*
* @author Levan Tsinadze
* @since 0.0.81-SNAPSHOT
*/
public class ExtUtils extends DirUtils {
public static final FileType type = FileType.EAR;
private File tmpFile;
public ExtUtils(String path) {
super(path);
}
public ExtUtils(File file) {
super(file);
}
public ExtUtils(URL url) throws IOException {
super(url);
}
@Override
public FileType getType() {
return type;
}
/**
* Extracts ear file into the temporary file
*
* @throws IOException
*/
protected void exctractEar() throws IOException {
tmpFile = File.createTempFile(realFile.getName(),
StringUtils.EMPTY_STRING);
tmpFile.delete();
tmpFile.mkdir();
addTmpFile(tmpFile);
ZipFile zipFile = getEarFile();
Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
while (zipFileEntries.hasMoreElements()) {
ZipEntry entry = zipFileEntries.nextElement();
exctractFile(entry);
}
}
protected void exctractFile(ZipEntry entry) throws IOException {
InputStream extStream = getEarFile().getInputStream(entry);
File file = new File(tmpFile, entry.getName());
File parrent = file.getParentFile();
if (ObjectUtils.notTrue(parrent.exists())) {
parrent.mkdirs();
addTmpFile(parrent);
}
// Caches temporal files
addTmpFile(file);
if (ObjectUtils.notTrue(entry.isDirectory())) {
if (ObjectUtils.notTrue(file.exists())) {
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
IOUtils.write(extStream, out);
} else {
file.mkdir();
}
}
@Override
protected void scanArchive(Object... args) throws IOException {
exctractEar();
super.realFile = tmpFile;
super.path = tmpFile.getPath();
super.isDirectory = tmpFile.isDirectory();
super.scanArchive(args);
}
} |
package org.apache.batik.apps.svgbrowser;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.util.Map;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.batik.ext.swing.JGridBagPanel;
import org.apache.batik.ext.swing.GridBagConstants;
import org.apache.batik.util.PreferenceManager;
import org.apache.batik.util.gui.CSSMediaPanel;
import org.apache.batik.util.gui.LanguageDialog;
import org.apache.batik.util.gui.UserStyleDialog;
/**
* Dialog that displays user preferences.
*
* @author <a href="mailto:vhardy@apache.org">Vincent Hardy</a>
* @version $Id$
*/
public class PreferenceDialog extends JDialog
implements GridBagConstants {
/**
* The return value if 'OK' is chosen.
*/
public final static int OK_OPTION = 0;
/**
* The return value if 'Cancel' is chosen.
*/
public final static int CANCEL_OPTION = 1;
// GUI Resources Keys
public static final String ICON_USER_LANGUAGE
= "PreferenceDialog.icon.userLanguagePref";
public static final String ICON_USER_STYLESHEET
= "PreferenceDialog.icon.userStylesheetPref";
public static final String ICON_BEHAVIOR
= "PreferenceDialog.icon.behaviorsPref";
public static final String ICON_NETWORK
= "PreferenceDialog.icon.networkPref";
public static final String LABEL_USER_OPTIONS
= "PreferenceDialog.label.user.options";
public static final String LABEL_BEHAVIOR
= "PreferenceDialog.label.behavior";
public static final String LABEL_NETWORK
= "PreferenceDialog.label.network";
public static final String LABEL_USER_LANGUAGE
= "PreferenceDialog.label.user.language";
public static final String LABEL_USER_STYLESHEET
= "PreferenceDialog.label.user.stylesheet";
public static final String LABEL_USER_FONT
= "PreferenceDialog.label.user.font";
public static final String LABEL_APPLICATIONS
= "PreferenceDialog.label.applications";
public static final String LABEL_SHOW_RENDERING
= "PreferenceDialog.label.show.rendering";
public static final String LABEL_AUTO_ADJUST_WINDOW
= "PreferenceDialog.label.auto.adjust.window";
public static final String LABEL_ENABLE_DOUBLE_BUFFERING
= "PreferenceDialog.label.enable.double.buffering";
public static final String LABEL_SHOW_DEBUG_TRACE
= "PreferenceDialog.label.show.debug.trace";
public static final String LABEL_SELECTION_XOR_MODE
= "PreferenceDialog.label.selection.xor.mode";
public static final String LABEL_IS_XML_PARSER_VALIDATING
= "PreferenceDialog.label.is.xml.parser.validating";
public static final String LABEL_ENFORCE_SECURE_SCRIPTING
= "PreferenceDialog.label.enforce.secure.scripting";
public static final String LABEL_SECURE_SCRIPTING_TOGGLE
= "PreferenceDialog.label.secure.scripting.toggle";
public static final String LABEL_GRANT_SCRIPT_FILE_ACCESS
= "PreferenceDialog.label.grant.script.file.access";
public static final String LABEL_GRANT_SCRIPT_NETWORK_ACCESS
= "PreferenceDialog.label.grant.script.network.access";
public static final String LABEL_LOAD_JAVA
= "PreferenceDialog.label.load.java";
public static final String LABEL_LOAD_ECMASCRIPT
= "PreferenceDialog.label.load.ecmascript";
public static final String LABEL_HOST
= "PreferenceDialog.label.host";
public static final String LABEL_PORT
= "PreferenceDialog.label.port";
public static final String LABEL_OK
= "PreferenceDialog.label.ok";
public static final String LABEL_LOAD_SCRIPTS
= "PreferenceDialog.label.load.scripts";
public static final String LABEL_ORIGIN_ANY
= "PreferenceDialog.label.origin.any";
public static final String LABEL_ORIGIN_DOCUMENT
= "PreferenceDialog.label.origin.document";
public static final String LABEL_ORIGIN_EMBED
= "PreferenceDialog.label.origin.embed";
public static final String LABEL_ORIGIN_NONE
= "PreferenceDialog.label.origin.none";
public static final String LABEL_SCRIPT_ORIGIN
= "PreferenceDialog.label.script.origin";
public static final String LABEL_RESOURCE_ORIGIN
= "PreferenceDialog.label.resource.origin";
public static final String LABEL_CANCEL
= "PreferenceDialog.label.cancel";
public static final String TITLE_BROWSER_OPTIONS
= "PreferenceDialog.title.browser.options";
public static final String TITLE_BEHAVIOR
= "PreferenceDialog.title.behavior";
public static final String TITLE_SECURITY
= "PreferenceDialog.title.security";
public static final String TITLE_NETWORK
= "PreferenceDialog.title.network";
public static final String TITLE_DIALOG
= "PreferenceDialog.title.dialog";
public static final String CONFIG_HOST_TEXT_FIELD_LENGTH
= "PreferenceDialog.config.host.text.field.length";
public static final String CONFIG_PORT_TEXT_FIELD_LENGTH
= "PreferenceDialog.config.port.text.field.length";
public static final String CONFIG_OK_MNEMONIC
= "PreferenceDialog.config.ok.mnemonic";
public static final String CONFIG_CANCEL_MNEMONIC
= "PreferenceDialog.config.cancel.mnemonic";
// Following are the preference keys used in the
// PreferenceManager model.
public static final String PREFERENCE_KEY_LANGUAGES
= "preference.key.languages";
public static final String PREFERENCE_KEY_IS_XML_PARSER_VALIDATING
= "preference.key.is.xml.parser.validating";
public static final String PREFERENCE_KEY_USER_STYLESHEET
= "preference.key.user.stylesheet";
public static final String PREFERENCE_KEY_SHOW_RENDERING
= "preference.key.show.rendering";
public static final String PREFERENCE_KEY_AUTO_ADJUST_WINDOW
= "preference.key.auto.adjust.window";
public static final String PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING
= "preference.key.enable.double.buffering";
public static final String PREFERENCE_KEY_SHOW_DEBUG_TRACE
= "preference.key.show.debug.trace";
public static final String PREFERENCE_KEY_SELECTION_XOR_MODE
= "preference.key.selection.xor.mode";
public static final String PREFERENCE_KEY_PROXY_HOST
= "preference.key.proxy.host";
public static final String PREFERENCE_KEY_CSS_MEDIA
= "preference.key.cssmedia";
public static final String PREFERENCE_KEY_PROXY_PORT
= "preference.key.proxy.port";
public static final String PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING
= "preference.key.enforce.secure.scripting";
public static final String PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS
= "preference.key.grant.script.file.access";
public static final String PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS
= "preferenced.key.grant.script.network.access";
public static final String PREFERENCE_KEY_LOAD_ECMASCRIPT
= "preference.key.load.ecmascript";
public static final String PREFERENCE_KEY_LOAD_JAVA
= "preference.key.load.java.script";
public static final String PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN
= "preference.key.allowed.script.origin";
public static final String PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN
= "preference.key.allowed.external.resource.origin";
/**
* <tt>PreferenceManager</tt> used to store and retrieve
* preferences
*/
protected PreferenceManager model;
/**
* Allows selection of the desired configuration panel
*/
protected ConfigurationPanelSelector configPanelSelector;
/**
* Allows selection of the user languages
*/
protected LanguageDialog.Panel languagePanel;
/**
* Allows selection of a user stylesheet
*/
protected UserStyleDialog.Panel userStylesheetPanel;
protected JCheckBox showRendering;
protected JCheckBox autoAdjustWindow;
protected JCheckBox showDebugTrace;
protected JCheckBox enableDoubleBuffering;
protected JCheckBox selectionXorMode;
protected JCheckBox isXMLParserValidating;
protected JCheckBox enforceSecureScripting;
protected JCheckBox grantScriptFileAccess;
protected JCheckBox grantScriptNetworkAccess;
protected JCheckBox loadJava;
protected JCheckBox loadEcmascript;
protected ButtonGroup scriptOriginGroup;
protected ButtonGroup resourceOriginGroup;
protected JTextField host, port;
protected CSSMediaPanel cssMediaPanel;
/**
* Code indicating whether the dialog was OKayed
* or cancelled
*/
protected int returnCode;
/**
* Default constructor
*/
public PreferenceDialog(PreferenceManager model){
super((Frame)null, true);
if(model == null){
throw new IllegalArgumentException();
}
this.model = model;
buildGUI();
initializeGUI();
pack();
}
/**
* Returns the preference manager used by this dialog.
*/
public PreferenceManager getPreferenceManager() {
return model;
}
/**
* Initializes the GUI components with the values
* from the model.
*/
protected void initializeGUI(){
// Initialize language. The set of languages is
// defined by a String.
String languages = model.getString(PREFERENCE_KEY_LANGUAGES);
languagePanel.setLanguages(languages);
// Initializes the User Stylesheet
String userStylesheetPath = model.getString(PREFERENCE_KEY_USER_STYLESHEET);
userStylesheetPanel.setPath(userStylesheetPath);
// Initializes the browser options
showRendering.setSelected(model.getBoolean(PREFERENCE_KEY_SHOW_RENDERING));
autoAdjustWindow.setSelected(model.getBoolean(PREFERENCE_KEY_AUTO_ADJUST_WINDOW));
enableDoubleBuffering.setSelected(model.getBoolean(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING));
showDebugTrace.setSelected(model.getBoolean(PREFERENCE_KEY_SHOW_DEBUG_TRACE));
selectionXorMode.setSelected(model.getBoolean(PREFERENCE_KEY_SELECTION_XOR_MODE));
isXMLParserValidating.setSelected(model.getBoolean(PREFERENCE_KEY_IS_XML_PARSER_VALIDATING));
enforceSecureScripting.setSelected(model.getBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING));
grantScriptFileAccess.setSelected(model.getBoolean(PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS));
grantScriptNetworkAccess.setSelected(model.getBoolean(PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS));
loadJava.setSelected(model.getBoolean(PREFERENCE_KEY_LOAD_JAVA));
loadEcmascript.setSelected(model.getBoolean(PREFERENCE_KEY_LOAD_ECMASCRIPT));
String allowedScriptOrigin = "" + model.getInteger(PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN);
if (allowedScriptOrigin == null || "".equals(allowedScriptOrigin)) {
allowedScriptOrigin = "" + ResourceOrigin.NONE;
}
Enumeration e = scriptOriginGroup.getElements();
while (e.hasMoreElements()) {
AbstractButton ab = (AbstractButton)e.nextElement();
String ac = ab.getActionCommand();
if (allowedScriptOrigin.equals(ac)) {
ab.setSelected(true);
}
}
String allowedResourceOrigin = "" + model.getInteger(PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN);
if (allowedResourceOrigin == null || "".equals(allowedResourceOrigin)) {
allowedResourceOrigin = "" + ResourceOrigin.NONE;
}
e = resourceOriginGroup.getElements();
while (e.hasMoreElements()) {
AbstractButton ab = (AbstractButton)e.nextElement();
String ac = ab.getActionCommand();
if (allowedResourceOrigin.equals(ac)) {
ab.setSelected(true);
}
}
showRendering.setEnabled
(!model.getBoolean(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING));
grantScriptFileAccess.setEnabled
(model.getBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING));
grantScriptNetworkAccess.setEnabled
(model.getBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING));
// Initialize the proxy options
host.setText(model.getString(PREFERENCE_KEY_PROXY_HOST));
port.setText(model.getString(PREFERENCE_KEY_PROXY_PORT));
// Initialize the CSS media
cssMediaPanel.setMedia(model.getString(PREFERENCE_KEY_CSS_MEDIA));
// Sets the dialog's title
setTitle(Resources.getString(TITLE_DIALOG));
}
/**
* Stores current setting in PreferenceManager model
*/
protected void savePreferences(){
model.setString(PREFERENCE_KEY_LANGUAGES,
languagePanel.getLanguages());
model.setString(PREFERENCE_KEY_USER_STYLESHEET,
userStylesheetPanel.getPath());
model.setBoolean(PREFERENCE_KEY_SHOW_RENDERING,
showRendering.isSelected());
model.setBoolean(PREFERENCE_KEY_AUTO_ADJUST_WINDOW,
autoAdjustWindow.isSelected());
model.setBoolean(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING,
enableDoubleBuffering.isSelected());
model.setBoolean(PREFERENCE_KEY_SHOW_DEBUG_TRACE,
showDebugTrace.isSelected());
model.setBoolean(PREFERENCE_KEY_SELECTION_XOR_MODE,
selectionXorMode.isSelected());
model.setBoolean(PREFERENCE_KEY_IS_XML_PARSER_VALIDATING,
isXMLParserValidating.isSelected());
model.setBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING,
enforceSecureScripting.isSelected());
model.setBoolean(PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS,
grantScriptFileAccess.isSelected());
model.setBoolean(PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS,
grantScriptNetworkAccess.isSelected());
model.setBoolean(PREFERENCE_KEY_LOAD_JAVA,
loadJava.isSelected());
model.setBoolean(PREFERENCE_KEY_LOAD_ECMASCRIPT,
loadEcmascript.isSelected());
model.setInteger(PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN,
(new Integer(scriptOriginGroup.getSelection().getActionCommand())).intValue());
model.setInteger(PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN,
(new Integer(resourceOriginGroup.getSelection().getActionCommand())).intValue());
model.setString(PREFERENCE_KEY_PROXY_HOST,
host.getText());
model.setString(PREFERENCE_KEY_PROXY_PORT,
port.getText());
model.setString(PREFERENCE_KEY_CSS_MEDIA,
cssMediaPanel.getMediaAsString());
}
/**
* Builds the UI for this dialog
*/
protected void buildGUI(){
JPanel panel = new JPanel(new BorderLayout());
Component config = buildConfigPanel();
Component list = buildConfigPanelList();
panel.add(list, BorderLayout.WEST);
panel.add(config, BorderLayout.CENTER);
panel.add(buildButtonsPanel(), BorderLayout.SOUTH);
panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 0, 0));
getContentPane().add(panel);
}
/**
* Creates the OK/Cancel buttons panel
*/
protected JPanel buildButtonsPanel() {
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton okButton = new JButton(Resources.getString(LABEL_OK));
okButton.setMnemonic(Resources.getCharacter(CONFIG_OK_MNEMONIC));
JButton cancelButton = new JButton(Resources.getString(LABEL_CANCEL));
cancelButton.setMnemonic(Resources.getCharacter(CONFIG_CANCEL_MNEMONIC));
p.add(okButton);
p.add(cancelButton);
okButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
returnCode = OK_OPTION;
savePreferences();
dispose();
}
});
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
returnCode = CANCEL_OPTION;
dispose();
}
});
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
setVisible(false);
returnCode = CANCEL_OPTION;
dispose();
}
}
});
return p;
}
protected Component buildConfigPanelList(){
String[] configList
= { Resources.getString(LABEL_NETWORK),
Resources.getString(LABEL_USER_LANGUAGE),
Resources.getString(LABEL_BEHAVIOR),
Resources.getString(LABEL_USER_STYLESHEET),
};
final JList list = new JList(configList);
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent evt){
if(!evt.getValueIsAdjusting()){
configPanelSelector.select(list.getSelectedValue().toString());
}
}
});
list.setVisibleRowCount(4);
// Set Cell Renderer
ClassLoader cl = this.getClass().getClassLoader();
Map map= new Hashtable();
map.put(Resources.getString(LABEL_USER_LANGUAGE), new ImageIcon(cl.getResource(Resources.getString(ICON_USER_LANGUAGE))));
map.put(Resources.getString(LABEL_USER_STYLESHEET), new ImageIcon(cl.getResource(Resources.getString(ICON_USER_STYLESHEET))));
map.put(Resources.getString(LABEL_BEHAVIOR), new ImageIcon(cl.getResource(Resources.getString(ICON_BEHAVIOR))));
map.put(Resources.getString(LABEL_NETWORK), new ImageIcon(cl.getResource(Resources.getString(ICON_NETWORK))));
list.setCellRenderer(new IconCellRenderer(map));
list.setSelectedIndex(0);
return new JScrollPane(list);
}
protected Component buildConfigPanel(){
JPanel configPanel = new JPanel();
CardLayout cardLayout = new CardLayout();
configPanel.setLayout(cardLayout);
configPanel.add(buildUserLanguage(),
Resources.getString(LABEL_USER_LANGUAGE));
configPanel.add(buildUserStyleSheet(),
Resources.getString(LABEL_USER_STYLESHEET));
configPanel.add(buildBehavior(),
Resources.getString(LABEL_BEHAVIOR));
configPanel.add(buildNetwork(),
Resources.getString(LABEL_NETWORK));
configPanel.add(buildApplications(),
Resources.getString(LABEL_APPLICATIONS));
configPanelSelector = new ConfigurationPanelSelector(configPanel,
cardLayout);
return configPanel;
}
protected Component buildUserOptions(){
JTabbedPane p = new JTabbedPane();
p.add(buildUserLanguage(),
Resources.getString(LABEL_USER_LANGUAGE));
p.add(buildUserStyleSheet(),
Resources.getString(LABEL_USER_STYLESHEET));
p.add(buildUserFont(),
Resources.getString(LABEL_USER_FONT));
return p;
}
protected Component buildUserLanguage(){
languagePanel = new LanguageDialog.Panel();
return languagePanel;
}
protected Component buildUserStyleSheet(){
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
userStylesheetPanel = new UserStyleDialog.Panel();
panel.add(userStylesheetPanel, BorderLayout.NORTH);
cssMediaPanel = new CSSMediaPanel();
panel.add(cssMediaPanel, BorderLayout.SOUTH);
return panel;
}
protected Component buildUserFont(){
return new JButton("User Font");
}
protected Component buildBehavior(){
JGridBagPanel p = new JGridBagPanel();
showRendering
= new JCheckBox(Resources.getString(LABEL_SHOW_RENDERING));
autoAdjustWindow
= new JCheckBox(Resources.getString(LABEL_AUTO_ADJUST_WINDOW));
enableDoubleBuffering
= new JCheckBox(Resources.getString(LABEL_ENABLE_DOUBLE_BUFFERING));
enableDoubleBuffering.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showRendering.setEnabled(!enableDoubleBuffering.isSelected());
}
});
showDebugTrace
= new JCheckBox(Resources.getString(LABEL_SHOW_DEBUG_TRACE));
selectionXorMode
= new JCheckBox(Resources.getString(LABEL_SELECTION_XOR_MODE));
isXMLParserValidating
= new JCheckBox(Resources.getString(LABEL_IS_XML_PARSER_VALIDATING));
enforceSecureScripting
= new JCheckBox(Resources.getString(LABEL_SECURE_SCRIPTING_TOGGLE));
grantScriptFileAccess
= new JCheckBox(Resources.getString(LABEL_GRANT_SCRIPT_FILE_ACCESS));
grantScriptNetworkAccess
= new JCheckBox(Resources.getString(LABEL_GRANT_SCRIPT_NETWORK_ACCESS));
JGridBagPanel scriptSecurityPanel = new JGridBagPanel();
scriptSecurityPanel.add(enforceSecureScripting, 0, 0, 1, 1, WEST, HORIZONTAL, 1, 0);
scriptSecurityPanel.add(grantScriptFileAccess, 1, 0, 1, 1, WEST, HORIZONTAL, 1, 0);
scriptSecurityPanel.add(grantScriptNetworkAccess, 1, 1, 1, 1, WEST, HORIZONTAL, 1, 0);
enforceSecureScripting.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
grantScriptFileAccess.setEnabled(enforceSecureScripting.isSelected());
grantScriptNetworkAccess.setEnabled(enforceSecureScripting.isSelected());
}
});
loadJava
= new JCheckBox(Resources.getString(LABEL_LOAD_JAVA));
loadEcmascript
= new JCheckBox(Resources.getString(LABEL_LOAD_ECMASCRIPT));
JGridBagPanel loadScriptPanel = new JGridBagPanel();
loadScriptPanel.add(loadJava, 0, 0, 1, 1, WEST, NONE, 1, 0);
loadScriptPanel.add(loadEcmascript, 1, 0, 1, 1, WEST, NONE, 1, 0);
JPanel scriptOriginPanel = new JPanel();
scriptOriginGroup = new ButtonGroup();
JRadioButton rb = null;
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_ANY));
rb.setActionCommand("" + ResourceOrigin.ANY);
scriptOriginGroup.add(rb);
scriptOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_DOCUMENT));
rb.setActionCommand("" + ResourceOrigin.DOCUMENT);
scriptOriginGroup.add(rb);
scriptOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_EMBED));
rb.setActionCommand("" + ResourceOrigin.EMBEDED);
scriptOriginGroup.add(rb);
scriptOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_NONE));
rb.setActionCommand("" + ResourceOrigin.NONE);
scriptOriginGroup.add(rb);
scriptOriginPanel.add(rb);
JPanel resourceOriginPanel = new JPanel();
resourceOriginGroup = new ButtonGroup();
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_ANY));
rb.setActionCommand("" + ResourceOrigin.ANY);
resourceOriginGroup.add(rb);
resourceOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_DOCUMENT));
rb.setActionCommand("" + ResourceOrigin.DOCUMENT);
resourceOriginGroup.add(rb);
resourceOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_EMBED));
rb.setActionCommand("" + ResourceOrigin.EMBEDED);
resourceOriginGroup.add(rb);
resourceOriginPanel.add(rb);
rb = new JRadioButton(Resources.getString(LABEL_ORIGIN_NONE));
rb.setActionCommand("" + ResourceOrigin.NONE);
resourceOriginGroup.add(rb);
resourceOriginPanel.add(rb);
JTabbedPane browserOptions = new JTabbedPane();
// browserOptions.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
p.add(showRendering, 0, 0, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(autoAdjustWindow, 0, 1, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(enableDoubleBuffering, 0, 2, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(showDebugTrace, 0, 3, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(selectionXorMode, 0, 4, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(isXMLParserValidating, 0, 5, 2, 1, WEST, HORIZONTAL, 1, 0);
p.add(new JLabel(), 0, 11, 2, 1, WEST, BOTH, 1, 1);
browserOptions.addTab(Resources.getString(TITLE_BEHAVIOR), p);
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
p = new JGridBagPanel();
p.add(new JLabel(Resources.getString(LABEL_ENFORCE_SECURE_SCRIPTING)), 0, 6, 1, 1, NORTHWEST, NONE, 0, 0);
p.add(scriptSecurityPanel, 1, 6, 1, 1, WEST, NONE, 0, 0);
p.add(new JLabel(Resources.getString(LABEL_LOAD_SCRIPTS)), 0, 8, 1, 1, WEST, NONE, 0, 0);
p.add(loadScriptPanel, 1, 8, 1, 1, WEST, NONE, 1, 0);
p.add(new JLabel(Resources.getString(LABEL_SCRIPT_ORIGIN)), 0, 9, 1, 1, WEST, NONE, 0, 0);
p.add(scriptOriginPanel, 1, 9, 1, 1, WEST, NONE, 1, 0);
p.add(new JLabel(Resources.getString(LABEL_RESOURCE_ORIGIN)), 0, 10, 1, 1, WEST, NONE, 0, 0);
p.add(resourceOriginPanel, 1, 10, 1, 1, WEST, NONE, 1, 0);
p.add(new JLabel(), 0, 11, 2, 1, WEST, BOTH, 1, 1);
browserOptions.addTab(Resources.getString(TITLE_SECURITY), p);
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JGridBagPanel borderedPanel = new JGridBagPanel();
borderedPanel.add(browserOptions, 0, 0, 1, 1, WEST, BOTH, 1, 1);
borderedPanel.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),
Resources.getString(TITLE_BROWSER_OPTIONS)),
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
return borderedPanel;
}
protected Component buildNetwork(){
JGridBagPanel p = new JGridBagPanel();
host = new JTextField(Resources.getInteger(CONFIG_HOST_TEXT_FIELD_LENGTH));
JLabel hostLabel = new JLabel(Resources.getString(LABEL_HOST));
port = new JTextField(Resources.getInteger(CONFIG_PORT_TEXT_FIELD_LENGTH));
JLabel portLabel = new JLabel(Resources.getString(LABEL_PORT));
p.add(hostLabel, 0, 0, 1, 1, WEST, HORIZONTAL, 0, 0);
p.add(host, 0, 1, 1, 1, CENTER, HORIZONTAL, 1, 0);
p.add(portLabel, 1, 0, 1, 1, WEST, HORIZONTAL, 0, 0);
p.add(port, 1, 1, 1, 1, CENTER, HORIZONTAL, 0, 0);
p.add(new JLabel(""), 2, 1, 1, 1, CENTER, HORIZONTAL, 0, 0);
p.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),
Resources.getString(TITLE_NETWORK)),
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
return p;
}
protected Component buildApplications(){
return new JButton("Applications");
}
/**
* Shows the dialog
* @return OK_OPTION or CANCEL_OPTION
*/
public int showDialog(){
pack();
show();
return returnCode;
}
public static void main(String[] args){
Map defaults = new Hashtable();
defaults.put(PREFERENCE_KEY_LANGUAGES, "fr");
defaults.put(PREFERENCE_KEY_SHOW_RENDERING, Boolean.TRUE);
defaults.put(PREFERENCE_KEY_SELECTION_XOR_MODE, Boolean.FALSE);
defaults.put(PREFERENCE_KEY_IS_XML_PARSER_VALIDATING, Boolean.FALSE);
defaults.put(PREFERENCE_KEY_AUTO_ADJUST_WINDOW, Boolean.TRUE);
defaults.put(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING, Boolean.TRUE);
defaults.put(PREFERENCE_KEY_SHOW_DEBUG_TRACE, Boolean.TRUE);
defaults.put(PREFERENCE_KEY_PROXY_HOST, "webcache.eng.sun.com");
defaults.put(PREFERENCE_KEY_PROXY_PORT, "8080");
XMLPreferenceManager manager
= new XMLPreferenceManager(args[0], defaults);
PreferenceDialog dlg = new PreferenceDialog(manager);
int c = dlg.showDialog();
if(c == OK_OPTION){
try{
manager.save();
System.out.println("Done Saving options");
System.exit(0);
}catch(Exception e){
System.err.println("Could not save options");
e.printStackTrace();
}
}
}
}
class ConfigurationPanelSelector {
private CardLayout layout;
private Container container;
public ConfigurationPanelSelector(Container container,
CardLayout layout){
this.layout = layout;
this.container = container;
}
public void select(String panelName){
layout.show(container, panelName);
}
}
class IconCellRendererOld extends JLabel implements ListCellRenderer {
Map iconMap;
public IconCellRendererOld(Map iconMap){
this.iconMap = iconMap;
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
public Component getListCellRendererComponent
(
JList list,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
{
String s = value.toString();
setText(s);
ImageIcon icon = (ImageIcon)iconMap.get(s);
if(icon != null){
setIcon(icon);
setHorizontalAlignment(CENTER);
setHorizontalTextPosition(CENTER);
setVerticalTextPosition(BOTTOM);
}
// if (isSelected) {
setBackground(java.awt.Color.red); // list.getSelectionBackground());
setForeground(list.getSelectionForeground());
/*}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}*/
// setEnabled(list.isEnabled());
// setFont(list.getFont());
return this;
}
}
class IconCellRenderer extends JLabel
implements ListCellRenderer
{
protected Map map;
protected static Border noFocusBorder;
/**
* Constructs a default renderer object for an item
* in a list.
*/
public IconCellRenderer(Map map) {
super();
this.map = map;
noFocusBorder = BorderFactory.createEmptyBorder(1, 1, 1, 1);
setOpaque(true);
setBorder(noFocusBorder);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setComponentOrientation(list.getComponentOrientation());
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setBorder((cellHasFocus) ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder);
/*if (value instanceof Icon) {
setIcon((Icon)value);
setText("");
}
else {
setIcon(null);
setText((value == null) ? "" : value.toString());
}*/
setText(value.toString());
ImageIcon icon = (ImageIcon)map.get(value.toString());
if(icon != null){
setIcon(icon);
setHorizontalAlignment(CENTER);
setHorizontalTextPosition(CENTER);
setVerticalTextPosition(BOTTOM);
}
setEnabled(list.isEnabled());
setFont(list.getFont());
return this;
}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void validate() {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void revalidate() {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
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.
*/
public void repaint(Rectangle r) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
// Strings get interned...
if (propertyName=="text")
super.firePropertyChange(propertyName, oldValue, newValue);
}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
} |
package com.ecyrd.jspwiki.providers;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.Properties;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import java.util.Collections;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
/**
* Provides basic, versioning attachments.
*
* <PRE>
* Structure is as follows:
* attachment_dir/
* ThisPage/
* attachment.doc/
* attachment.properties
* 1.doc
* 2.doc
* 3.doc
* picture.png/
* attachment.properties
* 1.png
* 2.png
* ThatPage/
* picture.png/
* attachment.properties
* 1.png
*
* </PRE>
*
* The names of the directories will be URLencoded.
* <p>
* "attachment.properties" consists of the following items:
* <UL>
* <LI>1.author = author name for version 1 (etc)
* </UL>
*/
public class BasicAttachmentProvider
implements WikiAttachmentProvider
{
private String m_storageDir;
public static final String PROP_STORAGEDIR = "jspwiki.basicAttachmentProvider.storageDir";
public static final String PROPERTY_FILE = "attachment.properties";
public static final String DIR_EXTENSION = "-att";
public static final String ATTDIR_EXTENSION = "-dir";
static final Category log = Category.getInstance( BasicAttachmentProvider.class );
public void initialize( Properties properties )
throws NoRequiredPropertyException,
IOException
{
m_storageDir = WikiEngine.getRequiredProperty( properties, PROP_STORAGEDIR );
}
/**
* Finds storage dir, and if it exists, makes sure that it is valid.
*
* @param wikipage Page to which this attachment is attached.
*/
private File findPageDir( String wikipage )
throws ProviderException
{
wikipage = mangleName( wikipage );
File f = new File( m_storageDir, wikipage+DIR_EXTENSION );
if( f.exists() && !f.isDirectory() )
{
throw new ProviderException("Storage dir '"+f.getAbsolutePath()+"' is not a directory!");
}
return f;
}
private static String mangleName( String wikiname )
{
String res = TextUtil.urlEncodeUTF8( wikiname );
return res;
}
private static String unmangleName( String filename )
{
return TextUtil.urlDecodeUTF8( filename );
}
/**
* Finds the dir in which the attachment lives.
*/
private File findAttachmentDir( Attachment att )
throws ProviderException
{
File f = new File( findPageDir(att.getParentName()),
mangleName(att.getFileName()+ATTDIR_EXTENSION) );
return f;
}
/**
* Goes through the repository and decides which version is
* the newest one in that directory.
*
* @return Latest version number in the repository, or 0, if
* there is no page in the repository.
*/
private int findLatestVersion( Attachment att )
throws ProviderException
{
// File pageDir = findPageDir( att.getName() );
File attDir = findAttachmentDir( att );
// log.debug("Finding pages in "+attDir.getAbsolutePath());
String[] pages = attDir.list( new AttachmentVersionFilter() );
if( pages == null )
{
return 0; // No such thing found.
}
int version = 0;
for( int i = 0; i < pages.length; i++ )
{
// log.debug("Checking: "+pages[i]);
int cutpoint = pages[i].indexOf( '.' );
if( cutpoint > 0 )
{
String pageNum = ( cutpoint > 0 ) ? pages[i].substring( 0, cutpoint ) : pages[i] ;
try
{
int res = Integer.parseInt( pageNum );
if( res > version )
{
version = res;
}
}
catch( NumberFormatException e ) {} // It's okay to skip these.
}
}
return version;
}
/**
* Returns the file extension. For example "test.png" returns "png".
* <p>
* If file has no extension, will return "bin"
*/
protected static String getFileExtension( String filename )
{
String fileExt = "bin";
int dot = filename.lastIndexOf('.');
if( dot >= 0 && dot < filename.length()-1 )
{
fileExt = mangleName( filename.substring( dot+1 ) );
}
return fileExt;
}
/**
* Writes the page properties back to the file system.
* Note that it WILL overwrite any previous properties.
*/
private void putPageProperties( Attachment att, Properties properties )
throws IOException,
ProviderException
{
File attDir = findAttachmentDir( att );
File propertyFile = new File( attDir, PROPERTY_FILE );
OutputStream out = new FileOutputStream( propertyFile );
properties.store( out,
" JSPWiki page properties for "+
att.getName()+
". DO NOT MODIFY!" );
out.close();
}
/**
* Reads page properties from the file system.
*/
private Properties getPageProperties( Attachment att )
throws IOException,
ProviderException
{
Properties props = new Properties();
File propertyFile = new File( findAttachmentDir(att), PROPERTY_FILE );
if( propertyFile != null && propertyFile.exists() )
{
InputStream in = new FileInputStream( propertyFile );
props.load(in);
in.close();
}
return props;
}
public void putAttachmentData( Attachment att, InputStream data )
throws ProviderException,
IOException
{
OutputStream out = null;
File attDir = findAttachmentDir( att );
if(!attDir.exists())
{
attDir.mkdirs();
}
int latestVersion = findLatestVersion( att );
// System.out.println("Latest version is "+latestVersion);
try
{
int versionNumber = latestVersion+1;
File newfile = new File( attDir, versionNumber+"."+
getFileExtension(att.getFileName()) );
log.info("Uploading attachment "+att.getFileName()+" to page "+att.getParentName());
log.info("Saving attachment contents to "+newfile.getAbsolutePath());
out = new FileOutputStream(newfile);
FileUtil.copyContents( data, out );
out.close();
Properties props = getPageProperties( att );
String author = att.getAuthor();
if( author == null )
{
author = "unknown";
}
props.setProperty( versionNumber+".author", author );
putPageProperties( att, props );
}
catch( IOException e )
{
log.error( "Could not save attachment data: ", e );
throw (IOException) e.fillInStackTrace();
}
finally
{
if( out != null ) out.close();
}
}
public String getProviderInfo()
{
return "";
}
private File findFile( File dir, Attachment att )
throws FileNotFoundException,
ProviderException
{
int version = att.getVersion();
if( version == WikiProvider.LATEST_VERSION )
{
version = findLatestVersion( att );
}
File f = new File( dir, version+"."+getFileExtension(att.getFileName()) );
if( !f.exists() )
{
throw new FileNotFoundException("No such file: "+f.getAbsolutePath()+" exists.");
}
return f;
}
public InputStream getAttachmentData( Attachment att )
throws IOException,
ProviderException
{
File attDir = findAttachmentDir( att );
File f = findFile( attDir, att );
return new FileInputStream( f );
}
public Collection listAttachments( WikiPage page )
throws ProviderException
{
Collection result = new ArrayList();
File dir = findPageDir( page.getName() );
if( dir != null )
{
String[] attachments = dir.list();
if( attachments != null )
{
for( int i = 0; i < attachments.length; i++ )
{
File f = new File( dir, attachments[i] );
if( f.isDirectory() )
{
String attachmentName = unmangleName( attachments[i] );
if( attachmentName.endsWith( ATTDIR_EXTENSION ) )
{
attachmentName = attachmentName.substring( 0, attachmentName.length()-ATTDIR_EXTENSION.length() );
}
Attachment att = getAttachmentInfo( page, attachmentName,
WikiProvider.LATEST_VERSION );
if( att == null )
{
throw new ProviderException("Attachment disappeared while reading information:"+
" if you did not touch the repository, there is a serious bug somewhere. "+
"Attachment = "+attachments[i]+
", decoded = "+attachmentName );
}
result.add( att );
}
}
}
}
return result;
}
public Collection findAttachments( QueryItem[] query )
{
return null;
}
// FIXME: Very unoptimized.
public List listAllChanged( Date timestamp )
throws ProviderException
{
File attDir = new File( m_storageDir );
if( !attDir.exists() )
{
throw new ProviderException("Specified attachment directory "+m_storageDir+" does not exist!");
}
ArrayList list = new ArrayList();
String[] pagesWithAttachments = attDir.list( new AttachmentFilter() );
for( int i = 0; i < pagesWithAttachments.length; i++ )
{
String pageId = pagesWithAttachments[i];
pageId = pageId.substring( 0, pageId.length()-DIR_EXTENSION.length() );
Collection c = listAttachments( new WikiPage(pageId) );
for( Iterator it = c.iterator(); it.hasNext(); )
{
Attachment att = (Attachment) it.next();
if( att.getLastModified().after( timestamp ) )
{
list.add( att );
}
}
}
Collections.sort( list, new PageTimeComparator() );
return list;
}
public Attachment getAttachmentInfo( WikiPage page, String name, int version )
throws ProviderException
{
File dir = new File( findPageDir( page.getName() ),
mangleName(name)+ATTDIR_EXTENSION );
if( !dir.exists() )
{
// log.debug("Attachment dir not found - thus no attachment can exist.");
return null;
}
Attachment att = new Attachment( page.getName(), name );
if( version == WikiProvider.LATEST_VERSION )
{
version = findLatestVersion(att);
}
att.setVersion( version );
// System.out.println("Fetching info on version "+version);
try
{
Properties props = getPageProperties(att);
att.setAuthor( props.getProperty( version+".author" ) );
File f = findFile( dir, att );
att.setSize( f.length() );
att.setLastModified( new Date(f.lastModified()) );
}
catch( IOException e )
{
log.error("Can't read page properties", e );
throw new ProviderException("Cannot read page properties: "+e.getMessage());
}
// FIXME: Check for existence of this particular version.
return att;
}
public List getVersionHistory( Attachment att )
{
ArrayList list = new ArrayList();
try
{
int latest = findLatestVersion( att );
for( int i = 1; i <= latest; i++ )
{
Attachment a = getAttachmentInfo( new WikiPage(att.getParentName()),
att.getFileName(), i );
if( a != null )
{
list.add( a );
}
}
}
catch( ProviderException e )
{
log.error("Getting version history failed for page: "+att,e);
// FIXME: SHould this fail?
}
return list;
}
public void deleteVersion( Attachment att )
throws ProviderException
{
// FIXME: Does nothing yet.
}
public void deleteAttachment( Attachment att )
throws ProviderException
{
// FIXME: Does nothing yet.
}
/**
* Returns only those directories that contain attachments.
*/
public class AttachmentFilter
implements FilenameFilter
{
public boolean accept( File dir, String name )
{
return name.endsWith( DIR_EXTENSION );
}
}
/**
* Accepts only files that are actual versions, no control files.
*/
public class AttachmentVersionFilter
implements FilenameFilter
{
public boolean accept( File dir, String name )
{
return !name.equals( PROPERTY_FILE );
}
}
} |
package com.github.assisstion.ModulePack.logging;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Logger;
import javax.lang.model.SourceVersion;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import com.github.assisstion.ModulePack.Pair;
import com.github.assisstion.ModulePack.annotation.CompileVersion;
import com.github.assisstion.ModulePack.annotation.Dependency;
@Dependency(Pair.class)
@CompileVersion(SourceVersion.RELEASE_8) // Consumer<T>
public class LoggerPane extends JPanel implements Consumer<String>{
public Logger log;
private static final long serialVersionUID = 1022490441168101112L;
protected JTextPane textPane;
private JScrollPane scrollPane;
protected LogWorker worker;
protected ProgressWorker progress;
private JProgressBar progressBar;
protected Style style;
protected StyledDocument document;
//protected String separator;
protected Color color = Color.BLACK;
protected String separator;
protected boolean reverseOrder;
public LoggerPane(Logger log, boolean showProgress, boolean reverseOrder){
this(log, showProgress, "\n", reverseOrder);
}
public LoggerPane(Logger log, boolean showProgress, String separator){
this(log, showProgress, separator, false);
}
public LoggerPane(Logger log, boolean showProgress){
this(log, showProgress, "\n", false);
}
/**
* Create the frame.
*/
public LoggerPane(Logger log, boolean showProgress, String separator, boolean reverseOrder){
//setTitle();
setLayout(new BorderLayout(0, 0));
this.log = log;
this.reverseOrder = reverseOrder;
LogHandler handler = new LogHandler(this);
log.addHandler(handler);
scrollPane = new JScrollPane();
add(scrollPane);
textPane = new JTextPane();
scrollPane.setViewportView(textPane);
textPane.setEditable(false);
progressBar = new JProgressBar(0, 0);
progressBar.setEnabled(false);
progressBar.setStringPainted(false);
if(showProgress){
add(progressBar, BorderLayout.SOUTH);
}
if(!reverseOrder){
DefaultCaret caret = (DefaultCaret) textPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
document = textPane.getStyledDocument();
style = document.addStyle("text-style", null);
StyleConstants.setForeground(style, Color.BLACK);
worker = new LogWorker();
progress = new ProgressWorker();
this.separator = separator;
}
/*
public void setSeparator(String separator){
this.separator = separator;
}
public String getSeparator(){
return separator;
}
*/
public void setProgress(Pair<Integer, Integer> values){
progress.push(values);
}
public class LogWorker extends SwingWorker<Object, Pair<String, Color>>{
protected void push(Pair<String, Color> message){
publish(message);
}
@Override
protected Object doInBackground() throws Exception{
return null;
}
@Override
protected void process(List<Pair<String, Color>> messages){
for(Pair<String, Color> messageOne : messages){
String tempSeparator = "";
if(!textPane.getText().equals("")){
tempSeparator = separator;
}
StyleConstants.setForeground(style, messageOne.getValueTwo());
try{
if(reverseOrder){
document.insertString(0,
messageOne.getValueOne() + tempSeparator, style);
}
else{
document.insertString(document.getLength(),
tempSeparator + messageOne.getValueOne(), style);
}
}
catch(BadLocationException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ProgressWorker extends SwingWorker<Object, Pair<Integer, Integer>>{
protected void push(Pair<Integer, Integer> progress){
publish(progress);
}
@Override
protected Object doInBackground() throws Exception{
return null;
}
@Override
protected void process(List<Pair<Integer, Integer>> integerPairs){
for(Pair<Integer, Integer> pairOne : integerPairs){
if(pairOne.getValueTwo().equals(0)){
progressBar.setEnabled(false);
progressBar.setStringPainted(false);
}
else{
progressBar.setEnabled(true);
progressBar.setStringPainted(true);
}
progressBar.setValue(pairOne.getValueOne());
progressBar.setMaximum(pairOne.getValueTwo());
}
}
}
@Override
public void accept(String t){
worker.push(new Pair<String, Color>(t, color));
}
} |
package org.ow2.petals.activitibpmn;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_ENGINE_ENABLE_BPMN_VALIDATION;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_MONIT_TRACE_DELAY;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DEFAULT_SCHEDULED_LOGGER_CORE_SIZE;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.ENGINE_ENABLE_BPMN_VALIDATION;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.ENGINE_ENABLE_JOB_EXECUTOR;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.MONIT_TRACE_DELAY;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.SCHEDULED_LOGGER_CORE_SIZE;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.Activiti.PETALS_SENDER_COMP_NAME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DATABASE_SCHEMA_UPDATE;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DATABASE_TYPE;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_DRIVER;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_CHECKOUT_TIME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_IDLE_CONNECTIONS;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_MAX_WAIT_TIME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.DEFAULT_JDBC_URL_DATABASE_FILENAME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_DRIVER;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_ACTIVE_CONNECTIONS;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_CHECKOUT_TIME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_IDLE_CONNECTIONS;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_MAX_WAIT_TIME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_PASSWORD;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_URL;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.DBServer.JDBC_USERNAME;
import static org.ow2.petals.activitibpmn.ActivitiSEConstants.IntegrationOperation.ITG_OP_GETTASKS;
import java.io.File;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jbi.JBIException;
import javax.xml.namespace.QName;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.asyncexecutor.AsyncExecutor;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.transport.ConduitInitiatorManager;
import org.ow2.easywsdl.wsdl.api.Endpoint;
import org.ow2.easywsdl.wsdl.api.WSDLException;
import org.ow2.petals.activitibpmn.event.AbstractEventListener;
import org.ow2.petals.activitibpmn.event.ProcessInstanceCanceledEventListener;
import org.ow2.petals.activitibpmn.event.ProcessInstanceCompletedEventListener;
import org.ow2.petals.activitibpmn.event.ProcessInstanceStartedEventListener;
import org.ow2.petals.activitibpmn.event.ServiceTaskStartedEventListener;
import org.ow2.petals.activitibpmn.incoming.ActivitiService;
import org.ow2.petals.activitibpmn.incoming.integration.GetTasksOperation;
import org.ow2.petals.activitibpmn.incoming.integration.exception.OperationInitializationException;
import org.ow2.petals.activitibpmn.outgoing.PetalsSender;
import org.ow2.petals.activitibpmn.outgoing.cxf.transport.PetalsCxfTransportFactory;
import org.ow2.petals.component.framework.listener.AbstractListener;
import org.ow2.petals.component.framework.se.AbstractServiceEngine;
import org.ow2.petals.component.framework.su.AbstractServiceUnitManager;
import org.ow2.petals.component.framework.util.EndpointOperationKey;
import org.ow2.petals.component.framework.util.WSDLUtilImpl;
/**
* The component class of the Activiti BPMN Service Engine.
* @author Bertrand Escudie - Linagora
*/
public class ActivitiSE extends AbstractServiceEngine {
/**
* The Activiti BPMN Engine.
*/
private ProcessEngine activitiEngine;
/**
* A map used to get the Activiti Operation associated with (end-point Name + Operation)
*/
private final Map<EndpointOperationKey, ActivitiService> activitiServices = new ConcurrentHashMap<EndpointOperationKey, ActivitiService>();
/**
* An executor service to log MONIT trace about end of process instances
*/
private ScheduledExecutorService scheduledLogger = null;
/**
* Delay to wait before to log some MONIT traces
*/
// TODO: monitTraceDelay should be hot-changed
private int monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY;
/**
* Core size of the thread pool in charge of logging delayed MONIT traces
*/
// TODO: scheduledLoggerCoreSize should be hot-changed
private int scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE;
/**
* The Activiti Async Executor service
*/
private AsyncExecutor activitiAsyncExecutor = null;
/**
* Activation flag of the Activiti job executor
*/
private boolean enableActivitiJobExecutor = DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR;
/**
* Activation flag of the BPMN validation on process deployments into the Activiti engine
*/
private boolean enableActivitiBpmnValidation = DEFAULT_ENGINE_ENABLE_BPMN_VALIDATION;
/**
* Event listener fired when a process is started
*/
private AbstractEventListener processInstanceStartedEventListener;
/**
* Event listener fired when a process is completed
*/
private AbstractEventListener processInstanceCompletedEventListener;
/**
* Event listener fired when a process is canceled
*/
private AbstractEventListener processInstanceCanceledEventListener;
/**
* Event listener fired when a service task is started
*/
private AbstractEventListener serviceTaskStartedEventListener;
/**
* @return the Activiti Engine
*/
public ProcessEngine getProcessEngine() {
return this.activitiEngine;
}
/**
* @param eptAndOperation
* the end-point Name and operation Name
* @param activitiservice
* the Activiti service
* @return the map with the inserted elements
*/
public void registerActivitiService(final EndpointOperationKey eptAndOperation,
final ActivitiService activitiservice) {
this.activitiServices.put(eptAndOperation, activitiservice);
}
/**
* @param eptName
* the end-point name
*/
public void removeActivitiService(final String eptName) {
final Iterator<Entry<EndpointOperationKey, ActivitiService>> itEptOperationToActivitiOperation = this.activitiServices
.entrySet().iterator();
while (itEptOperationToActivitiOperation.hasNext()) {
final Entry<EndpointOperationKey, ActivitiService> entry = itEptOperationToActivitiOperation.next();
if (entry.getKey().getEndpointName().equals(eptName)) {
itEptOperationToActivitiOperation.remove();
}
}
}
/**
* @param logLevel
*/
public void logEptOperationToActivitiOperation(final Logger logger, final Level logLevel) {
if (logger.isLoggable(logLevel)) {
for (final Map.Entry<EndpointOperationKey, ActivitiService> entry : this.activitiServices.entrySet()) {
final EndpointOperationKey key = entry.getKey();
logger.log(logLevel, "*** Endpoint Operation ");
logger.log(logLevel, key.toString());
logger.log(logLevel, "
entry.getValue().log(logger, logLevel);
logger.log(logLevel, "******************* ");
}
}
}
/**
* @param eptAndOperation
* the end-point Name and operation Name
* @return the Activiti Service associated with this end-point name and operation Name
*/
public ActivitiService getActivitiServices(final EndpointOperationKey eptAndOperation) {
return this.activitiServices.get(eptAndOperation);
}
@Override
public void doInit() throws JBIException {
this.getLogger().fine("Start ActivitiSE.doInit()");
try {
// JDBC Driver
final String jdbcDriverConfigured = this.getComponentExtensions().get(JDBC_DRIVER);
final String jdbcDriver;
if (jdbcDriverConfigured == null || jdbcDriverConfigured.trim().isEmpty()) {
this.getLogger().info("No JDBC Driver configured for database. Default value used.");
jdbcDriver = DEFAULT_JDBC_DRIVER;
} else {
jdbcDriver = jdbcDriverConfigured;
}
// JDBC URL
final String jdbcUrlConfigured = this.getComponentExtensions().get(JDBC_URL);
final String jdbcUrl;
if (jdbcUrlConfigured == null || jdbcUrlConfigured.trim().isEmpty()) {
// $PETALS_HOME/data/repository/components/<se-bpmn>/h2-activiti.db
this.getLogger().info("No JDBC URL configured for database. Default value used.");
final File databaseFile = new File(this.getContext().getWorkspaceRoot(),
DEFAULT_JDBC_URL_DATABASE_FILENAME);
try {
jdbcUrl = String.format("jdbc:h2:%s", databaseFile.toURI().toURL().toExternalForm());
} catch (final MalformedURLException e) {
// This exception should not occur. It's a bug
throw new JBIException("The defaul JDBC URL is invalid !!", e);
}
} else {
jdbcUrl = jdbcUrlConfigured;
}
final String jdbcUsername = this.getComponentExtensions().get(JDBC_USERNAME);
final String jdbcPassword = this.getComponentExtensions().get(JDBC_PASSWORD);
final String jdbcMaxActiveConnectionsConfigured = this.getComponentExtensions().get(
JDBC_MAX_ACTIVE_CONNECTIONS);
int jdbcMaxActiveConnections;
if (jdbcMaxActiveConnectionsConfigured == null || jdbcMaxActiveConnectionsConfigured.trim().isEmpty()) {
this.getLogger().info("No JDBC Max Active Connections configured for database. Default value used.");
jdbcMaxActiveConnections = DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS;
} else {
try {
jdbcMaxActiveConnections = Integer.parseInt(jdbcMaxActiveConnectionsConfigured);
} catch (final NumberFormatException e) {
this.getLogger().warning(
"Invalid value for the number of JDBC Max Active Connections. Default value used.");
jdbcMaxActiveConnections = DEFAULT_JDBC_MAX_ACTIVE_CONNECTIONS;
}
}
final String jdbcMaxIdleConnectionsConfigured = this.getComponentExtensions()
.get(JDBC_MAX_IDLE_CONNECTIONS);
int jdbcMaxIdleConnections;
if (jdbcMaxIdleConnectionsConfigured == null || jdbcMaxIdleConnectionsConfigured.trim().isEmpty()) {
this.getLogger().info("No JDBC Max Idle Connections configured for database. Default value used.");
jdbcMaxIdleConnections = DEFAULT_JDBC_MAX_IDLE_CONNECTIONS;
} else {
try {
jdbcMaxIdleConnections = Integer.parseInt(jdbcMaxIdleConnectionsConfigured);
} catch (final NumberFormatException e) {
this.getLogger().warning(
"Invalid value for the number of JDBC Max Idle Connections. Default value used.");
jdbcMaxIdleConnections = DEFAULT_JDBC_MAX_IDLE_CONNECTIONS;
}
}
final String jdbcMaxCheckoutTimeConfigured = this.getComponentExtensions().get(JDBC_MAX_CHECKOUT_TIME);
int jdbcMaxCheckoutTime;
if (jdbcMaxCheckoutTimeConfigured == null || jdbcMaxCheckoutTimeConfigured.trim().isEmpty()) {
this.getLogger().info("No JDBC Max Checkout Time configured for database. Default value used.");
jdbcMaxCheckoutTime = DEFAULT_JDBC_MAX_CHECKOUT_TIME;
} else {
try {
jdbcMaxCheckoutTime = Integer.parseInt(jdbcMaxCheckoutTimeConfigured);
} catch (final NumberFormatException e) {
this.getLogger().warning(
"Invalid value for the number of JDBC Max Checkout Time. Default value used.");
jdbcMaxCheckoutTime = DEFAULT_JDBC_MAX_CHECKOUT_TIME;
}
}
final String jdbcMaxWaitTimeConfigured = this.getComponentExtensions().get(JDBC_MAX_WAIT_TIME);
int jdbcMaxWaitTime;
if (jdbcMaxWaitTimeConfigured == null || jdbcMaxWaitTimeConfigured.trim().isEmpty()) {
this.getLogger().info("No JDBC Max Wait Time configured for database. Default value used.");
jdbcMaxWaitTime = DEFAULT_JDBC_MAX_WAIT_TIME;
} else {
try {
jdbcMaxWaitTime = Integer.parseInt(jdbcMaxWaitTimeConfigured);
} catch (final NumberFormatException e) {
this.getLogger().warning("Invalid value for the number of JDBC Max Wait Time. Default value used.");
jdbcMaxWaitTime = DEFAULT_JDBC_MAX_WAIT_TIME;
}
}
/* DATABASE_TYPE Possible values: {h2, mysql, oracle, postgres, mssql, db2}. */
final String databaseType = this.getComponentExtensions().get(DATABASE_TYPE);
/* DATABASE_SCHEMA_UPDATE Possible values: {false, true, create-drop } */
final String databaseSchemaUpdate = this.getComponentExtensions().get(DATABASE_SCHEMA_UPDATE);
this.getLogger().config("DB configuration:");
this.getLogger().config(" - " + JDBC_DRIVER + " = " + jdbcDriver);
this.getLogger().config(" - " + JDBC_URL + " = " + jdbcUrl);
this.getLogger().config(" - " + JDBC_USERNAME + " = " + jdbcUsername);
this.getLogger().config(" - " + JDBC_PASSWORD + " = " + jdbcPassword);
this.getLogger().config(" - " + JDBC_MAX_ACTIVE_CONNECTIONS + " = " + jdbcMaxActiveConnections);
this.getLogger().config(" - " + JDBC_MAX_IDLE_CONNECTIONS + " = " + jdbcMaxIdleConnections);
this.getLogger().config(" - " + JDBC_MAX_CHECKOUT_TIME + " = " + jdbcMaxCheckoutTime);
this.getLogger().config(" - " + JDBC_MAX_WAIT_TIME + " = " + jdbcMaxWaitTime);
this.getLogger().config(" - " + DATABASE_TYPE + " = " + databaseType);
this.getLogger().config(" - " + DATABASE_SCHEMA_UPDATE + " = " + databaseSchemaUpdate);
// Caution:
// - only the value "false", ignoring case and spaces will disable the job executor,
// - only the value "true", ignoring case and spaces will enable the job executor,
// - otherwise, the default value is used.
final String enableActivitiJobExecutorConfigured = this.getComponentExtensions().get(
ENGINE_ENABLE_JOB_EXECUTOR);
if (enableActivitiJobExecutorConfigured == null || enableActivitiJobExecutorConfigured.trim().isEmpty()) {
this.getLogger().info(
"The activation of the Activiti job executor is not configured. Default value used.");
this.enableActivitiJobExecutor = DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR;
} else {
this.enableActivitiJobExecutor = enableActivitiJobExecutorConfigured.trim().equalsIgnoreCase("false") ? false
: (enableActivitiJobExecutorConfigured.trim().equalsIgnoreCase("true") ? true
: DEFAULT_ENGINE_ENABLE_JOB_EXECUTOR);
}
// Caution:
// - only the value "false", ignoring case and spaces will disable the BPMN validation,
// - only the value "true", ignoring case and spaces will enable the BPMN validation,
// - otherwise, the default value is used.
final String enableActivitiBpmnValidationConfigured = this.getComponentExtensions().get(
ENGINE_ENABLE_BPMN_VALIDATION);
if (enableActivitiBpmnValidationConfigured == null
|| enableActivitiBpmnValidationConfigured.trim().isEmpty()) {
this.getLogger()
.info("The activation of the BPMN validation during process deployments is not configured. Default value used.");
this.enableActivitiBpmnValidation = DEFAULT_ENGINE_ENABLE_BPMN_VALIDATION;
} else {
this.enableActivitiBpmnValidation = enableActivitiBpmnValidationConfigured.trim().equalsIgnoreCase(
"false") ? false
: (enableActivitiBpmnValidationConfigured.trim().equalsIgnoreCase("true") ? true
: DEFAULT_ENGINE_ENABLE_BPMN_VALIDATION);
}
this.getLogger().config("Activiti engine configuration:");
this.getLogger().config(" - " + ENGINE_ENABLE_JOB_EXECUTOR + " = " + this.enableActivitiJobExecutor);
this.getLogger()
.config(" - " + ENGINE_ENABLE_BPMN_VALIDATION + " = " + this.enableActivitiBpmnValidation);
final String monitTraceDelayConfigured = this.getComponentExtensions().get(MONIT_TRACE_DELAY);
if (monitTraceDelayConfigured == null || monitTraceDelayConfigured.trim().isEmpty()) {
this.getLogger().info("No MONIT trace delay configured. Default value used.");
this.monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY;
} else {
try {
this.monitTraceDelay = Integer.parseInt(monitTraceDelayConfigured);
} catch (final NumberFormatException e) {
this.getLogger().warning("Invalid value for the MONIT trace delay. Default value used.");
this.monitTraceDelay = DEFAULT_MONIT_TRACE_DELAY;
}
}
final String scheduledLoggerCoreSizeConfigured = this.getComponentExtensions().get(
SCHEDULED_LOGGER_CORE_SIZE);
if (scheduledLoggerCoreSizeConfigured == null || scheduledLoggerCoreSizeConfigured.trim().isEmpty()) {
this.getLogger()
.info("No core size of the thread pool in charge of logging MONIT traces is configured. Default value used.");
this.scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE;
} else {
try {
this.scheduledLoggerCoreSize = Integer.parseInt(scheduledLoggerCoreSizeConfigured);
} catch (final NumberFormatException e) {
this.getLogger()
.warning(
"Invalid value for the core size of the thread pool in charge of logging MONIT traces. Default value used.");
this.scheduledLoggerCoreSize = DEFAULT_SCHEDULED_LOGGER_CORE_SIZE;
}
}
this.getLogger().config("Other configuration parameters:");
this.getLogger().config(" - " + MONIT_TRACE_DELAY + " = " + this.monitTraceDelay);
this.getLogger().config(" - " + SCHEDULED_LOGGER_CORE_SIZE + " = " + this.scheduledLoggerCoreSize);
/* TODO Test Activiti database connection configuration */
/* TODO Test the Database Schema Version
* What about databaseSchemaUpdate values "true" and "create-drop"
*/
/* TODO Set the non set value with default value */
/* Create an Activiti ProcessEngine with database configuration */
final ProcessEngineConfiguration pec = ProcessEngineConfiguration
.createStandaloneProcessEngineConfiguration();
pec.setJdbcDriver(jdbcDriver);
pec.setJdbcUrl(jdbcUrl);
pec.setJdbcUsername(jdbcUsername).setJdbcPassword(jdbcPassword);
pec.setJdbcMaxActiveConnections(jdbcMaxActiveConnections);
pec.setJdbcMaxIdleConnections(jdbcMaxIdleConnections);
pec.setJdbcMaxCheckoutTime(jdbcMaxCheckoutTime);
pec.setJdbcMaxWaitTime(jdbcMaxWaitTime);
if (databaseType != null && !databaseType.trim().isEmpty()) {
pec.setDatabaseType(databaseType);
}
pec.setDatabaseSchemaUpdate(databaseSchemaUpdate);
pec.setJobExecutorActivate(false);
// We register the Petals transport into Apache CXF
this.registerCxfPetalsTransport();
// As recommended by Activiti team, we prefer the Async Job Executor
pec.setJobExecutorActivate(false);
// The Async job is enabled ...
pec.setAsyncExecutorEnabled(this.enableActivitiJobExecutor);
// ... but must be started when starting the SE
pec.setAsyncExecutorActivate(false);
this.activitiEngine = pec.buildProcessEngine();
this.activitiAsyncExecutor = this.enableActivitiJobExecutor ? pec.getAsyncExecutor() : null;
// Caution: Beans of the configuration are initialized when building the process engine
if (pec instanceof ProcessEngineConfigurationImpl) {
// We add to the BPMN engine the bean in charge of sending Petals message exchange
final AbstractListener petalsSender = new PetalsSender();
petalsSender.init(this);
((ProcessEngineConfigurationImpl) pec).getBeans().put(PETALS_SENDER_COMP_NAME, petalsSender);
} else {
this.getLogger().warning("The implementation of the process engine configuration is not the expected one ! No Petals services can be invoked !");
}
// Register integration operation
final List<Endpoint> integrationEndpoints = WSDLUtilImpl.getEndpointList(this.getNativeWsdl()
.getDescription());
if (integrationEndpoints.size() > 1) {
throw new JBIException("Unexpected endpoint number supporting integration services");
} else if (integrationEndpoints.size() == 1) {
try {
final Endpoint endpoint = integrationEndpoints.get(0);
final String integrationEndpointName = endpoint.getName();
final QName integrationInterfaceName = endpoint.getService().getInterface().getQName();
this.activitiServices
.put(new EndpointOperationKey(integrationEndpointName, integrationInterfaceName,
ITG_OP_GETTASKS),
new GetTasksOperation(this.activitiEngine.getTaskService(), this.activitiEngine
.getRepositoryService(), this.getLogger()));
} catch (final OperationInitializationException | WSDLException e) {
this.getLogger().log(Level.WARNING, "Integration operations are not completly initialized", e);
}
} else {
this.getLogger().warning("No endpoint exists to execute integration operations");
}
} catch( final ActivitiException e ) {
throw new JBIException( "An error occurred while creating the Activiti BPMN Engine.", e );
} finally {
this.getLogger().fine("End ActivitiSE.doInit()");
}
}
@Override
public void doStart() throws JBIException {
this.getLogger().fine("Start ActivitiSE.doStart()");
this.scheduledLogger = Executors.newScheduledThreadPool(this.scheduledLoggerCoreSize,
new ScheduledLoggerThreadFactory(ActivitiSE.this.getContext().getComponentName()));
// Create & Register event listeners
final RuntimeService runtimeService = this.activitiEngine.getRuntimeService();
this.processInstanceStartedEventListener = new ProcessInstanceStartedEventListener(this.getLogger());
runtimeService.addEventListener(this.processInstanceStartedEventListener,
this.processInstanceStartedEventListener.getListenEventType());
this.processInstanceCompletedEventListener = new ProcessInstanceCompletedEventListener(this.scheduledLogger,
this.monitTraceDelay, this.getLogger());
runtimeService.addEventListener(this.processInstanceCompletedEventListener,
this.processInstanceCompletedEventListener.getListenEventType());
this.processInstanceCanceledEventListener = new ProcessInstanceCanceledEventListener(this.scheduledLogger,
this.monitTraceDelay, this.getLogger());
runtimeService.addEventListener(this.processInstanceCanceledEventListener,
this.processInstanceCanceledEventListener.getListenEventType());
this.serviceTaskStartedEventListener = new ServiceTaskStartedEventListener(this.getLogger());
runtimeService.addEventListener(this.serviceTaskStartedEventListener,
this.serviceTaskStartedEventListener.getListenEventType());
try {
// Startup Activiti engine against running states of the SE:
// - Activiti Engine must be started when the SE is in state 'STOPPED' to be able to deploy process
// definitions
// - In state 'STOPPED', the SE will not process incoming requests, so no process instance creation and no
// user task completion will occur
// - To avoid the executions of activities trigerred by timer or other events, the Activiti job executor
// must be stopped when the SE is in state 'STOPPED'
if (this.enableActivitiJobExecutor) {
if (this.activitiAsyncExecutor != null) {
if (this.activitiAsyncExecutor.isActive()) {
this.getLogger().warning("Activiti Job Executor already started !!");
} else {
this.activitiAsyncExecutor.start();
}
} else {
this.getLogger().warning("No Activiti Job Executor exists !!");
}
} else {
this.getLogger().info("Activiti Job Executor not started because it is not activated.");
}
// TODO: Add JMX operation to start/stop the Activiti job executor when the component is started
// TODO: Add JMX operation to disable/enable the Activiti job executor when the component is running
} catch( final ActivitiException e ) {
throw new JBIException( "An error occurred while starting the Activiti BPMN Engine.", e );
} finally {
this.getLogger().fine("End ActivitiSE.doStart()");
}
}
@Override
public void doStop() throws JBIException {
this.getLogger().fine("Start ActivitiSE.doStop()");
try {
// Stop the Activiti Job Executor */
if (this.enableActivitiJobExecutor) {
if (this.activitiAsyncExecutor != null) {
if (this.activitiAsyncExecutor.isActive()) {
this.activitiAsyncExecutor.shutdown();
} else {
this.getLogger().warning("Activiti Job Executor not started !!");
}
} else {
this.getLogger().warning("No Activiti Job Executor exists !!");
}
} else {
this.getLogger().info("Activiti Job Executor not stopped because it is not activated.");
}
} catch (final ActivitiException e) {
throw new JBIException("An error occurred while stopping the Activiti BPMN Engine.", e);
} finally {
this.getLogger().fine("End ActivitiSE.doStop()");
}
// Deregister event listeners
final RuntimeService runtimeService = this.activitiEngine.getRuntimeService();
runtimeService.removeEventListener(this.processInstanceStartedEventListener);
runtimeService.removeEventListener(this.processInstanceCompletedEventListener);
runtimeService.removeEventListener(this.processInstanceCanceledEventListener);
runtimeService.removeEventListener(this.serviceTaskStartedEventListener);
try {
this.scheduledLogger.shutdown();
// TODO: The timeout should be configurable
this.scheduledLogger.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (final InterruptedException e) {
this.getLogger().log(Level.WARNING, "The termination of the scheduled logger was interrupted", e);
}
}
@Override
public void doShutdown() throws JBIException {
this.getLogger().fine("Start ActivitiSE.doShutdown()");
try {
this.activitiEngine.close();
} catch( final ActivitiException e ) {
throw new JBIException( "An error occurred while shutdowning the Activiti BPMN Engine.", e );
} finally {
this.getLogger().fine("End ActivitiSE.doShutdown()");
}
}
@Override
protected AbstractServiceUnitManager createServiceUnitManager() {
return new ActivitiSuManager(this, this.enableActivitiBpmnValidation);
}
private void registerCxfPetalsTransport() {
final Bus bus = BusFactory.getThreadDefaultBus();
final PetalsCxfTransportFactory cxfPetalsTransport = new PetalsCxfTransportFactory();
final ConduitInitiatorManager extension = bus.getExtension(ConduitInitiatorManager.class);
extension.registerConduitInitiator(PetalsCxfTransportFactory.TRANSPORT_ID, cxfPetalsTransport);
// TODO: Set a timeout at CXF client level (it should be the same than the tiemout at NMR level)
// TODO: Add unit tests about timeout
}
} |
package org.sahagin.runlib.srctreegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.jdt.core.dom.IAnnotationBinding;
import org.eclipse.jdt.core.dom.IMemberValuePairBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.sahagin.runlib.external.CaptureStyle;
import org.sahagin.runlib.external.Locale;
import org.sahagin.runlib.external.Page;
import org.sahagin.runlib.external.Pages;
import org.sahagin.runlib.external.TestDoc;
import org.sahagin.runlib.external.TestDocs;
import org.sahagin.share.AcceptableLocales;
public class ASTUtils {
// Get the method annotation whose class name is equals to annotationClass canonical name.
// Return null if specified name annotation is not found.
public static IAnnotationBinding getAnnotationBinding(
IAnnotationBinding[] annotations, String annotationClassName) {
if (annotations == null) {
return null;
}
if (annotationClassName == null) {
throw new NullPointerException();
}
for (IAnnotationBinding annotation : annotations) {
String qName = annotation.getAnnotationType().getBinaryName();
assert qName != null;
if (qName.equals(annotationClassName)) {
return annotation;
}
}
return null;
}
// Get the method annotation whose class equals to annotationClass.
// Return null if specified name annotation is not found.
private static IAnnotationBinding getAnnotationBinding(
IAnnotationBinding[] annotations, Class<?> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException();
}
return getAnnotationBinding(annotations, annotationClass.getCanonicalName());
}
// returns null if specified varName annotation is not found
private static Object getAnnotationValue(IAnnotationBinding annotation, String varName) {
if (annotation == null) {
throw new NullPointerException();
}
if (varName == null) {
throw new NullPointerException();
}
for (IMemberValuePairBinding value : annotation.getDeclaredMemberValuePairs()) {
if (value.getName() != null && value.getName().equals(varName)) {
assert value.getValue() != null; // annotation value cannot be null
assert !(value.getValue() instanceof IVariableBinding);
return value.getValue();
}
}
return null;
}
// - for example, returns string "STEP_IN" for CaptureStyle.STEP_IN
// returns null if specified varName annotation is not found
private static String getEnumAnnotationFieldName(IAnnotationBinding annotation, String varName) {
if (annotation == null) {
throw new NullPointerException();
}
if (varName == null) {
throw new NullPointerException();
}
for (IMemberValuePairBinding value : annotation.getDeclaredMemberValuePairs()) {
if (value.getName() != null && value.getName().equals(varName)) {
assert value.getValue() != null; // annotation value cannot be null
assert value.getValue() instanceof IVariableBinding;
IVariableBinding varBinding = (IVariableBinding) value.getValue();
assert varBinding.isEnumConstant();
return varBinding.getName();
}
}
return null;
}
// returns default value if varName value is not specified
private static CaptureStyle getAnnotationCaptureStyleValue(
IAnnotationBinding annotation, String varName) {
String fieldName = getEnumAnnotationFieldName(annotation, varName);
if (fieldName == null) {
return CaptureStyle.getDefault();
}
CaptureStyle resultCaptureStyle = CaptureStyle.valueOf(fieldName);
if (resultCaptureStyle == null) {
throw new RuntimeException("invalid captureStyle: " + fieldName);
}
return resultCaptureStyle;
}
// returns default value if varName value is not specified
private static Locale getAnnotationLocaleValue(
IAnnotationBinding annotation, String varName) {
String fieldName = getEnumAnnotationFieldName(annotation, varName);
if (fieldName == null) {
return Locale.getDefault();
}
Locale resultLocale = Locale.valueOf(fieldName);
if (resultLocale == null) {
throw new RuntimeException("invalid locale: " + fieldName);
}
return resultLocale;
}
// return empty list and null pair if no TestDoc is found
private static Pair<Map<Locale, String>, CaptureStyle> getAllTestDocs(
IAnnotationBinding[] annotations) {
IAnnotationBinding testDocAnnotation = getAnnotationBinding(annotations, TestDoc.class);
IAnnotationBinding testDocsAnnotation = getAnnotationBinding(annotations, TestDocs.class);
if (testDocAnnotation != null && testDocsAnnotation != null) {
throw new RuntimeException("don't use @TestDoc and @TestDocs at the same place");
}
// all testDoc value on @TestDoc and @TestDocs
List<IAnnotationBinding> allTestDocAnnotations = new ArrayList<IAnnotationBinding>(2);
CaptureStyle resultCaptureStyle = null;
if (testDocAnnotation != null) {
// get @TestDoc
allTestDocAnnotations.add(testDocAnnotation);
resultCaptureStyle = getAnnotationCaptureStyleValue(testDocAnnotation, "capture");
} else if (testDocsAnnotation != null) {
// get @TestDoc from @TestDocs
Object value = getAnnotationValue(testDocsAnnotation, "value");
Object[] values = (Object[]) value;
for (Object element : values) {
IAnnotationBinding binding = (IAnnotationBinding) element;
if (getEnumAnnotationFieldName(binding, "capture") != null) {
throw new RuntimeException(
"capture must be set on not @TestDoc but @TestDocs");
}
allTestDocAnnotations.add(binding);
}
resultCaptureStyle = getAnnotationCaptureStyleValue(testDocsAnnotation, "capture");
}
// get resultTestDocMap
Map<Locale, String> resultTestDocMap
= new HashMap<Locale, String>(allTestDocAnnotations.size());
for (IAnnotationBinding eachTestDocAnnotation : allTestDocAnnotations) {
Object value = getAnnotationValue(eachTestDocAnnotation, "value");
Locale locale = getAnnotationLocaleValue(eachTestDocAnnotation, "locale");
resultTestDocMap.put(locale, (String) value);
}
return Pair.of(resultTestDocMap, resultCaptureStyle);
}
// return empty list and null pair if no Page is found
private static Map<Locale, String> getAllPageTestDocs(
IAnnotationBinding[] annotations) {
IAnnotationBinding pageAnnotation = getAnnotationBinding(annotations, Page.class);
IAnnotationBinding pagesAnnotation = getAnnotationBinding(annotations, Pages.class);
if (pageAnnotation != null && pagesAnnotation != null) {
throw new RuntimeException("don't use @Page and @Pages at the same place");
}
// all testDoc value on @Page and @Pages
List<IAnnotationBinding> allPageAnnotations = new ArrayList<IAnnotationBinding>(2);
if (pageAnnotation != null) {
// get @Page
allPageAnnotations.add(pageAnnotation);
} else if (pagesAnnotation != null) {
// get @Page from @Pages
Object value = getAnnotationValue(pagesAnnotation, "value");
Object[] values = (Object[]) value;
for (Object element : values) {
allPageAnnotations.add((IAnnotationBinding) element);
}
}
// get resultPageMap
Map<Locale, String> resultPageMap
= new HashMap<Locale, String>(allPageAnnotations.size());
for (IAnnotationBinding eachPageAnnotation : allPageAnnotations) {
Object value = getAnnotationValue(eachPageAnnotation, "value");
Locale locale = getAnnotationLocaleValue(eachPageAnnotation, "locale");
resultPageMap.put(locale, (String) value);
}
return resultPageMap;
}
// first... value
// second... captureStyle value.
// return null pair if no TestDoc is found
private static Pair<String, CaptureStyle> getTestDoc(
IAnnotationBinding[] annotations, AcceptableLocales locales) {
Pair<Map<Locale, String>, CaptureStyle> allTestDocs = getAllTestDocs(annotations);
Map<Locale, String> testDocMap = allTestDocs.getLeft();
if (testDocMap.isEmpty()) {
return Pair.of(null, null); // no @TestDoc found
}
String testDoc = null;
for (Locale locale : locales.getLocales()) {
String value = testDocMap.get(locale);
if (value != null) {
testDoc = value;
break;
}
}
if (testDoc == null) {
// set empty string if no locale matched data is found
return Pair.of("", allTestDocs.getRight());
} else {
return Pair.of(testDoc, allTestDocs.getRight());
}
}
// return null if no Page found
private static String getPageTestDoc(
IAnnotationBinding[] annotations, AcceptableLocales locales) {
Map<Locale, String> allPages = getAllPageTestDocs(annotations);
if (allPages.isEmpty()) {
return null; // no @Page found
}
for (Locale locale : locales.getLocales()) {
String value = allPages.get(locale);
if (value != null) {
return value;
}
}
// set empty string if no locale matched data is found
return "";
}
// return null if not found
public static String getPageTestDoc(ITypeBinding type, AcceptableLocales locales) {
return getPageTestDoc(type.getAnnotations(), locales);
}
// return null if not found
public static String getTestDoc(ITypeBinding type, AcceptableLocales locales) {
Pair<String, CaptureStyle> pair = getTestDoc(type.getAnnotations(), locales);
return pair.getLeft();
}
// return null pair if not found
public static Pair<String, CaptureStyle> getTestDoc(
IMethodBinding method, AcceptableLocales locales) {
return getTestDoc(method.getAnnotations(), locales);
}
public static String getTestDoc(
IVariableBinding variable, AcceptableLocales locales) {
return getTestDoc(variable.getAnnotations(), locales).getLeft();
}
} |
package com.googlecode.jmxtrans.model.output;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.util.BaseOutputWriter;
import com.googlecode.jmxtrans.util.ValidationException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class OpenTSDBWriter extends BaseOutputWriter {
private static final Logger log = LoggerFactory.getLogger(OpenTSDBWriter.class);
private String host;
private Integer port;
private Map<String, String> tags;
private String tagName;
String addTags(String resultString) throws UnknownHostException {
resultString = addTag(resultString, "host", java.net.InetAddress.getLocalHost().getHostName());
if (tags != null)
for (Map.Entry<String, String> tagEntry : tags.entrySet()) {
resultString = addTag(resultString, tagEntry.getKey(), tagEntry.getValue());
}
return resultString;
}
String addTag(String resultString, String tagName, String tagValue) {
String tagFormat = " %s=%s";
resultString += String.format(tagFormat, tagName, tagValue);
return resultString;
}
String getResultString(String className, String attributeName, long epoch, Object value) {
String resultStringFormat = "put %s.%s %d %s";
return String.format(resultStringFormat, className, attributeName, epoch, value);
}
String getResultString(String className, String attributeName, long epoch, Object value, String tagName, String tagValue) {
String taggedResultStringFormat = "put %s.%s %d %s %s=%s";
return String.format(taggedResultStringFormat, className, attributeName, epoch, value, tagName, tagValue);
}
List<String> resultParser(Result result) throws UnknownHostException {
List<String> resultStrings = new LinkedList<String>();
Map<String, Object> values = result.getValues();
if (values == null)
return resultStrings;
String attributeName = result.getAttributeName();
String className = result.getClassNameAlias() == null ? result.getClassName() : result.getClassNameAlias();
if (values.containsKey(attributeName) && values.size() == 1) {
String resultString = getResultString(className, attributeName, (long)(result.getEpoch()/1000L), values.get(attributeName));
resultString = addTags(resultString);
if (getTypeNames().size() > 0) {
resultString = addTag(resultString, StringUtils.join(getTypeNames(), ""), getConcatedTypeNameValues(result.getTypeName()));
}
resultStrings.add(resultString);
} else {
for (Map.Entry<String, Object> valueEntry: values.entrySet() ) {
String resultString = getResultString(className, attributeName, (long)(result.getEpoch()/1000L), valueEntry.getValue(), tagName, valueEntry.getKey());
resultString = addTags(resultString);
if (getTypeNames().size() > 0) {
resultString = addTag(resultString, StringUtils.join(getTypeNames(), ""), getConcatedTypeNameValues(result.getTypeName()));
}
resultStrings.add(resultString);
}
}
return resultStrings;
}
@Override
public void doWrite(Query query) throws Exception {
Socket socket = new Socket(host, port);
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
for (Result result : query.getResults()) {
for(String resultString: resultParser(result)) {
if (isDebugEnabled())
System.out.println(resultString);
out.writeBytes(resultString + "\n");
}
}
socket.close();
}
@Override
public void validateSetup(Query query) throws ValidationException {
host = (String) this.getSettings().get(HOST);
port = (Integer) this.getSettings().get(PORT);
tags = (Map<String, String>) this.getSettings().get("tags");
tagName = this.getStringSetting("tagName", "type");
}
} |
package com.hp.hpl.jena.db.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.util.iterator.MapFiller;
import com.hp.hpl.jena.util.iterator.MapMany;
/**
* @author hkuno
* @version $Version$
*
* TripleStoreGraph is an abstract superclass for TripleStoreGraph
* implementations. By "triple store," we mean that the subjects, predicate
* and object URI's are stored in a single collection (denormalized).
*
*/
public class SpecializedGraphReifier_RDB implements SpecializedGraphReifier {
/**
* holds PSet
*/
public IPSet m_pset;
/**
* caches a copy of LSet properties
*/
public DBPropLSet m_dbPropLSet;
/**
* holds ID of graph in database (defaults to "0")
*/
public IDBID my_GID = new DBIDInt(0);
// lset name
private String m_lsetName;
// lset classname
private String m_className;
// cache of reified statement status
private ReifCacheMap m_reifCache;
public PSet_ReifStore_RDB m_reif;
// constructors
/**
* Constructor
* Create a new instance of a TripleStore graph.
*/
SpecializedGraphReifier_RDB(DBPropLSet lProp, IPSet pSet) {
m_pset = pSet;
m_dbPropLSet = lProp;
m_reifCache = new ReifCacheMap(1);
m_reif = (PSet_ReifStore_RDB) m_pset;
}
/**
* Constructor
*
* Create a new instance of a TripleStore graph, taking
* DBPropLSet and a PSet as arguments
*/
public SpecializedGraphReifier_RDB(IPSet pSet) {
m_pset = pSet;
m_reifCache = new ReifCacheMap(1);
m_reif = (PSet_ReifStore_RDB) m_pset;
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#add(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void add(Node n, Triple t, CompletionFlag complete) throws Reifier.AlreadyReifiedException {
ReifCache rs = m_reifCache.load((Node_URI) t.getSubject());
if (rs != null)
throw new Reifier.AlreadyReifiedException(n);
m_reif.storeReifStmt(n, t, my_GID);
complete.setDone();
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#delete(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void delete(Node n, Triple t, CompletionFlag complete) {
m_reifCache.flushAll();
m_reif.deleteReifStmt( n, t, my_GID);
complete.setDone();
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#contains(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public boolean contains(Node n, Triple t, CompletionFlag complete) {
if ( true )
throw new RuntimeException("SpecializedGraphReifier.contains called");
return false;
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#findReifiedNodes(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public ExtendedIterator findReifiedNodes(Triple t, CompletionFlag complete) {
complete.setDone();
return m_reif.findReifStmtURIByTriple(t, my_GID);
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#findReifiedTriple(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public Triple findReifiedTriple(Node n, CompletionFlag complete) {
ExtendedIterator it = m_reif.findReifStmt(n, true, my_GID);
Triple res = null;
if ( it.hasNext() ) {
List l = (List) it.next();
if ( !it.hasNext() )
res = new Triple((Node)l.get(1), (Node)l.get(2), (Node)l.get(3));
}
complete.setDone();
return res;
}
/** Find all the triples corresponding to a given reified node.
* In a perfect world, there would only ever be one, but when a user calls
* add(Triple) there is nothing in RDF that prevents them from adding several
* subjects,predicates or objects for the same statement.
*
* The resulting Triples may be incomplete, in which case some of the
* nodes may be Node_ANY.
*
* For example, if an application had previously done:
* add( new Triple( a, rdf.subject A )) and
* add( new Triple( a, rdf.object B )) and
* add( new Triple( a, rdf.object B2 ))
*
* Then the result of findReifiedTriple(a, flag) will be an iterator containing
* Triple(A, ANY, B) and Triple(ANY, ANY, B2).
*
* @param n is the Node for which we are querying.
* @param complete is true if we know we've returned all the triples which may exist.
* @return ExtendedIterator.
*/
public ExtendedIterator findReifiedTriples(Node n, CompletionFlag complete) {
complete.setDone();
return m_reif.findReifStmt(n, false, my_GID);
}
/**
* Attempt to add all the triples from a graph to the specialized graph
*
* Caution - this call changes the graph passed in, deleting from
* it each triple that is successfully added.
*
* Node that when calling add, if complete is true, then the entire
* graph was added successfully and the graph g will be empty upon
* return. If complete is false, then some triples in the graph could
* not be added. Those triples remain in g after the call returns.
*
* If the triple can't be stored for any reason other than incompatability
* (for example, a lack of disk space) then the implemenation should throw
* a runtime exception.
*
* @param g is a graph containing triples to be added
* @param complete is true if a subsequent call to contains(triple) will return true for any triple in g.
*/
public void add(Graph g, CompletionFlag complete) {
throw new RuntimeException("sorry, not implemented");
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#add(com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void add(Triple frag, CompletionFlag complete) throws Reifier.AlreadyReifiedException {
StmtMask fragMask = new StmtMask(frag);
if (fragMask.hasNada())
return;
boolean fragHasType = fragMask.hasType();
Node stmtURI = frag.getSubject();
ReifCache cachedFrag = m_reifCache.load(stmtURI);
if (cachedFrag == null) {
// not in database
m_reif.storeFrag(stmtURI, frag, fragMask, my_GID);
complete.setDone();
} else {
StmtMask cachedMask = cachedFrag.getStmtMask();
if (cachedMask.hasIntersect(fragMask)) {
// see if this is a duplicate fragment
boolean dup = fragHasType && cachedMask.hasType();
if (dup == false) {
// not a type fragement; have to search db
ExtendedIterator it = m_reif.findFrag (stmtURI, frag, fragMask, my_GID);
dup = it.hasNext();
}
if (!dup && cachedMask.isStmt()) {
throw new Reifier.AlreadyReifiedException(frag.getSubject());
}
// cannot perform a reificiation
m_reif.storeFrag(stmtURI, frag, fragMask, my_GID);
m_reifCache.flush(cachedFrag);
} else {
// reification may be possible; update if possible, else compact
if (cachedFrag.canMerge(fragMask)) {
if ( cachedFrag.canUpdate(fragMask) ) {
m_reif.updateFrag(stmtURI, frag, fragMask, my_GID);
cachedFrag.setMerge(fragMask);
} else
fragCompact(stmtURI);
} else {
// reification not possible
m_reif.storeFrag(stmtURI, frag, fragMask, my_GID);
}
}
}
complete.setDone();
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#delete(com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void delete(Triple frag, CompletionFlag complete) {
StmtMask fragMask = new StmtMask(frag);
if (fragMask.hasNada())
return;
boolean fragHasType = fragMask.hasType();
Node stmtURI = frag.getSubject();
ResultSetTripleIterator it = m_reif.findFrag(stmtURI, frag, fragMask, my_GID);
if ( it.hasNext() ) {
it.next();
Triple dbFrag = it.m_triple;
StmtMask dbMask = new StmtMask(dbFrag);
if ( dbMask.equals(fragMask) ) {
/* last fragment in this tuple; can just delete it */
it.deleteRow(); it.close();
} else {
/* remove fragment from row */
m_reif.nullifyFrag(stmtURI, fragMask, my_GID);
/* compact remaining fragments, if possible */
it.close();
fragCompact(stmtURI);
}
// remove cache entry, if any
ReifCache cachedFrag = m_reifCache.lookup(stmtURI);
if ( cachedFrag != null ) m_reifCache.flush(cachedFrag);
}
complete.setDone();
}
/* fragCompact
*
* Compact fragments for a given statement URI.
*
* first, find the unique row for stmtURI that with the HasType Statement fragment.
* if no such row exists, we are done. then, get all fragments for stmtURI and
* try to merge them with the hasType fragment, deleting each as they are merged.
*/
protected void fragCompact ( Node stmtURI ) {
ResultSetTripleIterator itHasType;
itHasType = m_reif.findReifStmt(stmtURI,true,my_GID);
if ( itHasType.hasNext() ) {
/* something to do */
itHasType.next();
if ( itHasType.hasNext() ) throw new RuntimeException("Multiple HasType fragments for URI");
StmtMask htMask = new StmtMask(itHasType.m_triple);
itHasType.close();
// now, look at fragments and try to merge them with the hasType fragement
ResultSetTripleIterator itFrag = m_reif.findReifStmt(stmtURI,false,my_GID);
StmtMask upMask = new StmtMask();
while ( itFrag.hasNext() ) {
StmtMask fm = new StmtMask(itFrag.m_triple);
if ( fm.hasType() ) continue; // got the hasType fragment again
if ( htMask.hasIntersect(fm) )
break; // can't merge all fragments
// at this point, we can merge in the current fragment
m_reif.updateFrag(stmtURI, itFrag.m_triple, fm, my_GID);
htMask.setMerge(fm);
itFrag.deleteRow();
}
}
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#add(java.util.List, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void add(List triples, CompletionFlag complete) {
ArrayList remainingTriples = new ArrayList();
for( int i=0; i< triples.size(); i++) {
CompletionFlag partialResult = new CompletionFlag();
add( (Triple)triples.get(i), partialResult);
if( !partialResult.isDone())
remainingTriples.add(triples.get(i));
}
triples.clear();
if( remainingTriples.isEmpty())
complete.setDone();
else
triples.addAll(remainingTriples);
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#delete(java.util.List, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public void delete(List triples, CompletionFlag complete) {
boolean result = true;
Iterator it = triples.iterator();
while(it.hasNext()) {
CompletionFlag partialResult = new CompletionFlag();
delete( (Triple)it.next(), partialResult);
result = result && partialResult.isDone();
}
if( result )
complete.setDone();
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#tripleCount()
*/
public int tripleCount() {
// A very inefficient, but simple implementation
ExtendedIterator it = find(new StandardTripleMatch(null, null, null), new CompletionFlag());
int count = 0;
while (it.hasNext()) {
count++;
}
it.close();
return count;
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#find(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag)
*/
public ExtendedIterator find(TripleMatch t, CompletionFlag complete) {
Node stmtURI = t.getSubject(); // note: can be null
ExtendedIterator nodes = m_reif.findReifNodes(stmtURI, my_GID);
ExtendedIterator allTriples = new MapMany(nodes, new ExpandReifiedTriples(this));
return allTriples.filterKeep(new TripleMatchFilter(t));
}
public class ExpandReifiedTriples implements MapFiller {
SpecializedGraphReifier_RDB m_sgr;
ExpandReifiedTriples( SpecializedGraphReifier_RDB sgr) {
m_sgr = sgr;
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.util.iterator.MapFiller#refill(java.lang.Object, java.util.ArrayList)
*/
public boolean refill(Object x, ArrayList pending) {
Node node = (Node) x;
boolean addedToPending = false;
ResultSetTripleIterator it = m_reif.findReifStmt(node, false, my_GID);
while( it.hasNext()) {
it.next();
if ( it.getHasType() ) {
pending.add( new Triple( node, Reifier.type, Reifier.Statement ));
addedToPending = true;
}
Triple t = (Triple)it.getRow();
if( !t.getSubject().equals(Node.ANY)) {
pending.add( new Triple( node, Reifier.subject, t.getSubject() ));
addedToPending = true;
}
if( !t.getPredicate().equals(Node.ANY)) {
pending.add( new Triple( node, Reifier.predicate, t.getPredicate() ));
addedToPending = true;
}
if( !t.getObject().equals(Node.ANY)) {
pending.add( new Triple( node, Reifier.object, t.getObject() ));
addedToPending = true;
}
}
return addedToPending;
}
}
/**
* Tests if a triple is contained in the specialized graph.
* @param t is the triple to be tested
* @param complete is true if the graph can guarantee that
* no other specialized graph
* could hold any matching triples.
* @return boolean result to indicte if the tripple was contained
*/
public boolean contains(Triple t, CompletionFlag complete) {
// A very inefficient, but simple implementation
TripleMatch m = new StandardTripleMatch(t.getSubject(), t.getPredicate(), t.getObject());
ExtendedIterator it = find(m, complete);
boolean result = it.hasNext();
it.close();
return result;
}
/*
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#getLSetName()
*/
public String getLSetName() {
return m_lsetName;
}
/*
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#getClassName()
*/
public String getClassName() {
return m_className;
}
/*
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#close()
*/
public void close() {
m_reif.close();
}
/*
* @see com.hp.hpl.jena.db.impl.SpecializedGraph#clear()
*/
public void clear() {
m_reif.removeStatementsFromDB(my_GID);
}
public class ReifCacheMap {
protected int cacheSize = 1;
protected ReifCache[] cache;
protected boolean[] inUse;
ReifCacheMap(int size) {
int i;
inUse = new boolean[size];
for (i = 0; i < size; i++)
inUse[i] = false;
}
ReifCache lookup(Node stmtURI) {
int i;
for (i = 0; i < cacheSize; i++) {
if (inUse[i] && (cache[i].getStmtURI().equals(stmtURI)))
return cache[i];
}
return null;
}
public void flushAll() {
int i;
for (i = 0; i < cacheSize; i++)
inUse[i] = false;
}
public void flush(ReifCache entry) {
flushAll(); // optimize later
}
public ReifCache load(Node stmtURI) {
ReifCache entry = lookup(stmtURI);
if (entry != null)
return entry;
flushAll();
StmtMask m = new StmtMask();
Triple t;
int cnt = 0;
ResultSetTripleIterator it = m_reif.findReifStmt(stmtURI,false,my_GID);
while (it.hasNext()) {
cnt++;
StmtMask n = new StmtMask((Triple) it.next());
if ( it.getHasType() ) n.setHasType();
if ( n.hasNada() ) throw new RuntimeException("Fragment has no data");
m.setMerge(n);
}
if (m.hasSPOT() && (cnt == 1))
m.setIsStmt();
inUse[0] = true;
cache[0] = new ReifCache(stmtURI, m, cnt);
return cache[0];
}
protected Triple fragToTriple(Triple t, StmtMask s) {
Triple res;
Node_URI n = (Node_URI) t.getSubject();
if (s.hasProp())
return new Triple(n, t.getPredicate(), Node.ANY);
else if (s.hasObj())
return new Triple(n, Node.ANY, t.getObject());
else
return new Triple(n, Node.ANY, Node.ANY);
}
}
class ReifCache {
protected Node stmtURI;
protected StmtMask mask;
protected int tripleCnt;
ReifCache( Node s, StmtMask m, int cnt )
{ stmtURI = s; mask = m; tripleCnt = cnt; }
public StmtMask getStmtMask() { return mask; }
public int getCnt() { return tripleCnt; }
public Node getStmtURI() { return stmtURI; }
public void setMask ( StmtMask m ) { mask = m; }
public void setCnt ( int cnt ) { tripleCnt = cnt; }
public void incCnt ( int cnt ) { tripleCnt++; }
public void decCnt ( int cnt ) { tripleCnt
public boolean canMerge ( StmtMask fragMask ) {
return (!mask.hasIntersect(fragMask)); }
public boolean canUpdate ( StmtMask fragMask ) {
return ( canMerge(fragMask) && (tripleCnt == 1)); }
public void setMerge ( StmtMask fragMask ) {
mask.setMerge(fragMask); }
}
static boolean isReifProp ( Node_URI p ) {
return p.equals(Reifier.subject) ||
p.equals(Reifier.predicate)||
p.equals(Reifier.object) ||
p.equals(Reifier.type);
}
class StmtMask {
protected int mask;
public static final int HasSubj = 1;
public static final int HasProp = 2;
public static final int HasObj = 4;
public static final int HasType = 8;
public static final int HasSPOT = 15;
public static final int IsStmt = 16;
public static final int HasNada = 0;
public boolean hasSubj () { return (mask ^ HasSubj) == HasSubj; };
public boolean hasProp () { return (mask ^ HasProp) == HasProp; };
public boolean hasObj () { return (mask ^ HasObj) == HasObj; };
public boolean hasType () { return (mask ^ HasType) == HasType; };
public boolean hasSPOT () { return (mask ^ HasSPOT) == HasSPOT; };
public boolean isStmt () { return (mask ^ IsStmt) == IsStmt; };
public boolean hasNada () { return mask == HasNada; };
public boolean hasOneBit () { return ( (mask == HasSubj) ||
(mask == HasProp) || (mask == HasObj) || ( mask == HasType) );
}
// note: have SPOT does not imply a reification since
// 1) there may be multiple fragments for prop, obj
// 2) the fragments may be in multiple tuples
StmtMask ( Triple t ) {
mask = HasNada;
Node_URI p = (Node_URI) t.getPredicate();
if ( p != null ) {
if ( p.equals(Reifier.subject) ) mask = HasSubj;
else if ( p.equals(Reifier.predicate) ) mask = HasProp;
else if ( p.equals(Reifier.object) ) mask = HasObj;
else if ( p.equals(Reifier.type) ) {
Node_URI o = (Node_URI) t.getObject();
if ( o.equals(Reifier.Statement) ) mask = HasType;
}
}
}
StmtMask () { mask = HasNada; };
public void setMerge ( StmtMask m ) {
mask |= m.mask;
}
public void setHasType () {
mask |= HasType;
}
public void setIsStmt () {
mask |= IsStmt;
}
public boolean hasIntersect ( StmtMask m ) {
return (mask & m.mask) != 0;
}
public boolean equals ( StmtMask m ) {
return mask == m.mask;
}
}
} |
package org.spongepowered.api.entity;
import com.flowpowered.math.imaginary.Quaterniond;
import com.flowpowered.math.matrix.Matrix4d;
import com.flowpowered.math.vector.Vector3d;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
public interface Transform {
static Transform of(World world) {
return Sponge.getRegistry().requireFactory(Factory.class).create(Location.of(world, Vector3d.ZERO), Vector3d.ZERO, Vector3d.ONE);
}
static Transform of(Location location) {
return Sponge.getRegistry().requireFactory(Factory.class).create(location, Vector3d.ZERO, Vector3d.ONE);
}
static Transform of(World world, Vector3d position) {
return Sponge.getRegistry().requireFactory(Factory.class).create(Location.of(world, position), Vector3d.ZERO, Vector3d.ONE);
}
static Transform of(World world, Vector3d position, Vector3d rotation) {
return Sponge.getRegistry().requireFactory(Factory.class).create(Location.of(world, position), rotation, Vector3d.ONE);
}
static Transform of(Location location, Vector3d rotation, Vector3d scale) {
return Sponge.getRegistry().requireFactory(Factory.class).create(location, rotation, scale);
}
boolean isValid();
Location getLocation();
/**
* Creates a copy of this transform and sets the {@link Location}.
*
* @param location The new location
* @return A new transform
*/
Transform withLocation(Location location);
World getWorld();
/**
* Creates a copy of this transform and sets the {@link World}.
*
* @param world The new world
* @return A new transform
*/
Transform withWorld(World world);
/**
* Gets the coordinates of this transform.
*
* @return The coordinates
*/
Vector3d getPosition();
/**
* Creates a copy of this transform while setting the position of the new
* one.
*
* @param position The position
* @return A new transform
*/
Transform withPosition(Vector3d position);
/**
* Gets the rotation of this transform, as a {@link Vector3d}.
*
* <p>The format of the rotation is represented by:</p>
* <ul>
* <li><code>x -> pitch</code></li>
* <li><code>y -> yaw</code></li>
* <li><code>z -> roll</code></li>
* </ul>
*
* @return The rotation vector
*/
Vector3d getRotation();
/**
* Creates a copy of this transform and sets the rotation as a quaternion.
*
* <p>Quaternions are objectively better than the Euler angles preferred by
* Minecraft. This is for compatibility with the flow-math library.</p>
*
* @param rotation The new rotation
* @return A new transform
*/
Transform withRotation(Vector3d rotation);
/**
* Creates a copy of this transform and sets the rotation.
*
* <p>The format of the rotation is represented by:</p>
* <ul>
* <li><code>x -> pitch</code></li>
* <li><code>y -> yaw</code></li>
* <li><code>z -> roll</code></li>
* </ul>
*
* @param rotation The new rotation
* @return A new transform
*/
Transform withRotation(Quaterniond rotation);
/**
* Returns the rotation as a quaternion.
*
* <p>Quaternions are objectively better than the Euler angles preferred by
* Minecraft. This is for compatibility with the flow-math library.</p>
*
* @return The rotation
*/
Quaterniond getRotationAsQuaternion();
/**
* Gets the pitch component of this transform rotation.
*
* @return The pitch
*/
double getPitch();
/**
* Gets the yaw component of this transform rotation.
*
* @return The yaw
*/
double getYaw();
/**
* Gets the roll component of this transform rotation.
*
* @return The roll
*/
double getRoll();
/**
* Gets the scale of the transform for each axis.
*
* @return The scale
*/
Vector3d getScale();
/**
* Creates a copy of this transform and sets the scale for each axis.
*
* @param scale The scale
* @return A new transform
*/
Transform withScale(Vector3d scale);
/**
* "Adds" another transform to this one. This is equivalent to adding the
* translation, rotation and scale individually.
*
* <p>Returns the results as a new copy.</p>
*
* @param other The transform to add
* @return A new transform
*/
Transform add(Transform other);
/**
* Adds a translation to this transform.
*
* <p>Returns the results as a new copy.</p>
*
* @param translation The translation to add
* @return A new transform
*/
Transform translate(Vector3d translation);
/**
* Adds a rotation to this transform. Returns the results as a new copy.
*
* @param rotation The rotation to add
* @return A new transform
*/
Transform rotate(Vector3d rotation);
/**
* Adds a rotation to this transform.
*
* <p>Quaternions are objectively better than the Euler angles preferred by
* Minecraft. This is the preferred method when dealing with rotation
* additions. This is for compatibility with the flow-math library.</p>
*
* <p>Returns the results as a new copy.</p>
*
* @param rotation The rotation to add
* @return A new transform
*/
Transform rotate(Quaterniond rotation);
/**
* "Adds" a scale to this transform. Scales are multiplicative, so this
* actually multiplies the current scale.
*
* <p>Returns the results as a new copy.</p>
*
* @param scale The scale to add
* @return A new transform
*/
Transform scale(Vector3d scale);
/**
* Returns a matrix representation of this transform.
*
* <p>This includes the position, rotation and scale. To apply the transform
* to a vector, use the following:</p>
*
* <blockquote><code>Vector3d original = ...;<br />
* Transform transform = ...;<br /><br />
* Vector3d transformed =
* transform.toMatrix().transform(original.toVector4(1)).toVector3();<br />
* }</code></blockquote>
*
* <p>This converts the original 3D vector to 4D by appending 1 as the w
* coordinate, applies the transformation, then converts it back to 3D by
* dropping the w coordinate.</p>
*
* <p>Using a 4D matrix and a w coordinate with value 1 is what allows for
* the position to be included in the transformation applied by the matrix.
* </p>
*
* @return The transform as a matrix
*/
Matrix4d toMatrix();
interface Factory {
Transform create(Location location, Vector3d rotation, Vector3d scale);
}
} |
package com.michaldabski.filemanager.folders;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
import com.michaldabski.filemanager.AppPreferences;
import com.michaldabski.filemanager.FileManagerApplication;
import com.michaldabski.filemanager.R;
import com.michaldabski.filemanager.clipboard.Clipboard;
import com.michaldabski.filemanager.clipboard.Clipboard.FileAction;
import com.michaldabski.filemanager.clipboard.FileOperationListener;
import com.michaldabski.filemanager.favourites.FavouriteFolder;
import com.michaldabski.filemanager.favourites.FavouritesManager;
import com.michaldabski.filemanager.favourites.FavouritesManager.FolderAlreadyFavouriteException;
import com.michaldabski.filemanager.folders.FileAdapter.OnFileSelectedListener;
import com.michaldabski.utils.AsyncResult;
import com.michaldabski.utils.FilePreviewCache;
import com.michaldabski.utils.FileUtils;
import com.michaldabski.utils.FontApplicator;
import com.michaldabski.utils.IntentUtils;
import com.michaldabski.utils.ListViewUtils;
import com.michaldabski.utils.OnResultListener;
public class FolderFragment extends Fragment implements OnItemClickListener, OnScrollListener, OnItemLongClickListener, MultiChoiceModeListener, OnFileSelectedListener
{
private static final String LOG_TAG = "FolderFragment";
private final int DISTANCE_TO_HIDE_ACTIONBAR = 0;
public static final String
EXTRA_DIR = "directory",
EXTRA_SELECTED_FILES = "selected_files",
EXTRA_SCROLL_POSITION = "scroll_position";
File currentDir,
nextDir = null;
int topVisibleItem=0;
List<File> files = null;
@SuppressWarnings("rawtypes")
AsyncTask loadFilesTask=null;
ListView listView = null;
FileAdapter fileAdapter;
private ActionMode actionMode = null;
private final HashSet<File> selectedFiles = new HashSet<File>();
private ShareActionProvider shareActionProvider;
// set to true when selection shouldnt be cleared from switching out fragments
boolean preserveSelection = false;
FilePreviewCache thumbCache;
public ListView getListView()
{
return listView;
}
private void setListAdapter(FileAdapter fileAdapter)
{
this.fileAdapter = fileAdapter;
if (listView != null)
{
listView.setAdapter(fileAdapter);
listView.setSelection(topVisibleItem);
getView().findViewById(R.id.layoutMessage).setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
}
}
FontApplicator getFontApplicator()
{
FolderActivity folderActivity = (FolderActivity) getActivity();
return folderActivity.getFontApplicator();
}
void showProgress()
{
if (getView() != null)
{
getListView().setVisibility(View.GONE);
getView().findViewById(R.id.layoutMessage).setVisibility(View.VISIBLE);
getView().findViewById(R.id.tvMessage).setVisibility(View.GONE);
}
}
FileManagerApplication getApplication()
{
if (getActivity() == null) return null;
return (FileManagerApplication) getActivity().getApplication();
}
AppPreferences getPreferences()
{
if (getApplication() == null) return null;
return getApplication().getAppPreferences();
}
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
Log.d(LOG_TAG, "Fragment created");
if (savedInstanceState != null)
{
this.topVisibleItem = savedInstanceState.getInt(EXTRA_SCROLL_POSITION, 0);
this.selectedFiles.addAll((HashSet<File>) savedInstanceState.getSerializable(EXTRA_SELECTED_FILES));
}
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(EXTRA_DIR))
currentDir = new File(arguments.getString(EXTRA_DIR));
else
currentDir = getPreferences().getStartFolder();
setHasOptionsMenu(true);
loadFileList();
}
void showMessage(CharSequence message)
{
View view = getView();
if (view != null)
{
getListView().setVisibility(View.GONE);
view.findViewById(R.id.layoutMessage).setVisibility(View.VISIBLE);
view.findViewById(R.id.progress).setVisibility(View.GONE);
TextView tvMessage = (TextView) view.findViewById(R.id.tvMessage);
tvMessage.setText(message);
}
}
void showMessage(int message)
{
showMessage(getString(message));
}
void showList()
{
getListView().setVisibility(View.VISIBLE);
getView().findViewById(R.id.layoutMessage).setVisibility(View.GONE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_list, container, false);
this.listView = (ListView) view.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
listView.setFastScrollAlwaysVisible(true);
return view;
}
@Override
public void onLowMemory()
{
super.onLowMemory();
if (thumbCache != null)
{
if (getView() == null) thumbCache.evictAll();
else thumbCache.trimToSize(1024*1024);
}
}
void loadFileList()
{
if (loadFilesTask != null) return;
this.loadFilesTask = new AsyncTask<File, Void, AsyncResult<File[]>>()
{
@Override
protected AsyncResult<File[]> doInBackground(File... params)
{
try
{
File[] files =params[0].listFiles(FileUtils.DEFAULT_FILE_FILTER);
if (files == null)
throw new NullPointerException(getString(R.string.cannot_read_directory_s, params[0].getName()));
if (isCancelled())
throw new Exception("Task cancelled");
Arrays.sort(files, getPreferences().getFileSortingComparator());
return new AsyncResult<File[]>(files);
}
catch (Exception e)
{
return new AsyncResult<File[]>(e);
}
}
@Override
protected void onCancelled(AsyncResult<File[]> result)
{
loadFilesTask = null;
}
@Override
protected void onPostExecute(AsyncResult<File[]> result)
{
Log.d("folder fragment", "Task finished");
loadFilesTask = null;
FileAdapter adapter;
try
{
files = Arrays.asList(result.getResult());
if (files.isEmpty())
{
showMessage(R.string.folder_empty);
return;
}
adapter = new FileAdapter(getActivity(), files, getApplication().getFileIconResolver());
final int cardPreference = getPreferences().getCardLayout();
if (cardPreference == AppPreferences.CARD_LAYOUT_ALWAYS || (cardPreference == AppPreferences.CARD_LAYOUT_MEDIA && FileUtils.isMediaDirectory(currentDir)))
{
if (thumbCache == null) thumbCache = new FilePreviewCache();
adapter = new FileCardAdapter(getActivity(), files, thumbCache, getApplication().getFileIconResolver());
}
else adapter = new FileAdapter(getActivity(), files, getApplication().getFileIconResolver());
adapter.setSelectedFiles(selectedFiles);
adapter.setOnFileSelectedListener(FolderFragment.this);
adapter.setFontApplicator(getFontApplicator());
setListAdapter(adapter);
} catch (Exception e)
{
// exception was thrown while loading files
showMessage(e.getMessage());
adapter = new FileAdapter(getActivity(), getApplication().getFileIconResolver());
}
getActivity().invalidateOptionsMenu();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, currentDir);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.folder_browser, menu);
menu.findItem(R.id.menu_selectAll).setVisible(!(files == null || files.isEmpty()));
if (getApplication().getFavouritesManager().isFolderFavourite(currentDir))
{
menu.findItem(R.id.menu_unfavourite).setVisible(true);
menu.findItem(R.id.menu_favourite).setVisible(false);
}
else
{
menu.findItem(R.id.menu_unfavourite).setVisible(false);
menu.findItem(R.id.menu_favourite).setVisible(true);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.menu_paste).setVisible(Clipboard.getInstance().isEmpty() == false);
menu.findItem(R.id.menu_navigate_up).setVisible(currentDir.getParentFile() != null);
}
void showEditTextDialog(int title, int okButtonText, final OnResultListener<CharSequence> enteredTextResult, CharSequence hint, CharSequence defaultValue)
{
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_edittext, (ViewGroup) getActivity().getWindow().getDecorView(), false);
final EditText editText = (EditText) view.findViewById(android.R.id.edit);
editText.setHint(hint);
editText.setText(defaultValue);
if (TextUtils.isEmpty(defaultValue) == false)
{
int end = defaultValue.toString().indexOf('.');
if (end > 0) editText.setSelection(0, end);
}
final Dialog dialog = new AlertDialog.Builder(getActivity())
.setTitle(title)
.setView(view)
.setPositiveButton(okButtonText, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
enteredTextResult.onResult(new AsyncResult<CharSequence>(editText.getText()));
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.show();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_selectAll:
selectFiles(this.files);
return true;
case R.id.menu_navigate_up:
String newFolder = currentDir.getParent();
if (newFolder != null)
{
Bundle args = new Bundle(1);
args.putString(EXTRA_DIR, newFolder);
FolderFragment fragment = new FolderFragment();
fragment.setArguments(args);
FolderActivity activity = (FolderActivity) getActivity();
activity.showFragment(fragment);
}
return true;
case R.id.menu_favourite:
try
{
final String directoryName = FileUtils.getFolderDisplayName(currentDir);
FavouritesManager favouritesManager = getApplication().getFavouritesManager();
favouritesManager.addFavourite(new FavouriteFolder(currentDir, directoryName));
getActivity().invalidateOptionsMenu();
} catch (FolderAlreadyFavouriteException e1)
{
e1.printStackTrace();
}
return true;
case R.id.menu_unfavourite:
FavouritesManager favouritesManager = getApplication().getFavouritesManager();
favouritesManager.removeFavourite(currentDir);
getActivity().invalidateOptionsMenu();
return true;
case R.id.menu_create_folder:
showEditTextDialog(R.string.create_folder, R.string.create, new OnResultListener<CharSequence>()
{
@Override
public void onResult(AsyncResult<CharSequence> result)
{
try
{
String name = result.getResult().toString();
File newFolder = new File(currentDir, name);
if (newFolder.mkdirs())
{
refreshFolder();
Toast.makeText(getActivity(), R.string.folder_created_successfully, Toast.LENGTH_SHORT).show();
navigateTo(newFolder);
}
else Toast.makeText(getActivity(), R.string.folder_could_not_be_created, Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, "", "");
return true;
case R.id.menu_paste:
pasteFiles();
return true;
case R.id.menu_refresh:
refreshFolder();
return true;
}
return super.onOptionsItemSelected(item);
}
public void pasteFiles()
{
new AsyncTask<Clipboard, Float, Exception>()
{
ProgressDialog progressDialog;
@Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(getActivity().getString(R.string.pasting_files_));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
@Override
protected void onProgressUpdate(Float... values)
{
float progress = values[0];
progressDialog.setMax(100);
progressDialog.setProgress((int) (progress * 100));
}
@Override
protected Exception doInBackground(Clipboard... params)
{
try
{
final int total = FileUtils.countFilesIn(params[0].getFiles());
final int[] progress = {0};
params[0].paste(currentDir, new FileOperationListener()
{
@Override
public void onFileProcessed(String filename)
{
progress[0]++;
publishProgress((float)progress[0] / (float)total);
}
@Override
public boolean isOperationCancelled()
{
return isCancelled();
}
});
return null;
} catch (IOException e)
{
e.printStackTrace();
return e;
}
}
@Override
protected void onCancelled() {
progressDialog.dismiss();
refreshFolder();
};
@Override
protected void onPostExecute(Exception result) {
progressDialog.dismiss();
refreshFolder();
if (result == null)
{
Clipboard.getInstance().clear();
Toast.makeText(getActivity(), R.string.files_pasted, Toast.LENGTH_SHORT).show();
}
else
{
new AlertDialog.Builder(getActivity())
.setMessage(result.getMessage())
.setPositiveButton(android.R.string.ok, null)
.show();
}
};
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Clipboard.getInstance());
}
@Override
public void onViewCreated(View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getFontApplicator().applyFont(view);
loadFileList();
if (selectedFiles.isEmpty() == false)
{
selectFiles(selectedFiles);
}
final String directoryName = FileUtils.getFolderDisplayName(currentDir);
getActivity().setTitle(directoryName);
getListView().setOnItemClickListener(FolderFragment.this);
getListView().setOnScrollListener(this);
getListView().setOnItemLongClickListener(this);
getListView().setMultiChoiceModeListener(this);
getActivity().getActionBar().setSubtitle(FileUtils.getUserFriendlySdcardPath(currentDir));
if (topVisibleItem <= DISTANCE_TO_HIDE_ACTIONBAR)
setActionbarVisibility(true);
// add listview header to push items below the actionbar
ListViewUtils.addListViewHeader(getListView(), getActivity());
if (fileAdapter != null)
setListAdapter(fileAdapter);
FolderActivity activity = (FolderActivity) getActivity();
activity.setLastFolder(currentDir);
}
@Override
public void onDestroyView()
{
finishActionMode(true);
listView = null;
super.onDestroyView();
}
@Override
public void onDestroy()
{
if (loadFilesTask != null)
loadFilesTask.cancel(true);
if (thumbCache != null)
thumbCache.evictAll();
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_SCROLL_POSITION, topVisibleItem);
outState.putSerializable(EXTRA_SELECTED_FILES, selectedFiles);
}
void navigateTo(File folder)
{
nextDir = folder;
FolderActivity activity = (FolderActivity) getActivity();
FolderFragment fragment = new FolderFragment();
Bundle args = new Bundle();
args.putString(EXTRA_DIR, folder.getAbsolutePath());
fragment.setArguments(args);
activity.showFragment(fragment);
}
void openFile(File file)
{
if (file.isDirectory())
throw new IllegalArgumentException("File cannot be a directory!");
Intent intent = IntentUtils.createFileOpenIntent(file);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException e)
{
startActivity(Intent.createChooser(intent, getString(R.string.open_file_with_, file.getName())));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity())
.setMessage(e.getMessage())
.setTitle(R.string.error)
.setPositiveButton(android.R.string.ok, null)
.show();
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3)
{
Object selectedObject = adapterView.getItemAtPosition(position);
if (selectedObject instanceof File)
{
if (actionMode == null)
{
File selectedFile = (File) selectedObject;
if (selectedFile.isDirectory())
navigateTo(selectedFile);
else
openFile(selectedFile);
}
else
{
toggleFileSelected((File) selectedObject);
}
}
}
void setActionbarVisibility(boolean visible)
{
if (actionMode == null || visible == true) // cannot hide CAB
((FolderActivity) getActivity()).setActionbarVisible(visible);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
if (firstVisibleItem < this.topVisibleItem - DISTANCE_TO_HIDE_ACTIONBAR)
{
setActionbarVisibility(true);
this.topVisibleItem = firstVisibleItem;
}
else if (firstVisibleItem > this.topVisibleItem + DISTANCE_TO_HIDE_ACTIONBAR)
{
setActionbarVisibility(false);
this.topVisibleItem = firstVisibleItem;
}
ListAdapter adapter = view.getAdapter();
if (adapter instanceof HeaderViewListAdapter)
{
HeaderViewListAdapter headerViewListAdapter = (HeaderViewListAdapter) adapter;
if (headerViewListAdapter.getWrappedAdapter() instanceof FileCardAdapter)
{
int startPrefetch = firstVisibleItem + visibleItemCount-headerViewListAdapter.getHeadersCount();
((FileCardAdapter) headerViewListAdapter.getWrappedAdapter()).prefetchImages(startPrefetch, visibleItemCount);
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
setFileSelected((File) arg0.getItemAtPosition(arg2), true);
return true;
}
void showFileInfo(Collection<File> files)
{
final CharSequence title;
final StringBuilder message = new StringBuilder();
if (files.size() == 1) title = ((File) files.toArray()[0]).getName();
else title = getString(R.string._d_objects, files.size());
if (files.size() > 1)
message.append(FileUtils.combineFileNames(files)).append("\n\n");
message.append(getString(R.string.size_s, FileUtils.formatFileSize(files))).append('\n');
message.append(getString(R.string.mime_type_s, FileUtils.getCollectiveMimeType(files)));
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_delete:
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.delete_d_items_, selectedFiles.size()))
.setPositiveButton(R.string.delete, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
int n = FileUtils.deleteFiles(selectedFiles);
Toast.makeText(getActivity(), getString(R.string._d_files_deleted, n), Toast.LENGTH_SHORT).show();
refreshFolder();
finishActionMode(false);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
case R.id.action_selectAll:
if (isEverythingSelected()) clearFileSelection();
else selectFiles(files);
return true;
case R.id.action_info:
if (selectedFiles.isEmpty()) return true;
showFileInfo(selectedFiles);
return true;
case R.id.action_copy:
Clipboard.getInstance().addFiles(selectedFiles, FileAction.Copy);
Toast.makeText(getActivity(), R.string.objects_copied_to_clipboard, Toast.LENGTH_SHORT).show();
finishActionMode(false);
return true;
case R.id.action_cut:
Clipboard clipboard = Clipboard.getInstance();
clipboard.addFiles(selectedFiles, FileAction.Cut);
Toast.makeText(getActivity(), R.string.objects_cut_to_clipboard, Toast.LENGTH_SHORT).show();
finishActionMode(false);
return true;
case R.id.action_rename:
final File fileToRename = (File) selectedFiles.toArray()[0];
showEditTextDialog(fileToRename.isDirectory()?R.string.rename_folder:R.string.rename_file, R.string.rename, new OnResultListener<CharSequence>()
{
@Override
public void onResult(AsyncResult<CharSequence> result)
{
try
{
String newName = result.getResult().toString();
if (fileToRename.renameTo(new File(fileToRename.getParentFile(), newName)))
{
finishActionMode(false);
refreshFolder();
Toast.makeText(getActivity(), R.string.file_renamed, Toast.LENGTH_SHORT).show();
}
else Toast.makeText(getActivity(), getActivity().getString(R.string.file_could_not_be_renamed_to_s, newName), Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, fileToRename.getName(), fileToRename.getName());
return true;
case R.id.menu_add_homescreen_icon:
for (File file : selectedFiles)
IntentUtils.createShortcut(getActivity(), file);
Toast.makeText(getActivity(), R.string.shortcut_created, Toast.LENGTH_SHORT).show();
actionMode.finish();
return true;
}
return false;
}
protected void refreshFolder()
{
showProgress();
loadFileList();
}
void updateActionMode()
{
if (actionMode != null)
{
actionMode.invalidate();
int count = selectedFiles.size();
actionMode.setTitle(getString(R.string._d_objects, count));
actionMode.setSubtitle(FileUtils.combineFileNames(selectedFiles));
if (shareActionProvider != null)
{
final Intent shareIntent;
if (selectedFiles.isEmpty()) shareIntent = null;
else if (selectedFiles.size() == 1)
{
File file = (File) selectedFiles.toArray()[0];
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType(FileUtils.getFileMimeType(file));
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
else
{
ArrayList<Uri> fileUris = new ArrayList<Uri>(selectedFiles.size());
for (File file : selectedFiles) if (file.isDirectory() == false)
{
fileUris.add(Uri.fromFile(file));
}
shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, fileUris);
shareIntent.setType(FileUtils.getCollectiveMimeType(selectedFiles));
}
shareActionProvider.setShareIntent(shareIntent);
}
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu)
{
setActionbarVisibility(true);
getActivity().getMenuInflater().inflate(R.menu.action_file, menu);
MenuItem shareMenuItem = menu.findItem(R.id.action_share);
shareActionProvider = (ShareActionProvider) shareMenuItem.getActionProvider();
this.preserveSelection = false;
return true;
}
void finishSelection()
{
if (listView != null)
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
clearFileSelection();
}
void finishActionMode(boolean preserveSelection)
{
this.preserveSelection = preserveSelection;
if (actionMode != null)
actionMode.finish();
}
@Override
public void onDestroyActionMode(ActionMode mode)
{
actionMode = null;
shareActionProvider = null;
if (preserveSelection == false)
finishSelection();
Log.d(LOG_TAG, "Action mode destroyed");
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu)
{
int count = selectedFiles.size();
if (count == 1)
{
menu.findItem(R.id.action_rename).setVisible(true);
menu.findItem(R.id.menu_add_homescreen_icon).setTitle(R.string.add_to_homescreen);
}
else
{
menu.findItem(R.id.action_rename).setVisible(false);
menu.findItem(R.id.menu_add_homescreen_icon).setTitle(R.string.add_to_homescreen_multiple);
}
// show Share button if no folder was selected
boolean allowShare = (count > 0);
if (allowShare)
{
for (File file : selectedFiles) if (file.isDirectory())
{
allowShare = false;
break;
}
}
menu.findItem(R.id.action_share).setVisible(allowShare);
return true;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked)
{
}
void toggleFileSelected(File file)
{
setFileSelected(file, !selectedFiles.contains(file));
}
void clearFileSelection()
{
if (listView != null)
listView.clearChoices();
selectedFiles.clear();
updateActionMode();
if (fileAdapter != null)
fileAdapter.notifyDataSetChanged();
Log.d(LOG_TAG, "Selection cleared");
}
boolean isEverythingSelected()
{
return selectedFiles.size() == files.size();
}
void selectFiles(Collection<File> files)
{
if (files == null || files.isEmpty()) return;
if (actionMode == null)
{
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
actionMode = getActivity().startActionMode(this);
}
selectedFiles.addAll(files);
updateActionMode();
if (fileAdapter != null)
fileAdapter.notifyDataSetChanged();
}
void setFileSelected(File file, boolean selected)
{
if (actionMode == null)
{
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
actionMode = getActivity().startActionMode(this);
}
if (selected)
selectedFiles.add(file);
else
selectedFiles.remove(file);
updateActionMode();
if (fileAdapter != null)
fileAdapter.notifyDataSetChanged();
if (selectedFiles.isEmpty())
finishActionMode(false);
}
@Override
public void onFileSelected(File file)
{
toggleFileSelected(file);
}
} |
package org.testng.reporters;
import org.testng.IInvokedMethod;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestClass;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.collections.Lists;
import org.testng.internal.Utils;
import org.testng.log4testng.Logger;
import org.testng.reporters.util.StackTraceTools;
import org.testng.xml.XmlSuite;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Reported designed to render self-contained HTML top down view of a testing
* suite.
*
* @author Paul Mendelson
* @since 5.2
* @version $Revision: 719 $
*/
public class EmailableReporter implements IReporter {
private static final Logger L = Logger.getLogger(EmailableReporter.class);
private PrintWriter m_out;
private int m_row;
private int m_methodIndex;
private int m_rowTotal;
/** Creates summary of the run */
@Override
public void generateReport(List<XmlSuite> xml, List<ISuite> suites, String outdir) {
try {
m_out = createWriter(outdir);
}
catch (IOException e) {
L.error("output file", e);
return;
}
startHtml(m_out);
generateSuiteSummaryReport(suites);
generateMethodSummaryReport(suites);
generateMethodDetailReport(suites);
endHtml(m_out);
m_out.flush();
m_out.close();
}
protected PrintWriter createWriter(String outdir) throws IOException {
new File(outdir).mkdirs();
return new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir,
"emailable-report.html"))));
}
/** Creates a table showing the highlights of each test method with links to the method details */
protected void generateMethodSummaryReport(List<ISuite> suites) {
m_methodIndex = 0;
m_out.println("<a id=\"summary\"></a>");
startResultSummaryTable("passed");
for (ISuite suite : suites) {
if(suites.size()>1) {
titleRow(suite.getName(), 4);
}
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
String testName = testContext.getName();
resultSummary(suite, testContext.getFailedConfigurations(), testName,
"failed", " (configuration methods)");
resultSummary(suite, testContext.getFailedTests(), testName, "failed",
"");
resultSummary(suite, testContext.getSkippedConfigurations(), testName,
"skipped", " (configuration methods)");
resultSummary(suite, testContext.getSkippedTests(), testName,
"skipped", "");
resultSummary(suite, testContext.getPassedTests(), testName, "passed",
"");
}
}
m_out.println("</table>");
}
/** Creates a section showing known results for each method */
protected void generateMethodDetailReport(List<ISuite> suites) {
m_methodIndex = 0;
for (ISuite suite : suites) {
Map<String, ISuiteResult> r = suite.getResults();
for (ISuiteResult r2 : r.values()) {
ITestContext testContext = r2.getTestContext();
if (r.values().size() > 0) {
m_out.println("<h1>" + testContext.getName() + "</h1>");
}
resultDetail(testContext.getFailedConfigurations());
resultDetail(testContext.getFailedTests());
resultDetail(testContext.getSkippedConfigurations());
resultDetail(testContext.getSkippedTests());
resultDetail(testContext.getPassedTests());
}
}
}
/**
* @param tests
*/
private void resultSummary(ISuite suite, IResultMap tests, String testname, String style,
String details) {
if (tests.getAllResults().size() > 0) {
StringBuffer buff = new StringBuffer();
String lastClassName = "";
int mq = 0;
int cq = 0;
for (ITestNGMethod method : getMethodSet(tests, suite)) {
m_row += 1;
m_methodIndex += 1;
ITestClass testClass = method.getTestClass();
String className = testClass.getName();
if (mq == 0) {
titleRow(testname + " — " + style + details, 4);
}
if (!className.equalsIgnoreCase(lastClassName)) {
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style
+ (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td rowspan=\""
+ mq + "\">" + lastClassName + buff);
}
mq = 0;
buff.setLength(0);
lastClassName = className;
}
Set<ITestResult> resultSet = tests.getResults(method);
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
for (ITestResult testResult : tests.getResults(method)) {
if (testResult.getEndMillis() > end) {
end = testResult.getEndMillis();
}
if (testResult.getStartMillis() < start) {
start = testResult.getStartMillis();
}
}
mq += 1;
if (mq > 1) {
buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even")
+ "\">");
}
String description = method.getDescription();
String testInstanceName = resultSet.toArray(new ITestResult[]{})[0].getTestName();
buff.append("<td><a href=\"#m" + m_methodIndex + "\">"
+ qualifiedName(method)
+ " " + (description != null && description.length() > 0
? "(\"" + description + "\")"
: "")
+ "</a>" + (null == testInstanceName ? "" : "<br>(" + testInstanceName + ")")
+ "</td>"
+ "<td class=\"numi\">" + resultSet.size() + "</td>"
+ "<td>" + start + "</td>"
+ "<td class=\"numi\">" + (end - start) + "</td>"
+ "</tr>");
}
if (mq > 0) {
cq += 1;
m_out.println("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")
+ "\">" + "<td rowspan=\"" + mq + "\">" + lastClassName + buff);
}
}
}
/** Starts and defines columns result summary table */
private void startResultSummaryTable(String style) {
tableStart(style);
m_out.println("<tr><th>Class</th>"
+ "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");
m_row = 0;
}
private String qualifiedName(ITestNGMethod method) {
StringBuilder addon = new StringBuilder();
String[] groups = method.getGroups();
int length = groups.length;
if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {
addon.append("(");
for (int i = 0; i < length; i++) {
if (i > 0) {
addon.append(", ");
}
addon.append(groups[i]);
}
addon.append(")");
}
return "<b>" + method.getMethodName() + "</b> " + addon;
}
private void resultDetail(IResultMap tests) {
for (ITestResult result : tests.getAllResults()) {
ITestNGMethod method = result.getMethod();
m_methodIndex++;
String cname = method.getTestClass().getName();
m_out.println("<a id=\"m" + m_methodIndex + "\"></a><h2>" + cname + ":"
+ method.getMethodName() + "</h2>");
Set<ITestResult> resultSet = tests.getResults(method);
generateForResult(result, method, resultSet.size());
m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");
}
}
private void generateForResult(ITestResult ans, ITestNGMethod method, int resultSetSize) {
int rq = 0;
rq += 1;
Object[] parameters = ans.getParameters();
boolean hasParameters = parameters != null && parameters.length > 0;
if (hasParameters) {
if (rq == 1) {
tableStart("param");
m_out.print("<tr>");
for (int x = 1; x <= parameters.length; x++) {
m_out
.print("<th style=\"padding-left:1em;padding-right:1em\">Parameter
+ x + "</th>");
}
m_out.println("</tr>");
}
m_out.print("<tr" + (rq % 2 == 0 ? " class=\"stripe\"" : "") + ">");
for (Object p : parameters) {
m_out.println("<td style=\"padding-left:.5em;padding-right:2em\">"
+ (p != null ? Utils.escapeHtml(p.toString()) : "null") + "</td>");
}
m_out.println("</tr>");
}
List<String> msgs = Reporter.getOutput(ans);
boolean hasReporterOutput = msgs.size() > 0;
Throwable exception=ans.getThrowable();
boolean hasThrowable = exception!=null;
if (hasReporterOutput||hasThrowable) {
String indent = " style=\"padding-left:3em\"";
if (hasParameters) {
m_out.println("<tr" + (rq % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td" + indent + " colspan=\"" + parameters.length + "\">");
}
else {
m_out.println("<div" + indent + ">");
}
if (hasReporterOutput) {
if(hasThrowable) {
m_out.println("<h3>Test Messages</h3>");
}
for (String line : msgs) {
m_out.println(line + "<br/>");
}
}
if(hasThrowable) {
boolean wantsMinimalOutput = ans.getStatus()==ITestResult.SUCCESS;
if(hasReporterOutput) {
m_out.println("<h3>"
+(wantsMinimalOutput?"Expected Exception":"Failure")
+"</h3>");
}
generateExceptionReport(exception,method);
}
if (hasParameters) {
m_out.println("</td></tr>");
}
else {
m_out.println("</div>");
}
}
if (hasParameters) {
if (rq == resultSetSize) {
m_out.println("</table>");
}
}
}
protected void generateExceptionReport(Throwable exception,ITestNGMethod method) {
generateExceptionReport(exception, method, exception.getLocalizedMessage());
}
private void generateExceptionReport(Throwable exception,ITestNGMethod method,String title) {
m_out.println("<p>" + Utils.escapeHtml(title) + "</p>");
StackTraceElement[] s1= exception.getStackTrace();
Throwable t2= exception.getCause();
if(t2 == exception) {
t2= null;
}
int maxlines= Math.min(100,StackTraceTools.getTestRoot(s1, method));
for(int x= 0; x <= maxlines; x++) {
m_out.println((x>0 ? "<br/>at " : "") + Utils.escapeHtml(s1[x].toString()));
}
if(maxlines < s1.length) {
m_out.println("<br/>" + (s1.length-maxlines) + " lines not shown");
}
if(t2 != null) {
generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage());
}
}
/**
* @param tests
* @param suite
* @return
*/
private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {
List<IInvokedMethod> r = Lists.newArrayList();
List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();
for (IInvokedMethod im : invokedMethods) {
if (tests.getAllMethods().contains(im.getTestMethod())) {
r.add(im);
}
}
Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());
List<ITestNGMethod> result = Lists.newArrayList();
for (IInvokedMethod m : r) {
result.add(m.getTestMethod());
}
return result;
}
public void generateSuiteSummaryReport(List<ISuite> suites) {
tableStart("param");
m_out.print("<tr><th>Test</th>");
tableColumnStart("Methods<br/>Passed");
tableColumnStart("Scenarios<br/>Passed");
tableColumnStart("# skipped");
tableColumnStart("# failed");
tableColumnStart("Total<br/>Time");
tableColumnStart("Included<br/>Groups");
tableColumnStart("Excluded<br/>Groups");
m_out.println("</tr>");
NumberFormat formatter = new DecimalFormat("
int qty_tests = 0;
int qty_pass_m = 0;
int qty_pass_s = 0;
int qty_skip = 0;
int qty_fail = 0;
long time_start = Long.MAX_VALUE;
long time_end = Long.MIN_VALUE;
for (ISuite suite : suites) {
if (suites.size() > 1) {
titleRow(suite.getName(), 7);
}
Map<String, ISuiteResult> tests = suite.getResults();
for (ISuiteResult r : tests.values()) {
qty_tests += 1;
ITestContext overview = r.getTestContext();
startSummaryRow(overview.getName());
int q = getMethodSet(overview.getPassedTests(), suite).size();
qty_pass_m += q;
summaryCell(q,Integer.MAX_VALUE);
q = overview.getPassedTests().size();
qty_pass_s += q;
summaryCell(q,Integer.MAX_VALUE);
q = getMethodSet(overview.getSkippedTests(), suite).size();
qty_skip += q;
summaryCell(q,0);
q = getMethodSet(overview.getFailedTests(), suite).size();
qty_fail += q;
summaryCell(q,0);
time_start = Math.min(overview.getStartDate().getTime(), time_start);
time_end = Math.max(overview.getEndDate().getTime(), time_end);
summaryCell(formatter.format(
(overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.)
+ " seconds", true);
summaryCell(overview.getIncludedGroups());
summaryCell(overview.getExcludedGroups());
m_out.println("</tr>");
}
}
if (qty_tests > 1) {
m_out.println("<tr class=\"total\"><td>Total</td>");
summaryCell(qty_pass_m,Integer.MAX_VALUE);
summaryCell(qty_pass_s,Integer.MAX_VALUE);
summaryCell(qty_skip,0);
summaryCell(qty_fail,0);
summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true);
m_out.println("<td colspan=\"2\"> </td></tr>");
}
m_out.println("</table>");
}
private void summaryCell(String[] val) {
StringBuffer b = new StringBuffer();
for (String v : val) {
b.append(v + " ");
}
summaryCell(b.toString(),true);
}
private void summaryCell(String v,boolean isgood) {
m_out.print("<td class=\"numi"+(isgood?"":"_attn")+"\">" + v + "</td>");
}
private void startSummaryRow(String label) {
m_row += 1;
m_out.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")
+ "><td style=\"text-align:left;padding-right:2em\">" + label
+ "</td>");
}
private void summaryCell(int v,int maxexpected) {
summaryCell(String.valueOf(v),v<=maxexpected);
m_rowTotal += v;
}
private void tableStart(String cssclass) {
m_out.println("<table cellspacing=0 cellpadding=0"
+ (cssclass != null ? " class=\"" + cssclass + "\""
: " style=\"padding-bottom:2em\"") + ">");
m_row = 0;
}
private void tableColumnStart(String label) {
m_out.print("<th class=\"numi\">" + label + "</th>");
}
private void titleRow(String label, int cq) {
m_out.println("<tr><th colspan=\"" + cq + "\">" + label + "</th></tr>");
m_row = 0;
}
protected void writeStyle(String[] formats,String[] targets) {
}
/** Starts HTML stream */
protected void startHtml(PrintWriter out) {
out.println("<!DOCTYPE html PUBLIC \"-
out.println("<html xmlns=\"http:
out.println("<head>");
out.println("<title>TestNG: Unit Test</title>");
out.println("<style type=\"text/css\">");
out.println("table caption,table.info_table,table.param,table.passed,table.failed {margin-bottom:10px;border:1px solid #000099;border-collapse:collapse;empty-cells:show;}");
out.println("table.info_table td,table.info_table th,table.param td,table.param th,table.passed td,table.passed th,table.failed td,table.failed th {");
out.println("border:1px solid #000099;padding:.25em .5em .25em .5em");
out.println("}");
out.println("table.param th {vertical-align:bottom}");
out.println("td.numi,th.numi,td.numi_attn {");
out.println("text-align:right");
out.println("}");
out.println("tr.total td {font-weight:bold}");
out.println("table caption {");
out.println("text-align:center;font-weight:bold;");
out.println("}");
out.println("table.passed tr.stripe td,table tr.passedodd td {background-color: #00AA00;}");
out.println("table.passed td,table tr.passedeven td {background-color: #33FF33;}");
out.println("table.passed tr.stripe td,table tr.skippedodd td {background-color: #cccccc;}");
out.println("table.passed td,table tr.skippedodd td {background-color: #dddddd;}");
out.println("table.failed tr.stripe td,table tr.failedodd td,table.param td.numi_attn {background-color: #FF3333;}");
out.println("table.failed td,table tr.failedeven td,table.param tr.stripe td.numi_attn {background-color: #DD0000;}");
out.println("tr.stripe td,tr.stripe th {background-color: #E6EBF9;}");
out.println("p.totop {font-size:85%;text-align:center;border-bottom:2px black solid}");
out.println("div.shootout {padding:2em;border:3px #4854A8 solid}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
}
/** Finishes HTML stream */
protected void endHtml(PrintWriter out) {
out.println("</body></html>");
}
/** Arranges methods by classname and method name */
private class TestSorter implements Comparator<IInvokedMethod> {
/** Arranges methods by classname and method name */
@Override
public int compare(IInvokedMethod o1, IInvokedMethod o2) {
// System.out.println("Comparing " + o1.getMethodName() + " " + o1.getDate()
// + " and " + o2.getMethodName() + " " + o2.getDate());
return (int) (o1.getDate() - o2.getDate());
// int r = ((T) o1).getTestClass().getName().compareTo(((T) o2).getTestClass().getName());
// if (r == 0) {
// r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());
// return r;
}
}
} |
package com.namelessmc.java_api.modules.store;
import com.google.gson.JsonObject;
import com.namelessmc.java_api.NamelessAPI;
import com.namelessmc.java_api.exception.NamelessException;
import com.namelessmc.java_api.NamelessUser;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class StoreCustomer {
private final NamelessAPI api;
private final int id;
private final @Nullable Integer userId;
private final @Nullable String username;
private final @Nullable String identifier;
StoreCustomer(NamelessAPI api, JsonObject json) {
this.api = api;
this.id = json.get("customer_id").getAsInt();
this.userId = json.has("user_id") ? json.get("user_id").getAsInt() : null;
this.username = json.has("username") ? json.get("username").getAsString() : null;
this.identifier = json.has("identifier") ? json.get("identifier").getAsString() : null;
if (this.username == null && this.identifier == null) {
throw new IllegalStateException("Username and identifier cannot be null at the same time");
}
}
public int id() {
return this.id;
}
public @Nullable NamelessUser user() throws NamelessException {
return this.userId != null ? this.api.user(this.userId) : null;
}
public @Nullable String username() {
return this.username;
}
public @Nullable String identifier() {
return this.identifier;
}
public @Nullable UUID identifierAsUuid() {
// Unlike NamelessMC, the store module sends UUIDs with dashes
return this.identifier != null ? UUID.fromString(this.identifier) : null;
}
} |
package org.xtx.ut4converter.t3d;
import org.xtx.ut4converter.export.UTPackageExtractor;
import org.xtx.ut4converter.tools.Geometry;
import org.xtx.ut4converter.ucore.UPackageRessource;
import org.xtx.ut4converter.ucore.ue2.TerrainLayer;
import org.xtx.ut4converter.ucore.ue4.LandscapeCollisionComponent;
import org.xtx.ut4converter.ucore.ue4.LandscapeComponent;
import org.xtx.ut4converter.ucore.ue4.LandscapeComponentAlphaLayer;
import javax.vecmath.Point2d;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* Very basic implementation of Unreal Engine 4 terrain
*
* @author XtremeXp
*/
public class T3DUE4Terrain extends T3DActor {
private File landscapeMatFile;
private UPackageRessource landscapeMaterial;
private UPackageRessource landscapeHoleMaterial;
private int collisionMipLevel;
private int collisionThickness = 16;
/**
* Max component size
*/
private final int maxComponentSize = 255;
private int componentSizeQuads;
private int subsectionSizeQuads;
private short numSubsections;
private boolean bUsedForNavigation;
private LandscapeCollisionComponent[][] collisionComponents;
private LandscapeComponent[][] landscapeComponents;
/**
* Creates an Unreal Engine 4 terrain from Unreal Engine 3 terrain
*
* @param ue3Terrain Unreal Engine 4 terrain
*/
public T3DUE4Terrain(final T3DUE3Terrain ue3Terrain) {
super(ue3Terrain.getMapConverter(), ue3Terrain.t3dClass);
initialise();
this.name = ue3Terrain.name;
this.location = ue3Terrain.location;
this.rotation = Geometry.UE123ToUE4Rotation(ue3Terrain.rotation);
this.scale3d = ue3Terrain.scale3d;
// compute the number of collision components from terrain size and max component size
/**
* In our example:
* NumPatchesX=20
* NumPatchesY=20
* MaxComponentSize=4
*
* In UE3 a component size could have height and width different (SectionSizeX and SectionSizeY properties)
* in UE4 these properties have been replaced by ComponentSizeQuads so it's always a square so we need to compute the number of components needed for UE4 terrain
*/
// in UE4 compQuadSize is always either 7x7 or 15x15 or 31x31 or 63x63 or 127*127 or 255*255
//int compQuadSize = ue3Terrain.getTerrainActorMembers().getMaxComponentSize() * ue3Terrain.getTerrainActorMembers().getMaxTesselationLevel();
// FIXME global, UE3Terrain conversion buggy with multi component so as a temp fix we do only one big component that fits the whole square
int compQuadSize = computeQuadSize(ue3Terrain.getTerrainHeight().getHeight(), ue3Terrain.getTerrainHeight().getWidth());
// since collision data and landscape data are the same compSize and subSectionSize are the same
this.componentSizeQuads = compQuadSize;
this.subsectionSizeQuads = compQuadSize;
this.numSubsections = 1;
// Ceil(20 / (4*4)) = Ceil(1.25) = 2
int nbCompX = (int) Math.ceil(ue3Terrain.getTerrainActorMembers().getNumPatchesX() * 1f / compQuadSize);
// Ceil(20 / (4*4)) = Ceil(1.25) = 2
int nbCompY = (int) Math.ceil(ue3Terrain.getTerrainActorMembers().getNumPatchesY() * 1f / compQuadSize);
collisionComponents = new LandscapeCollisionComponent[nbCompX][nbCompY];
landscapeComponents = new LandscapeComponent[nbCompX][nbCompY];
final List<Integer> heightMap = ue3Terrain.getTerrainHeight().getHeightMap();
final short terrainWidth = ue3Terrain.getTerrainHeight().getWidth();
final short terrainHeight = ue3Terrain.getTerrainHeight().getHeight();
// TODO handle visibility data (not visible terrain parts)
final List<Boolean> visData = new LinkedList<>();
// vis data in UT3 is 0 1 0 0 0 0 1 1
for (final Integer vis : ue3Terrain.getTerrainInfoData().getData()) {
if (vis == 0) {
visData.add(Boolean.FALSE);
} else {
visData.add(Boolean.TRUE);
}
}
// compute new alpha values for all alpha layers to fit the sum = 255
final Map<Integer, List<Integer>> newAlphaValueLayersByTerrainLayerIdx = fixAlphaLayersValuesByTerrainLayerIndex(ue3Terrain);
for (org.xtx.ut4converter.ucore.ue3.TerrainLayer terrainLayer : ue3Terrain.getTerrainLayers()) {
ue3Terrain.getAlphaLayers().set(terrainLayer.getAlphaMapIndex(), newAlphaValueLayersByTerrainLayerIdx.get(terrainLayer.getIndex()));
}
buildLandscapeAndCollisionComponents(compQuadSize, nbCompX, nbCompY, heightMap, ue3Terrain.getAlphaLayers(), visData, terrainWidth, terrainHeight);
}
/**
* // IN Unreal Engine 4 the sum of all alpha values given an alpha index is always 255 (FF in hexa)
* // as such we have to modify the current alpha values for UE3 so the sum of all alpha values for all layers given an alpha index is 255
* // e.g: AlphaValue(L1, X) = 64
* // e.g: AlphaValue(L2, X) = 200
* // e.g: AlphaValue(L3, X) = 240
* // Sum of all layers in UT4 must equals to
* // AlphaValueNEW(L1, X) = 255 * ((AlphaValue(L1, X) / (AlphaValue(L1, X) +AlphaValue(L2, X) +AlphaValue(L3, X))) = 32.38 -> 32
* // AlphaValueNEW(L1, X) = 255 * (64 / (64 +200 +240)) = 32.38 -> 32
* @param ue3Terrain
* @return
*/
private Map<Integer, List<Integer>> fixAlphaLayersValuesByTerrainLayerIndex(T3DUE3Terrain ue3Terrain) {
// FIXME better alpha values but not yet perfect
final Map<Integer, List<Integer>> newAlphaValueLayersByTerrainLayerIdx = new HashMap<>();
final List<Integer> allLayersAlphaValueSum = new LinkedList<>();
// precompute sum of all alphalayers given an alpha value index
for (int alphaValueIdx = 0; alphaValueIdx < ue3Terrain.getAlphaLayers().get(0).size(); alphaValueIdx++) {
for (int i = 0; i < ue3Terrain.getTerrainLayers().size(); i++) {
allLayersAlphaValueSum.add(ue3Terrain.getAlphaLayers().get(i).get(alphaValueIdx));
}
}
for (int terrainLayerIdx = 0; terrainLayerIdx < ue3Terrain.getTerrainLayers().size(); terrainLayerIdx++) {
final org.xtx.ut4converter.ucore.ue3.TerrainLayer terrainLayer = ue3Terrain.getTerrainLayers().get(terrainLayerIdx);
final List<Integer> alphaValues = ue3Terrain.getAlphaLayers().get(terrainLayer.getAlphaMapIndex());
final List<Integer> newAlphaValues = new ArrayList<>();
for (int alphaValueIdx = 0; alphaValueIdx < alphaValues.size(); alphaValueIdx++) {
int alphaValueAllLayersSum = allLayersAlphaValueSum.get(alphaValueIdx);
Integer oldAlphaValue = alphaValues.get(alphaValueIdx);
int alphaValueOtherLayersSum = alphaValueAllLayersSum - oldAlphaValue;
int newAlphaValue;
// first alpha layer in UT4 is always rendered
if (terrainLayer.getAlphaMapIndex() == 0) {
// AlphaLayer 1: 240
// AlphaLayer 2: 20
// AlphaLayer 3: 40
int newOldAlphaValue = 255 * ue3Terrain.getTerrainLayers().size() - alphaValueOtherLayersSum;
alphaValueAllLayersSum += (newOldAlphaValue - oldAlphaValue);
oldAlphaValue = newOldAlphaValue;
alphaValueAllLayersSum += (255 - oldAlphaValue);
oldAlphaValue = 255;
}
newAlphaValue = (int) (255f * ((oldAlphaValue * 1f) / (alphaValueAllLayersSum * 1f)));
newAlphaValues.add(newAlphaValue);
}
newAlphaValueLayersByTerrainLayerIdx.put(terrainLayer.getIndex(), newAlphaValues);
}
return newAlphaValueLayersByTerrainLayerIdx;
}
/**
* Compute quadsize of UE4 terrain.
* in UE4 compQuadSize is always either 7x7 or 15x15 or 31x31 or 63x63 or 127*127 or 255*255
*
* @param terrainHeight
* @param terrainWidth
* @return
*/
private int computeQuadSize(final int terrainHeight, final int terrainWidth) {
int compQuadSize = Math.max(terrainHeight, terrainWidth);
// we fit to the best UE4 quadSize
if (compQuadSize <= 7) {
compQuadSize = 7;
} else if (compQuadSize <= 15) {
compQuadSize = 15;
} else if (compQuadSize <= 31) {
compQuadSize = 31;
} else if (compQuadSize <= 127) {
compQuadSize = 127;
} else if (compQuadSize <= 255) {
compQuadSize = 255;
} else {
// not supported
compQuadSize = 255;
}
return compQuadSize;
}
/**
* Build landscape collision and heigh components
* @param compQuadSize
* @param nbCompX
* @param nbCompY
* @param heightMap
* @param alphaLayersData
* @param visibilityData
* @param terrainWidth
* @param terrainHeight
*/
private void buildLandscapeAndCollisionComponents(int compQuadSize, int nbCompX, int nbCompY, final List<Integer> heightMap, final List<List<Integer>> alphaLayersData, final List<Boolean> visibilityData, short terrainWidth, short terrainHeight) {
// size of heightmap values for components
int ue4CompHeightDataSize = (compQuadSize + 1) * (compQuadSize + 1);
int compIdx = 0;
// min terrain height will become the default value
long minTerrainHeight = heightMap.stream().mapToInt(a -> a).min().orElse(32768);
for (int compIdxX = 0; compIdxX < nbCompX; compIdxX++) {
for (int compIdxY = 0; compIdxY < nbCompY; compIdxY++) {
// create component
final LandscapeCollisionComponent lcc = new LandscapeCollisionComponent(mapConverter, this, compIdx, compQuadSize);
lcc.setSectionBaseX(compIdxX * compQuadSize);
lcc.setSectionBaseY(compIdxY * compQuadSize);
// fill up heighdata for this component
for (int i = 0; i < ue4CompHeightDataSize; i++) {
final Integer heightMatchIdx = getDataIndexForComponentHeightIndex(i, compQuadSize, compIdxX, compIdxY, terrainWidth, terrainHeight);
if (heightMatchIdx != -1) {
lcc.getHeightData().add(heightMap.get(heightMatchIdx).longValue());
}
// outside of original UE2/3 terrain square set default value
else {
lcc.getHeightData().add(minTerrainHeight);
}
}
// fill up visibility data for this component
if (visibilityData != null) {
for (int i = 0; i < ue4CompHeightDataSize; i++) {
final Integer visibilityMatchIdx = getDataIndexForComponentHeightIndex(i, compQuadSize, compIdxX, compIdxY, terrainWidth, terrainHeight);
if (visibilityMatchIdx != -1) {
lcc.getVisibilityData().add(visibilityData.get(visibilityMatchIdx));
}
// outside of original UE2/3 terrain square set to not rendering
else {
lcc.getVisibilityData().add(Boolean.FALSE);
}
}
}
// fill up alpha layers for this component
final List<LandscapeComponentAlphaLayer> alphaLayers = new LinkedList<>();
for (int layerNum = 0; layerNum < alphaLayersData.size(); layerNum++) {
// increment the layer num since the first layer (0) is used by heightmap
final LandscapeComponentAlphaLayer landscapeComponentAlphaLayer = new LandscapeComponentAlphaLayer(layerNum);
final List<Integer> alphaData = alphaLayersData.get(layerNum);
for (int alphaIdx = 0; alphaIdx < ue4CompHeightDataSize; alphaIdx++) {
final Integer alphaMatchIdx = getDataIndexForComponentHeightIndex(alphaIdx, compQuadSize, compIdxX, compIdxY, terrainWidth, terrainHeight);
if (alphaMatchIdx != -1) {
landscapeComponentAlphaLayer.getAlphaData().add(alphaData.get(alphaMatchIdx));
}
// outside of original UE2/3 terrain square set to not rendering
else {
landscapeComponentAlphaLayer.getAlphaData().add(0);
}
}
alphaLayers.add(landscapeComponentAlphaLayer);
}
collisionComponents[compIdxX][compIdxY] = lcc;
final LandscapeComponent lc = new LandscapeComponent(mapConverter, this, lcc, alphaLayers);
lc.setName("LC_" + compIdx);
landscapeComponents[compIdxX][compIdxY] = lc;
lcc.setRenderComponent(lc);
compIdx ++;
}
}
}
/**
* Given a component height index and the height data of original UE3 terrain, return the height
* related to this index within the UE4 terrain
*
* FIXME only works if there is only one component for whole terrain else would give bad index (if compIdxX > 0 or compIdxY > 0)
*
* @param compHeightIdx Component height index
* @param compQuadSize Quad Size for UE4 terrain
* @param compIdxX UE4 terrain component X coordinate
* @param compIdxY UE4 terrain component Y coordinate
* @param ue3GlobalWidth UE3 terrain width (might be different from the new UE4 terrain width due to QuadSize list restrictions)
* @return
*/
private Integer getDataIndexForComponentHeightIndex(int compHeightIdx, int compQuadSize, int compIdxX, int compIdxY, int ue3GlobalWidth, int ue3GlobalHeight) {
// let's say in UE3 our terrain was a 21x21 square (ue3GlobalWidth)
// and our UE4 converted terrain a 31*31 square
// some heightvalues will be out of the UE3 terrain and will be needed to be set to default value (32768)
// local coordinates within the UE4 component of height index
final Point2d compHeightIdxCoord = getCoordinatesForIndexInSquareSize(compHeightIdx, (compQuadSize + 1), 0);
// global coordinates within the UE4 terrain of this height index
final Point2d compHeightIdxGlobalCoord = new Point2d(compIdxX * (compQuadSize + 1) + compHeightIdxCoord.x, compIdxY * (compQuadSize + 1) + compHeightIdxCoord.y);
// this point is outside the original UE3 square return -1
if (compHeightIdxGlobalCoord.x > (ue3GlobalWidth - 1) || compHeightIdxGlobalCoord.y > (ue3GlobalHeight - 1)) {
return -1;
} else {
return compIdxX * (compQuadSize + 1) + compIdxY * (compQuadSize + 1) + compHeightIdx - (int)(compHeightIdxGlobalCoord.y * (compQuadSize - ue3GlobalWidth + 1));
}
}
public static Point2d getCoordinatesForIndexInSquareSize(final int globalIndex, final int width, final int height) {
return new Point2d(globalIndex % width, (int) Math.floor((globalIndex * 1f) / width));
}
/**
* Creates t3d ue4 terrain from unreal engine 2 terrain
*
* @param ue2Terrain
*/
public T3DUE4Terrain(final T3DUE2Terrain ue2Terrain) {
super(ue2Terrain.getMapConverter(), ue2Terrain.t3dClass);
initialise();
this.name = ue2Terrain.name;
this.location = ue2Terrain.location;
this.rotation = Geometry.UE123ToUE4Rotation(ue2Terrain.rotation);
this.scale3d = ue2Terrain.getTerrainScale();
if (!ue2Terrain.getLayers().isEmpty()) {
landscapeMaterial = ue2Terrain.getLayers().get(0).getTexture();
}
short ue2TerrainWidth = (short) (ue2Terrain.getHeightMapTextureDimensions().width);
short ue2TerrainHeight = (short) (ue2Terrain.getHeightMapTextureDimensions().height);
// E.G: 128X128 -> 127
int compQuadSize = computeQuadSize(ue2TerrainHeight -1, ue2TerrainWidth - 1);
this.componentSizeQuads = compQuadSize;
this.subsectionSizeQuads = this.componentSizeQuads;
this.numSubsections = 1;
// E.G: 128 / (127 + 1) = 1
int nbCompX = ue2Terrain.getHeightMapTextureDimensions().width / (componentSizeQuads + 1);
int nbCompY = ue2Terrain.getHeightMapTextureDimensions().height / (componentSizeQuads + 1);
collisionComponents = new LandscapeCollisionComponent[nbCompX][nbCompY];
landscapeComponents = new LandscapeComponent[nbCompX][nbCompY];
// FIXME visibility data seems not working
final List<Boolean> visibilityData = convertUe2Visibility(ue2Terrain);
final List<List<Integer>> alphaLayers = ue2Terrain.getLayers().stream().map(TerrainLayer::getAlphaMap).collect(Collectors.toList());
final Map<Integer, List<Integer>> newAlphaValuesByLayerIdx = new HashMap<>();
final List<Integer> allLayersAlphaValueSum = new LinkedList<>();
// precompute sum of all alphalayers given an alpha value index
for (int alphaValueIdx = 0; alphaValueIdx < ue2Terrain.getLayers().get(0).getAlphaMap().size(); alphaValueIdx++) {
for (int i = 0; i < ue2Terrain.getLayers().size(); i++) {
allLayersAlphaValueSum.add(ue2Terrain.getLayers().get(i).getAlphaMap().get(alphaValueIdx));
}
}
int layerIdx = 0;
for (final TerrainLayer terrainLayer : ue2Terrain.getLayers()) {
final List<Integer> newAlphaValues = new ArrayList<>();
for (int alphaValueIdx = 0; alphaValueIdx < terrainLayer.getAlphaMap().size(); alphaValueIdx++) {
int newAlphaValue = 0;
int alphaValueAllLayersSum = allLayersAlphaValueSum.get(alphaValueIdx);
int oldAlphaValue = terrainLayer.getAlphaMap().get(alphaValueIdx);
int alphaValueOtherLayersSum = alphaValueAllLayersSum - oldAlphaValue;
// first alpha layer in UT4 is always rendered
if (layerIdx == 0) {
// AlphaLayer 1: 240
// AlphaLayer 2: 20
// AlphaLayer 3: 40
int newOldAlphaValue = 255 * ue2Terrain.getLayers().size() - alphaValueOtherLayersSum;
alphaValueAllLayersSum += (newOldAlphaValue - oldAlphaValue);
oldAlphaValue = newOldAlphaValue;
alphaValueAllLayersSum += (255 - oldAlphaValue);
oldAlphaValue = 255;
}
newAlphaValue = (int) (255f * ((oldAlphaValue * 1f) / (alphaValueAllLayersSum * 1f)));
newAlphaValues.add(newAlphaValue);
}
newAlphaValuesByLayerIdx.put(layerIdx, newAlphaValues);
layerIdx++;
}
// replace alpha values with new ones
newAlphaValuesByLayerIdx.forEach((layerIdx2, newAlphaMapValues) -> {
ue2Terrain.getLayers().get(layerIdx2).setAlphaMap(newAlphaMapValues);
});
buildLandscapeAndCollisionComponents(compQuadSize, nbCompX, nbCompY, ue2Terrain.getHeightMap(), alphaLayers, visibilityData, ue2TerrainWidth, ue2TerrainHeight);
// In Unreal Engine 2, terrain pivot is "centered"
// unlike UE3/4, so need update location
if (this.location != null && this.scale3d != null) {
double offsetX = (nbCompX * this.scale3d.x * this.componentSizeQuads) / 2;
double offsetY = (nbCompY * this.scale3d.y * this.componentSizeQuads) / 2;
this.location.x -= (offsetX + 100);
this.location.y -= (offsetY + 100);
this.location.z *= mapConverter.getScale();
}
}
/**
* Convert visibility data from unreal engine 2 terrain. Adapted code from
* UT3 converter
*
* e.g (UE2):
* "QuadVisibilityBitmap(0)=-65540, QuadVisibilityBitmap(0)=-1, ..." e.g:
* (UE4): "CustomProperties DominantLayerData fffffffffff...."
*
* @param ue2Terrain
* Terrain from unreal engine 2 ut game (ut2003, ut2004 or unreal
* 2)
*/
private List<Boolean> convertUe2Visibility(T3DUE2Terrain ue2Terrain) {
List<Boolean> globalVisibility = new ArrayList<>();
if (ue2Terrain.getQuadVisibilityBitmaps() == null || !ue2Terrain.getQuadVisibilityBitmaps().isEmpty()) {
StringBuilder tmpRadix;
Map<Integer, Long> visMap = ue2Terrain.getQuadVisibilityBitmaps();
for (int i = 0; i < ue2Terrain.getTotalSquares() / 32; i++) {
if (visMap != null && visMap.containsKey(i)) {
Long visibility = visMap.get(i);
tmpRadix = new StringBuilder();
// -1 means 32 squares are rendered
if (visibility == -1) {
for (int j = 0; j < 32; j++) {
globalVisibility.add(Boolean.TRUE);
}
} else {
// "-134217728"
visibility++;
// "-134217727" -> --111111111111111111111111111
// (rendered squares in "reverse" order)
String radix = Long.toString(visibility, 2);
radix = radix.replaceAll("-", "");
for (int k = 0; k < (32 - radix.length()); k++) {
tmpRadix.append("0");
}
radix = tmpRadix + radix;
for (int j = 31; j >= 0; j
globalVisibility.add(radix.charAt(j) == '1');
}
}
} else {
for (int j = 0; j < 32; j++) {
globalVisibility.add(Boolean.TRUE);
}
}
}
}
return globalVisibility;
}
private void initialise() {
numSubsections = 1;
bUsedForNavigation = true;
}
@Override
public boolean isValidWriting() {
return landscapeComponents.length > 0;
}
@Override
public void convert() {
if (landscapeMaterial != null) {
landscapeMaterial.export(UTPackageExtractor.getExtractor(mapConverter, landscapeMaterial));
}
if (landscapeHoleMaterial != null) {
landscapeHoleMaterial.export(UTPackageExtractor.getExtractor(mapConverter, landscapeHoleMaterial));
}
super.convert();
}
@Override
public String toString() {
return toT3d();
}
public String toT3d() {
sbf.append(IDT).append("Begin Actor Class=Landscape Name=").append(name).append("\n");
for (int x = 0; x < collisionComponents.length; x++) {
for (int y = 0; y < collisionComponents[0].length; y++) {
sbf.append(IDT).append("\tBegin Object Class=LandscapeHeightfieldCollisionComponent Name=\"").append(collisionComponents[x][y].getName()).append("\"\n");
sbf.append(IDT).append("\tEnd Object\n");
}
}
for (int x = 0; x < landscapeComponents.length; x++) {
for (int y = 0; y < landscapeComponents[0].length; y++) {
sbf.append(IDT).append("\tBegin Object Class=LandscapeComponent Name=\"").append(landscapeComponents[x][y].getName()).append("\"\n");
sbf.append(IDT).append("\tEnd Object\n");
}
}
sbf.append(IDT).append("\tBegin Object Class=SceneComponent Name=\"RootComponent0\"\n");
sbf.append(IDT).append("\tEnd Object\n");
for (int x = 0; x < collisionComponents.length; x++) {
for (int y = 0; y < collisionComponents[0].length; y++) {
collisionComponents[x][y].toT3d(sbf, null);
}
}
for (int x = 0; x < landscapeComponents.length; x++) {
for (int y = 0; y < landscapeComponents[0].length; y++) {
landscapeComponents[x][y].toT3d(sbf, null);
}
}
sbf.append(IDT).append("\tBegin Object Name=\"RootComponent0\"\n");
writeLocRotAndScale();
sbf.append(IDT).append("\tEnd Object\n");
// needs a guid or else would crash on import
sbf.append(IDT).append("\tLandscapeGuid=").append(T3DUtils.randomGuid()).append("\n");
// use the UT4X landscape material (UT4X_LandscapeMat.uasset)
AtomicInteger terrainIdx = new AtomicInteger();
// compute index of this terrain in map
mapConverter.getT3dLvlConvertor().getConvertedActors().forEach(e -> {
if (e.getChildren() != null && !e.getChildren().isEmpty() && e.getChildren().get(0) instanceof T3DUE4Terrain) {
if (e.getChildren().get(0) == this) {
return;
}
terrainIdx.getAndIncrement();
}
});
sbf.append(IDT).append("\tLandscapeMaterial=Material'").append(mapConverter.getUt4ReferenceBaseFolder()).append("/UT4X_LandscapeMat_").append(terrainIdx.getAcquire()).append(".UT4X_LandscapeMat_").append(terrainIdx.getAcquire()).append("'\n");
int idx = 0;
for (int x = 0; x < landscapeComponents.length; x++) {
for (int y = 0; y < landscapeComponents[0].length; y++) {
sbf.append(IDT).append("\tLandscapeComponents(").append(idx).append(")=LandscapeComponent'").append(landscapeComponents[x][y].getName()).append("'\n");
idx++;
}
}
idx = 0;
for (int x = 0; x < collisionComponents.length; x++) {
for (int y = 0; y < collisionComponents[0].length; y++) {
sbf.append(IDT).append("\tCollisionComponents(").append(idx).append(")=CollisionComponent'").append(collisionComponents[x][y].getName()).append("'\n");
idx++;
}
}
sbf.append(IDT).append("\tComponentSizeQuads=").append(componentSizeQuads).append("\n");
sbf.append(IDT).append("\tSubsectionSizeQuads=").append(subsectionSizeQuads).append("\n");
sbf.append(IDT).append("\tNumSubsections=").append(numSubsections).append("\n");
sbf.append(IDT).append("\tRootComponent=RootComponent0\n");
writeEndActor();
return sbf.toString();
}
public LandscapeCollisionComponent[][] getCollisionComponents() {
return collisionComponents;
}
public LandscapeComponent[][] getLandscapeComponents() {
return landscapeComponents;
}
public File getLandscapeMatFile() {
return landscapeMatFile;
}
public void setLandscapeMatFile(File landscapeMatFile) {
this.landscapeMatFile = landscapeMatFile;
}
} |
package org.zalando.nakadi.domain;
import com.google.common.base.Preconditions;
import java.util.Objects;
public class NakadiCursor {
public static final int VERSION_LENGTH = 3;
/**
* - ZERO is reserved for old offset format, e.g. those previous to timelines: "000000000000000010"
* - ONE is reserved for the first version of timeline offsets: "001-0000-000000000000000A"
**/
public enum Version {
ZERO("000"),
ONE("001"),;
public final String code;
Version(final String code) {
Preconditions.checkArgument(
code.length() == VERSION_LENGTH,
"Version field length should be equal to " + VERSION_LENGTH);
this.code = code;
}
}
private final Timeline timeline;
private final String partition;
// NO BEGIN HERE - only real offset!
private final String offset;
public NakadiCursor(
final Timeline timeline,
final String partition,
final String offset) {
this.timeline = timeline;
this.partition = partition;
this.offset = offset;
}
public Timeline getTimeline() {
return timeline;
}
public String getTopic() {
return timeline.getTopic();
}
public String getPartition() {
return partition;
}
public String getOffset() {
return offset;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof NakadiCursor)) {
return false;
}
final NakadiCursor that = (NakadiCursor) o;
return Objects.equals(this.timeline, that.timeline)
&& Objects.equals(this.partition, that.partition)
&& Objects.equals(this.offset, that.offset);
}
// TODO: Remove method one subscriptions are transferred to use timelines.
public NakadiCursor withOffset(final String offset) {
return new NakadiCursor(timeline, partition, offset);
}
@Override
public int hashCode() {
int result = timeline.hashCode();
result = 31 * result + partition.hashCode();
result = 31 * result + offset.hashCode();
return result;
}
@Override
public String toString() {
return "NakadiCursor{" +
"partition='" + partition + '\'' +
", offset='" + offset + '\'' +
", timeline='" + timeline + '\'' +
'}';
}
} |
//@@author A0139961U
package seedu.tache.logic.commands;
import seedu.tache.commons.exceptions.IllegalValueException;
import seedu.tache.logic.commands.exceptions.CommandException;
/**
* Adds a task to the task manager.
*/
public class SaveCommand extends Command {
public static final String COMMAND_WORD = "save";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the save location of the"
+ "data files based on the directory entered or selected.\n"
+ "Parameters: DIRECTORY \n"
+ "Example: " + COMMAND_WORD
+ " C:\\Users\\user\\Desktop";
public static final String MESSAGE_SUCCESS = "Save location changed to: %1$s";
public final String newPath;
public SaveCommand(String newDirectory) {
this.newPath = newDirectory;
}
@Override
public CommandResult execute() throws CommandException {
assert storage != null;
storage.setTaskManagerFilePath(newPath + "\\taskmanager.xml");
return new CommandResult(String.format(MESSAGE_SUCCESS, newPath));
}
} |
//@@author A0150120H
package seedu.tache.logic.commands;
import java.util.Stack;
/*
* Class to handle the Undo history. Uses a First-In-Last-Out data structure
* This class follows the Singleton Pattern
*/
public class UndoHistory {
private Stack<Undoable> data;
private static UndoHistory currentInstance;
/**
* Creates a new UndoHistory object.
* This should only be called once in the entire exectution
*/
private UndoHistory() {
data = new Stack<Undoable>();
}
/**
* Saves an Undoable Command into history
* @param target Undoable Command to be saved
*/
public void push(Undoable target) {
data.push(target);
}
/**
* Removes and returns the latest Undoable Command from history.
* @return Undoable object if history is populated, null otherwise
*/
public Undoable pop() {
if (data.isEmpty()) {
return null;
} else {
return data.pop();
}
}
/**
* Clears all history
*/
public void clear() {
data = new Stack<Undoable>();
}
/**
* Returns an instance of this class. It is guaranteed to be the same instance throughout execution.
* @return instance of this class
*/
public static UndoHistory getInstance() {
if (currentInstance == null) {
currentInstance = new UndoHistory();
}
return currentInstance;
}
} |
package seedu.todo.controllers;
import java.io.IOException;
import java.util.Map;
import seedu.todo.MainApp;
import seedu.todo.commons.core.Config;
import seedu.todo.commons.util.ConfigUtil;
import seedu.todo.commons.util.StringUtil;
import seedu.todo.controllers.concerns.Renderer;
import seedu.todo.models.TodoListDB;
/**
* Controller to declare aliases
*
* @author louietyj
*
*/
public class AliasController implements Controller {
private static final String NAME = "Alias";
private static final String DESCRIPTION = "Shows current aliases or updates them.";
private static final String COMMAND_SYNTAX = "alias [<alias key> <alias value>]";
private static final String SPACE = " ";
private static final int ARGS_LENGTH = 2;
private static final String MESSAGE_SHOWING = "Showing all aliases.";
private static final String MESSAGE_SAVE_SUCCESS = "Successfully saved alias!";
private static final String INVALID_NUM_PARAMS = "Seems like you have provided an invalid number of parameters!";
private static final String MESSAGE_INVALID_INPUT = "Invalid alias parameters! Alias inputs must consist solely "
+ "of alphabetical characters.";
private static final String SAVE_ERROR = "There was an error saving your aliases. Please try again.";
private static CommandDefinition commandDefinition =
new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX);
public static CommandDefinition getCommandDefinition() {
return commandDefinition;
}
@Override
public float inputConfidence(String input) {
// TODO
return input.toLowerCase().startsWith("alias") ? 1 : 0;
}
@Override
public void process(String input) {
String params = input.replaceFirst("alias", "").trim();
if (params.length() <= 0) {
Renderer.renderAlias(MESSAGE_SHOWING);
return;
}
String[] args = params.split(SPACE, ARGS_LENGTH);
String aliasKey = null;
String aliasValue = null;
// Best-effort matching, disambiguate if wrong.
validate: {
switch (args.length) {
case 0:
break;
case 1:
aliasKey = args[0];
break;
case 2: // All good!
aliasKey = args[0];
aliasValue = args[1];
break validate;
default:
aliasKey = args[0];
aliasValue = args[0];
break;
}
renderDisambiguation(aliasKey, aliasValue, INVALID_NUM_PARAMS);
return;
}
if (!validateAlias(aliasKey) || !validateAlias(aliasValue)) {
renderDisambiguation(aliasKey, aliasValue, MESSAGE_INVALID_INPUT);
return;
}
// Persist alias mapping
try {
saveAlias(aliasKey, aliasValue);
} catch (IOException e) {
Renderer.renderAlias(SAVE_ERROR);
return;
}
Renderer.renderAlias(MESSAGE_SAVE_SUCCESS);
}
/**
* Persists an alias mapping to the database.
*
* @param db TodoListDB singleton
* @param aliasKey
* @param aliasValue
* @throws IOException
*/
private static void saveAlias(String aliasKey, String aliasValue) throws IOException {
Config config = MainApp.getConfig();
Map<String, String> aliases = config.getAliases();
aliases.put(aliasKey, aliasValue);
ConfigUtil.saveConfig(config, MainApp.getConfigFilePath());
}
/**
* Validates that string is sanitized and safe for aliasing.
*
* @param alias string to check
* @return true if string is sanitized, false otherwise
*/
private static boolean validateAlias(String alias) {
return alias.chars().allMatch(Character::isLetter);
}
private static void renderDisambiguation(String aliasKey, String aliasValue, String message) {
String sanitizedAliasKey = StringUtil.sanitize(aliasKey);
sanitizedAliasKey = StringUtil.replaceEmpty(sanitizedAliasKey, "<alias key>");
String sanitizedAliasValue = StringUtil.sanitize(aliasValue);
sanitizedAliasValue = StringUtil.replaceEmpty(sanitizedAliasValue, "<alias value>");
Renderer.renderDisambiguation(String.format("alias %s %s",
sanitizedAliasKey, sanitizedAliasValue), message);
}
} |
package seedu.todo.logic.parser;
import static seedu.todo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.todo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.todo.commons.exceptions.IllegalValueException;
import seedu.todo.commons.util.StringUtil;
import seedu.todo.logic.commands.*;
import seedu.todo.model.task.Priority;
import seedu.todo.model.task.Recurrence.Frequency;
import com.joestelmach.natty.*;
/**
* Parses user input.
*/
public class ToDoListParser {
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = ParserFormats.BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
case MarkCommand.COMMAND_WORD:
return prepareMark(arguments);
case SearchCommand.COMMAND_WORD:
return prepareSearch(arguments);
case SeeCommand.COMMAND_WORD:
return new SeeCommand();
case TagCommand.COMMAND_WORD:
return prepareTag(arguments);
case UntagCommand.COMMAND_WORD:
return prepareUntag(arguments);
case UnmarkCommand.COMMAND_WORD:
return prepareUnmark(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case UpdateCommand.COMMAND_WORD:
return prepareUpdate(arguments);
case StoreCommand.COMMAND_WORD:
return prepareStore(arguments);
case ResetCommand.COMMAND_WORD:
return new ResetCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
private String matchNameResult(Matcher matcher) {
return matcher.group("name");
}
private String matchDetailResult(Matcher matcher) {
return matcher.group("detail");
}
private String matchOnDateTimeResult(Matcher matcher) {
return matcher.group("onDateTime");
}
private String matchByDateTimeResult(Matcher matcher) {
return matcher.group("byDateTime");
}
private String matchPriorityResult(Matcher matcher) {
return matcher.group("priority");
}
private String matchRecurrenceResult(Matcher matcher) {
return matcher.group("rec");
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args) {
Pattern[] dataPatterns = {ParserFormats.ADD_PRIORITY_FT,
ParserFormats.ADD_PRIORITY_ON, ParserFormats.ADD_PRIORITY_BY,
ParserFormats.ADD_PRIORITY_FL,
ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_FT, ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_BY,
ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_ON, ParserFormats.ADD_TASK_ARGS_FORMAT_FT,
ParserFormats.ADD_TASK_ARGS_FORMAT_BY, ParserFormats.ADD_TASK_ARGS_FORMAT_ON,
ParserFormats.ADD_TASK_ARGS_FORMAT_FLOAT};
//add buy chicken on friday by wednesday priority high every year ; chicken kfc
Matcher matcher;
try {
for (Pattern p : dataPatterns) {
matcher = p.matcher(args.trim());
if (matcher.matches()) {
if (p.equals(ParserFormats.ADD_TASK_ARGS_FORMAT_FT)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), matchByDateTimeResult(matcher), Priority.DEFAULT_PRIORITY, Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_TASK_ARGS_FORMAT_ON)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), null, Priority.DEFAULT_PRIORITY, Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_TASK_ARGS_FORMAT_BY)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher), null,
matchByDateTimeResult(matcher), Priority.DEFAULT_PRIORITY, Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_FT)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), matchByDateTimeResult(matcher),
Priority.DEFAULT_PRIORITY, Frequency.valueOf(matchRecurrenceResult(matcher).toUpperCase().trim()));
} else if (p.equals(ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_BY)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher), null,
matchByDateTimeResult(matcher), Priority.DEFAULT_PRIORITY, Frequency.valueOf(matchRecurrenceResult(matcher).toUpperCase().trim()));
} else if (p.equals(ParserFormats.ADD_TASK_ARGS_RECUR_FORMAT_ON)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), null, Priority.DEFAULT_PRIORITY, Frequency.valueOf(matchRecurrenceResult(matcher).toUpperCase().trim()));
} else if (p.equals(ParserFormats.ADD_PRIORITY_FT)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), matchByDateTimeResult(matcher), matchPriorityResult(matcher), Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_PRIORITY_FL)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
null, null, matchPriorityResult(matcher), Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_PRIORITY_ON)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher),
matchOnDateTimeResult(matcher), null, matchPriorityResult(matcher), Frequency.NONE);
} else if (p.equals(ParserFormats.ADD_PRIORITY_BY)) {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher), null,
matchByDateTimeResult(matcher), matchPriorityResult(matcher), Frequency.NONE);
} else {
return new AddCommand(matchNameResult(matcher), matchDetailResult(matcher), null, null, Priority.DEFAULT_PRIORITY, Frequency.NONE);
}
}
}
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (IllegalArgumentException ive) {
return new IncorrectCommand(ive.getMessage());
}
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the mark task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareMark(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
return new MarkCommand(index.get());
}
/**
* Parses arguments in the context of the unmark task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareUnmark(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnmarkCommand.MESSAGE_USAGE));
}
return new UnmarkCommand(index.get());
}
/**
* Parses arguments in the context of the tag task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareTag(String args) {
try {
String tempArgs = args.trim();
String indexString = tempArgs.substring(0, 1);
Optional<Integer> index = parseIndex(indexString);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
}
String tagNames = tempArgs.substring(1);
return new TagCommand(index.get(), tagNames);
} catch (Exception e) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
}
}
/**
* Parses arguments in the context of the untag task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareUntag(String args) {
try {
String tempArgs = args.trim();
String indexString = tempArgs.substring(0, 1);
Optional<Integer> index = parseIndex(indexString);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UntagCommand.MESSAGE_USAGE));
}
String tagNames = tempArgs.substring(1);
return new UntagCommand(index.get(), tagNames);
} catch (Exception e) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UntagCommand.MESSAGE_USAGE));
}
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned
* integer is given as the index. Returns an {@code Optional.empty()}
* otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = ParserFormats.TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareUpdate(String args) {
String tempArgs = args.trim();
if (tempArgs.length() < 1) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
String indexString = tempArgs.split(" ")[0];
Optional<Integer> index = parseIndex(indexString);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
tempArgs = tempArgs.substring(indexString.length()).trim();
Matcher matcher;
matcher = ParserFormats.UPDATE_TASK_ARGS_FORMAT.matcher(tempArgs.trim());
if (matcher.matches()) {
return new UpdateCommand(index.get(), matchNameResult(matcher).trim(), matchOnDateTimeResult(matcher),
matchByDateTimeResult(matcher), matchPriorityResult(matcher), matchDetailResult(matcher), matchRecurrenceResult(matcher));
} else {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
}
/**
* Parses arguments in the context of the search task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSearch(String args) {
Pattern[] dataPatterns = { ParserFormats.SEARCH_TASK_ARGS_FORMAT_ON,
ParserFormats.SEARCH_TASK_ARGS_FORMAT_BEFORE, ParserFormats.SEARCH_TASK_ARGS_FORMAT_AFTER,
ParserFormats.SEARCH_TASK_ARGS_FORMAT_FT, ParserFormats.KEYWORDS_ARGS_FORMAT,
ParserFormats.SEARCH_PRIORITY };
String tempArgs = args.trim();
Matcher matcher;
for (Pattern p : dataPatterns) {
matcher = p.matcher(tempArgs);
if (matcher.matches()) {
if (p.equals(ParserFormats.SEARCH_TASK_ARGS_FORMAT_ON)) {
return new SearchCommand(matchOnDateTimeResult(matcher), 0);
} else if (p.equals(ParserFormats.SEARCH_TASK_ARGS_FORMAT_BEFORE)) {
return new SearchCommand(matcher.group("beforeDateTime"), 1);
} else if (p.equals(ParserFormats.SEARCH_TASK_ARGS_FORMAT_AFTER)) {
return new SearchCommand(matcher.group("afterDateTime"), 2);
} else if (p.equals(ParserFormats.SEARCH_TASK_ARGS_FORMAT_FT)) {
return new SearchCommand(matcher.group("fromDateTime") + "@" + matcher.group("tillDateTime"), 3);
} else if (p.equals(ParserFormats.KEYWORDS_ARGS_FORMAT) && tempArgs.indexOf("tag") != 0
&& tempArgs.indexOf("done") != 0 && tempArgs.indexOf("undone") != 0
&& tempArgs.indexOf("priority") != 0) {
return new SearchCommand(matcher.group("keywords"), 4);
} else if (p.equals(ParserFormats.SEARCH_PRIORITY)) {
return new SearchCommand(matchPriorityResult(matcher), 8);
}
}
}
if (tempArgs.indexOf("tag") == 0) {
return new SearchCommand(tempArgs, 5);
}
if (tempArgs.indexOf("done") == 0) {
return new SearchCommand(tempArgs, 6);
}
if (tempArgs.indexOf("undone") == 0) {
return new SearchCommand(tempArgs, 7);
}
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SearchCommand.MESSAGE_USAGE));
}
/**
* Parses arguments in the context of the store command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareStore(String args) {
args = args.trim();
return new StoreCommand(args);
}
} |
package test.dr.evomodel.substmodel;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.TwoStateCovarion;
import dr.evolution.datatype.TwoStates;
import dr.evomodel.substmodel.BinaryCovarionModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.GeneralSubstitutionModel;
import dr.evomodel.substmodel.SubstitutionModelUtils;
import dr.inference.model.Parameter;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.Matrix;
import dr.math.matrixAlgebra.Vector;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* BinaryCovarionModel Tester.
*
* @author Alexei Drummond
* @version 1.0
* @since <pre>08/26/2007</pre>
*/
public class BinaryCovarionModelTest extends TestCase {
public BinaryCovarionModelTest(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
frequencies = new Parameter.Default(new double[]{0.5, 0.5});
hiddenFrequencies = new Parameter.Default(new double[]{0.5, 0.5});
alpha = new Parameter.Default(0.0);
switchingRate = new Parameter.Default(1.0);
model = new BinaryCovarionModel(TwoStateCovarion.INSTANCE, frequencies, hiddenFrequencies, alpha, switchingRate,
BinaryCovarionModel.Version.VERSION1);
dataType = model.getDataType();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
/**
* Tests that pi*Q = 0
*/
public void testEquilibriumDistribution() {
alpha.setParameterValue(0, 0.1);
switchingRate.setParameterValue(0, 1.0);
model.setupMatrix();
double[] pi = model.getFrequencyModel().getFrequencies();
try {
Matrix m = new Matrix(model.getQ());
Vector p = new Vector(pi);
Vector y = m.product(p);
assertEquals(0.0, y.norm(), 1e-14);
} catch (IllegalDimension illegalDimension) {
}
}
public void testTransitionProbabilitiesAgainstEqualBaseFreqsEqualRates() {
// with alpha == 1, the transition probability should be the same as binary jukes cantor
alpha.setParameterValue(0, 1.0);
switchingRate.setParameterValue(0, 1.0);
model.setupMatrix();
double[] matrix = new double[16];
double[] pi = model.getFrequencyModel().getFrequencies();
for (double distance = 0.01; distance <= 1.005; distance += 0.01) {
model.getTransitionProbabilities(distance, matrix);
double pChange =
(matrix[1] + matrix[3]) * pi[0] +
(matrix[4] + matrix[6]) * pi[1] +
(matrix[9] + matrix[11]) * pi[2] +
(matrix[12] + matrix[14]) * pi[3];
// analytical result for the probability of a mismatch in binary jukes cantor model
double jc = 0.5 * (1 - Math.exp(-2.0 * distance));
assertEquals(pChange, jc, 1e-14);
}
}
public void testTransitionProbabilitiesUnequalBaseFreqsEqualRates() {
// with alpha == 1, the transition probability should be the same as binary jukes cantor
alpha.setParameterValue(0, 1.0);
switchingRate.setParameterValue(0, 1.0);
frequencies.setParameterValue(0, 0.25);
frequencies.setParameterValue(1, 0.75);
FrequencyModel freqModel = new FrequencyModel(TwoStates.INSTANCE, frequencies);
GeneralSubstitutionModel modelToCompare = new GeneralSubstitutionModel(TwoStates.INSTANCE, freqModel, null, 0);
model.setupMatrix();
double[] matrix = new double[16];
double[] m = new double[4];
double[] pi = model.getFrequencyModel().getFrequencies();
for (double distance = 0.01; distance <= 1.005; distance += 0.01) {
model.getTransitionProbabilities(distance, matrix);
modelToCompare.getTransitionProbabilities(distance, m);
double pChange =
(matrix[1] + matrix[3]) * pi[0] +
(matrix[4] + matrix[6]) * pi[1] +
(matrix[9] + matrix[11]) * pi[2] +
(matrix[12] + matrix[14]) * pi[3];
double pChange2 = m[1] * frequencies.getParameterValue(0) +
m[2] * frequencies.getParameterValue(1);
System.out.println(distance + "\t" + pChange2 + "\t" + pChange);
assertEquals(pChange2, pChange, 1e-14);
}
}
public void testTransitionProbabilitiesUnequalBaseFreqsUnequalRateFreqsEqualRates() {
// with alpha == 1, the transition probability should be the same as binary jukes cantor
alpha.setParameterValue(0, 1.0);
switchingRate.setParameterValue(0, 1.0);
frequencies.setParameterValue(0, 0.25);
frequencies.setParameterValue(1, 0.75);
hiddenFrequencies.setParameterValue(0, 0.1);
hiddenFrequencies.setParameterValue(1, 0.9);
FrequencyModel freqModel = new FrequencyModel(TwoStates.INSTANCE, frequencies);
GeneralSubstitutionModel modelToCompare = new GeneralSubstitutionModel(TwoStates.INSTANCE, freqModel, null, 0);
model.setupMatrix();
double[] matrix = new double[16];
double[] m = new double[4];
double[] pi = model.getFrequencyModel().getFrequencies();
for (double distance = 0.01; distance <= 1.005; distance += 0.01) {
model.getTransitionProbabilities(distance, matrix);
modelToCompare.getTransitionProbabilities(distance, m);
double pChange =
(matrix[1] + matrix[3]) * pi[0] +
(matrix[4] + matrix[6]) * pi[1] +
(matrix[9] + matrix[11]) * pi[2] +
(matrix[12] + matrix[14]) * pi[3];
double pChange2 = m[1] * frequencies.getParameterValue(0) +
m[2] * frequencies.getParameterValue(1);
//System.out.println(distance + "\t" + pChange2 + "\t" + pChange);
assertEquals(pChange2, pChange, 1e-14);
}
}
public void testTransitionProbabilitiesAgainstMatLab() {
// test againt Matlab results for alpha = 0.5 and switching rate = 1.0
// and visible state base frequencies = 0.25, 0.75
alpha.setParameterValue(0, 0.5);
switchingRate.setParameterValue(0, 1.0);
frequencies.setParameterValue(0, 0.25);
frequencies.setParameterValue(1, 0.75);
model.setupMatrix();
double[] matrix = new double[16];
double[] pi = model.getFrequencyModel().getFrequencies();
System.out.println(pi[0] + " " + pi[1] + " " + pi[2] + " " + pi[3]);
System.out.println(SubstitutionModelUtils.toString(model.getQ(), dataType, 2));
int index = 0;
for (double distance = 0.01; distance <= 1.005; distance += 0.01) {
model.getTransitionProbabilities(distance, matrix);
double pChange =
(matrix[1] + matrix[3]) * pi[0] +
(matrix[4] + matrix[6]) * pi[1] +
(matrix[9] + matrix[11]) * pi[2] +
(matrix[12] + matrix[14]) * pi[3];
double pChangeIndependent = TwoStateCovarionModelTest.matLabPChange[index];
//System.out.println(distance + "\t" + pChange + "\t" + pChangeIndependent);
assertEquals(pChange, pChangeIndependent, 1e-14);
index += 1;
}
}
public static Test suite() {
return new TestSuite(BinaryCovarionModelTest.class);
}
BinaryCovarionModel model;
DataType dataType;
Parameter frequencies;
Parameter hiddenFrequencies;
Parameter switchingRate;
Parameter alpha;
} |
package de.danoeh.antennapod.feed;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.activity.AudioplayerActivity;
import de.danoeh.antennapod.asynctask.DownloadStatus;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.storage.*;
import de.danoeh.antennapod.util.FeedtitleComparator;
import de.danoeh.antennapod.util.comparator.FeedItemPubdateComparator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* Singleton class Manages all feeds, categories and feeditems
*
*
* */
public class FeedManager {
private static final String TAG = "FeedManager";
public static final String ACITON_FEED_LIST_UPDATE = "de.danoeh.antennapod.action.feed.feedlistUpdate";
public static final String ACTION_UNREAD_ITEMS_UPDATE = "de.danoeh.antennapod.action.feed.unreadItemsUpdate";
public static final String ACTION_QUEUE_UPDATE = "de.danoeh.antennapod.action.feed.queueUpdate";
public static final String EXTRA_FEED_ITEM_ID = "de.danoeh.antennapod.extra.feed.feedItemId";
public static final String EXTRA_FEED_ID = "de.danoeh.antennapod.extra.feed.feedId";
/** Number of completed Download status entries to store. */
private static final int DOWNLOAD_LOG_SIZE = 50;
private static FeedManager singleton;
private List<Feed> feeds;
private ArrayList<FeedCategory> categories;
/** Contains all items where 'read' is false */
private List<FeedItem> unreadItems;
/** Contains completed Download status entries */
private ArrayList<DownloadStatus> downloadLog;
/** Contains the queue of items to be played. */
private List<FeedItem> queue;
private DownloadRequester requester;
/** Should be used to change the content of the arrays from another thread. */
private Handler contentChanger;
/** Ensures that there are no parallel db operations. */
private Executor dbExec;
/** Prevents user from starting several feed updates at the same time. */
private static boolean isStartingFeedRefresh = false;
private FeedManager() {
feeds = Collections.synchronizedList(new ArrayList<Feed>());
categories = new ArrayList<FeedCategory>();
unreadItems = Collections.synchronizedList(new ArrayList<FeedItem>());
requester = DownloadRequester.getInstance();
downloadLog = new ArrayList<DownloadStatus>();
queue = Collections.synchronizedList(new ArrayList<FeedItem>());
contentChanger = new Handler();
dbExec = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
}
public static FeedManager getInstance() {
if (singleton == null) {
singleton = new FeedManager();
}
return singleton;
}
/**
* Play FeedMedia and start the playback service + launch Mediaplayer
* Activity.
*
* @param context
* for starting the playbackservice
* @param media
* that shall be played
* @param showPlayer
* if Mediaplayer activity shall be started
* @param startWhenPrepared
* if Mediaplayer shall be started after it has been prepared
*/
public void playMedia(Context context, FeedMedia media, boolean showPlayer,
boolean startWhenPrepared, boolean shouldStream) {
// Start playback Service
Intent launchIntent = new Intent(context, PlaybackService.class);
launchIntent.putExtra(PlaybackService.EXTRA_MEDIA_ID, media.getId());
launchIntent.putExtra(PlaybackService.EXTRA_FEED_ID, media.getItem()
.getFeed().getId());
launchIntent.putExtra(PlaybackService.EXTRA_START_WHEN_PREPARED,
startWhenPrepared);
launchIntent
.putExtra(PlaybackService.EXTRA_SHOULD_STREAM, shouldStream);
context.startService(launchIntent);
if (showPlayer) {
// Launch Mediaplayer
context.startActivity(PlaybackService.getPlayerActivityIntent(
context, media));
}
}
/** Remove media item that has been downloaded. */
public boolean deleteFeedMedia(Context context, FeedMedia media) {
boolean result = false;
if (media.isDownloaded()) {
File mediaFile = new File(media.file_url);
if (mediaFile.exists()) {
result = mediaFile.delete();
}
media.setDownloaded(false);
media.setFile_url(null);
setFeedMedia(context, media);
}
if (AppConfig.DEBUG)
Log.d(TAG, "Deleting File. Result: " + result);
return result;
}
/** Remove a feed with all its items and media files and its image. */
public void deleteFeed(final Context context, final Feed feed) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
DownloadRequester requester = DownloadRequester.getInstance();
adapter.open();
// delete image file
if (feed.getImage() != null) {
if (feed.getImage().isDownloaded()
&& feed.getImage().getFile_url() != null) {
File imageFile = new File(feed.getImage().getFile_url());
imageFile.delete();
}
} else if (requester.isDownloadingFile(feed.getImage())) {
requester.cancelDownload(context, feed.getImage()
.getDownloadId());
}
// delete stored media files and mark them as read
for (FeedItem item : feed.getItems()) {
if (!item.isRead()) {
unreadItems.remove(item);
}
if (queue.contains(item)) {
removeQueueItem(item, adapter);
}
if (item.getMedia() != null
&& item.getMedia().isDownloaded()) {
File mediaFile = new File(item.getMedia().getFile_url());
mediaFile.delete();
} else if (item.getMedia() != null
&& requester.isDownloadingFile(item.getMedia())) {
requester.cancelDownload(context, item.getMedia()
.getDownloadId());
}
}
adapter.removeFeed(feed);
adapter.close();
contentChanger.post(new Runnable() {
@Override
public void run() {
feeds.remove(feed);
sendFeedUpdateBroadcast(context);
}
});
}
});
}
private void sendUnreadItemsUpdateBroadcast(Context context, FeedItem item) {
Intent update = new Intent(ACTION_UNREAD_ITEMS_UPDATE);
if (item != null) {
update.putExtra(EXTRA_FEED_ID, item.getFeed().getId());
update.putExtra(EXTRA_FEED_ITEM_ID, item.getId());
}
context.sendBroadcast(update);
}
private void sendQueueUpdateBroadcast(Context context, FeedItem item) {
Intent update = new Intent(ACTION_QUEUE_UPDATE);
if (item != null) {
update.putExtra(EXTRA_FEED_ID, item.getFeed().getId());
update.putExtra(EXTRA_FEED_ITEM_ID, item.getId());
}
context.sendBroadcast(update);
}
private void sendFeedUpdateBroadcast(Context context) {
context.sendBroadcast(new Intent(ACITON_FEED_LIST_UPDATE));
}
/**
* Sets the 'read'-attribute of a FeedItem. Should be used by all Classes
* instead of the setters of FeedItem.
*/
public void markItemRead(final Context context, final FeedItem item,
final boolean read) {
if (AppConfig.DEBUG)
Log.d(TAG, "Setting item with title " + item.getTitle()
+ " as read/unread");
item.read = read;
setFeedItem(context, item);
contentChanger.post(new Runnable() {
@Override
public void run() {
if (read == true) {
unreadItems.remove(item);
} else {
unreadItems.add(item);
Collections.sort(unreadItems,
new FeedItemPubdateComparator());
}
sendUnreadItemsUpdateBroadcast(context, item);
}
});
}
/**
* Sets the 'read' attribute of all FeedItems of a specific feed to true
*
* @param context
*/
public void markFeedRead(Context context, Feed feed) {
for (FeedItem item : feed.getItems()) {
if (unreadItems.contains(item)) {
markItemRead(context, item, true);
}
}
}
/** Marks all items in the unread items list as read */
public void markAllItemsRead(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "marking all items as read");
for (FeedItem item : unreadItems) {
item.read = true;
}
unreadItems.clear();
sendUnreadItemsUpdateBroadcast(context, null);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
for (FeedItem item : unreadItems) {
setFeedItem(item, adapter);
}
adapter.close();
}
});
}
@SuppressLint("NewApi")
public void refreshAllFeeds(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "Refreshing all feeds.");
if (!isStartingFeedRefresh) {
isStartingFeedRefresh = true;
AsyncTask<Void, Void, Void> updateWorker = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
if (AppConfig.DEBUG)
Log.d(TAG,
"All feeds have been sent to the downloadmanager");
isStartingFeedRefresh = false;
}
@Override
protected Void doInBackground(Void... params) {
for (Feed feed : feeds) {
refreshFeed(context, feed);
}
return null;
}
};
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
updateWorker.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
updateWorker.execute();
}
}
}
/**
* Notifies the feed manager that the an image file is invalid. It will try
* to redownload it
*/
public void notifyInvalidImageFile(Context context, FeedImage image) {
Log.i(TAG,
"The feedmanager was notified about an invalid image download. It will now try to redownload the image file");
requester.downloadImage(context, image);
}
public void refreshFeed(Context context, Feed feed) {
requester.downloadFeed(context, new Feed(feed.getDownload_url(),
new Date()));
}
public void addDownloadStatus(final Context context,
final DownloadStatus status) {
downloadLog.add(status);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
if (downloadLog.size() > DOWNLOAD_LOG_SIZE) {
adapter.removeDownloadStatus(downloadLog.remove(0));
}
adapter.setDownloadStatus(status);
adapter.close();
}
});
}
public void addQueueItem(final Context context, final FeedItem item) {
contentChanger.post(new Runnable() {
@Override
public void run() {
queue.add(item);
sendQueueUpdateBroadcast(context, item);
}
});
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
/** Removes all items in queue */
public void clearQueue(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "Clearing queue");
queue.clear();
sendQueueUpdateBroadcast(context, null);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
/** Uses external adapter. */
public void removeQueueItem(FeedItem item, PodDBAdapter adapter) {
boolean removed = queue.remove(item);
if (removed) {
adapter.setQueue(queue);
}
}
/** Uses its own adapter. */
public void removeQueueItem(final Context context, FeedItem item) {
boolean removed = queue.remove(item);
if (removed) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
sendQueueUpdateBroadcast(context, item);
}
public void moveQueueItem(final Context context, FeedItem item, int delta) {
if (AppConfig.DEBUG)
Log.d(TAG, "Moving queue item");
int itemIndex = queue.indexOf(item);
int newIndex = itemIndex + delta;
if (newIndex >= 0 && newIndex < queue.size()) {
FeedItem oldItem = queue.set(newIndex, item);
queue.set(itemIndex, oldItem);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
sendQueueUpdateBroadcast(context, item);
}
public boolean isInQueue(FeedItem item) {
return queue.contains(item);
}
public FeedItem getFirstQueueItem() {
if (queue.isEmpty()) {
return null;
} else {
return queue.get(0);
}
}
private void addNewFeed(final Context context, final Feed feed) {
contentChanger.post(new Runnable() {
@Override
public void run() {
feeds.add(feed);
Collections.sort(feeds, new FeedtitleComparator());
sendFeedUpdateBroadcast(context);
}
});
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setCompleteFeed(feed);
adapter.close();
}
});
}
/**
* Updates an existing feed or adds it as a new one if it doesn't exist.
*
* @return The saved Feed with a database ID
*/
public Feed updateFeed(Context context, final Feed newFeed) {
// Look up feed in the feedslist
final Feed savedFeed = searchFeedByLink(newFeed.getLink());
if (savedFeed == null) {
if (AppConfig.DEBUG)
Log.d(TAG,
"Found no existing Feed with title "
+ newFeed.getTitle() + ". Adding as new one.");
// Add a new Feed
addNewFeed(context, newFeed);
return newFeed;
} else {
if (AppConfig.DEBUG)
Log.d(TAG, "Feed with title " + newFeed.getTitle()
+ " already exists. Syncing new with existing one.");
// Look for new or updated Items
for (int idx = 0; idx < newFeed.getItems().size(); idx++) {
final FeedItem item = newFeed.getItems().get(idx);
FeedItem oldItem = searchFeedItemByIdentifyingValue(savedFeed,
item.getIdentifyingValue());
if (oldItem == null) {
// item is new
final int i = idx;
item.setFeed(savedFeed);
contentChanger.post(new Runnable() {
@Override
public void run() {
savedFeed.getItems().add(i, item);
}
});
markItemRead(context, item, false);
}
}
// update attributes
savedFeed.setLastUpdate(newFeed.getLastUpdate());
savedFeed.setType(newFeed.getType());
setFeed(context, savedFeed);
return savedFeed;
}
}
/** Get a Feed by its link */
private Feed searchFeedByLink(String link) {
for (Feed feed : feeds) {
if (feed.getLink().equals(link)) {
return feed;
}
}
return null;
}
/**
* Returns true if a feed with the given download link is already in the
* feedlist.
*/
public boolean feedExists(String downloadUrl) {
for (Feed feed : feeds) {
if (feed.getDownload_url().equals(downloadUrl)) {
return true;
}
}
return false;
}
/** Get a FeedItem by its identifying value. */
private FeedItem searchFeedItemByIdentifyingValue(Feed feed,
String identifier) {
for (FeedItem item : feed.getItems()) {
if (item.getIdentifyingValue().equals(identifier)) {
return item;
}
}
return null;
}
/** Updates Information of an existing Feed. Uses external adapter. */
public void setFeed(Feed feed, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setFeed(feed);
} else {
Log.w(TAG, "Adapter in setFeed was null");
}
}
/** Updates Information of an existing Feeditem. Uses external adapter. */
public void setFeedItem(FeedItem item, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setSingleFeedItem(item);
} else {
Log.w(TAG, "Adapter in setFeedItem was null");
}
}
/** Updates Information of an existing Feedimage. Uses external adapter. */
public void setFeedImage(FeedImage image, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setImage(image);
} else {
Log.w(TAG, "Adapter in setFeedImage was null");
}
}
/**
* Updates Information of an existing Feedmedia object. Uses external
* adapter.
*/
public void setFeedImage(FeedMedia media, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setMedia(media);
} else {
Log.w(TAG, "Adapter in setFeedMedia was null");
}
}
/**
* Updates Information of an existing Feed. Creates and opens its own
* adapter.
*/
public void setFeed(final Context context, final Feed feed) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setFeed(feed);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedItem. Creates and opens its own
* adapter.
*/
public void setFeedItem(final Context context, final FeedItem item) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setSingleFeedItem(item);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedImage. Creates and opens its own
* adapter.
*/
public void setFeedImage(final Context context, final FeedImage image) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setImage(image);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedMedia object. Creates and opens
* its own adapter.
*/
public void setFeedMedia(final Context context, final FeedMedia media) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setMedia(media);
adapter.close();
}
});
}
/** Get a Feed by its id */
public Feed getFeed(long id) {
for (Feed f : feeds) {
if (f.id == id) {
return f;
}
}
Log.e(TAG, "Couldn't find Feed with id " + id);
return null;
}
/** Get a Feed Image by its id */
public FeedImage getFeedImage(long id) {
for (Feed f : feeds) {
FeedImage image = f.getImage();
if (image != null && image.getId() == id) {
return image;
}
}
return null;
}
/** Get a Feed Item by its id and its feed */
public FeedItem getFeedItem(long id, Feed feed) {
if (feed != null) {
for (FeedItem item : feed.getItems()) {
if (item.getId() == id) {
return item;
}
}
}
Log.e(TAG, "Couldn't find FeedItem with id " + id);
return null;
}
/** Get a FeedMedia object by the id of the Media object and the feed object */
public FeedMedia getFeedMedia(long id, Feed feed) {
if (feed != null) {
for (FeedItem item : feed.getItems()) {
if (item.getMedia().getId() == id) {
return item.getMedia();
}
}
}
Log.e(TAG, "Couldn't find FeedMedia with id " + id);
if (feed == null)
Log.e(TAG, "Feed was null");
return null;
}
/** Get a FeedMedia object by the id of the Media object. */
public FeedMedia getFeedMedia(long id) {
for (Feed feed : feeds) {
for (FeedItem item : feed.getItems()) {
if (item.getMedia() != null && item.getMedia().getId() == id) {
return item.getMedia();
}
}
}
Log.w(TAG, "Couldn't find FeedMedia with id " + id);
return null;
}
public DownloadStatus getDownloadStatus(FeedFile feedFile) {
for (DownloadStatus status : downloadLog) {
if (status.getFeedFile() == feedFile) {
return status;
}
}
return null;
}
/** Reads the database */
public void loadDBData(Context context) {
updateArrays(context);
}
public void updateArrays(Context context) {
feeds.clear();
categories.clear();
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
extractFeedlistFromCursor(context, adapter);
extractDownloadLogFromCursor(context, adapter);
extractQueueFromCursor(context, adapter);
adapter.close();
Collections.sort(feeds, new FeedtitleComparator());
Collections.sort(unreadItems, new FeedItemPubdateComparator());
}
private void extractFeedlistFromCursor(Context context, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Feedlist");
Cursor feedlistCursor = adapter.getAllFeedsCursor();
if (feedlistCursor.moveToFirst()) {
do {
Date lastUpdate = new Date(
feedlistCursor
.getLong(PodDBAdapter.KEY_LAST_UPDATE_INDEX));
Feed feed = new Feed(lastUpdate);
feed.id = feedlistCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
feed.setTitle(feedlistCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX));
feed.setLink(feedlistCursor
.getString(PodDBAdapter.KEY_LINK_INDEX));
feed.setDescription(feedlistCursor
.getString(PodDBAdapter.KEY_DESCRIPTION_INDEX));
feed.setPaymentLink(feedlistCursor
.getString(PodDBAdapter.KEY_PAYMENT_LINK_INDEX));
feed.setAuthor(feedlistCursor
.getString(PodDBAdapter.KEY_AUTHOR_INDEX));
feed.setLanguage(feedlistCursor
.getString(PodDBAdapter.KEY_LANGUAGE_INDEX));
feed.setType(feedlistCursor
.getString(PodDBAdapter.KEY_TYPE_INDEX));
long imageIndex = feedlistCursor
.getLong(PodDBAdapter.KEY_IMAGE_INDEX);
if (imageIndex != 0) {
feed.setImage(adapter.getFeedImage(imageIndex));
feed.getImage().setFeed(feed);
}
feed.file_url = feedlistCursor
.getString(PodDBAdapter.KEY_FILE_URL_INDEX);
feed.download_url = feedlistCursor
.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX);
feed.setDownloaded(feedlistCursor
.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0);
// Get FeedItem-Object
Cursor itemlistCursor = adapter.getAllItemsOfFeedCursor(feed);
feed.setItems(extractFeedItemsFromCursor(context, feed,
itemlistCursor, adapter));
itemlistCursor.close();
feeds.add(feed);
} while (feedlistCursor.moveToNext());
}
feedlistCursor.close();
}
private ArrayList<FeedItem> extractFeedItemsFromCursor(Context context,
Feed feed, Cursor itemlistCursor, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Feeditems of feed " + feed.getTitle());
ArrayList<FeedItem> items = new ArrayList<FeedItem>();
ArrayList<String> mediaIds = new ArrayList<String>();
if (itemlistCursor.moveToFirst()) {
do {
FeedItem item = new FeedItem();
item.id = itemlistCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
item.setFeed(feed);
item.setTitle(itemlistCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX));
item.setLink(itemlistCursor
.getString(PodDBAdapter.KEY_LINK_INDEX));
item.setDescription(itemlistCursor
.getString(PodDBAdapter.KEY_DESCRIPTION_INDEX));
item.setContentEncoded(itemlistCursor
.getString(PodDBAdapter.KEY_CONTENT_ENCODED_INDEX));
item.setPubDate(new Date(itemlistCursor
.getLong(PodDBAdapter.KEY_PUBDATE_INDEX)));
item.setPaymentLink(itemlistCursor
.getString(PodDBAdapter.KEY_PAYMENT_LINK_INDEX));
long mediaId = itemlistCursor
.getLong(PodDBAdapter.KEY_MEDIA_INDEX);
if (mediaId != 0) {
mediaIds.add(String.valueOf(mediaId));
item.setMedia(new FeedMedia(mediaId, item));
}
item.read = (itemlistCursor.getInt(PodDBAdapter.KEY_READ_INDEX) > 0) ? true
: false;
item.setItemIdentifier(itemlistCursor
.getString(PodDBAdapter.KEY_ITEM_IDENTIFIER_INDEX));
if (!item.read) {
unreadItems.add(item);
}
// extract chapters
boolean hasSimpleChapters = itemlistCursor
.getInt(PodDBAdapter.KEY_HAS_SIMPLECHAPTERS_INDEX) > 0;
if (hasSimpleChapters) {
Cursor chapterCursor = adapter
.getSimpleChaptersOfFeedItemCursor(item);
if (chapterCursor.moveToFirst()) {
item.setSimpleChapters(new ArrayList<SimpleChapter>());
do {
SimpleChapter chapter = new SimpleChapter(
item,
chapterCursor
.getLong(PodDBAdapter.KEY_SC_START_INDEX),
chapterCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX),
chapterCursor
.getString(PodDBAdapter.KEY_SC_LINK_INDEX));
chapter.setId(chapterCursor
.getLong(PodDBAdapter.KEY_ID_INDEX));
item.getSimpleChapters().add(chapter);
} while (chapterCursor.moveToNext());
}
chapterCursor.close();
}
items.add(item);
} while (itemlistCursor.moveToNext());
}
extractMediafromFeedItemlist(adapter, items, mediaIds);
Collections.sort(items, new FeedItemPubdateComparator());
return items;
}
private void extractMediafromFeedItemlist(PodDBAdapter adapter,
ArrayList<FeedItem> items, ArrayList<String> mediaIds) {
ArrayList<FeedItem> itemsCopy = new ArrayList<FeedItem>(items);
Cursor cursor = adapter.getFeedMediaCursor(mediaIds
.toArray(new String[mediaIds.size()]));
if (cursor.moveToFirst()) {
do {
long mediaId = cursor.getLong(PodDBAdapter.KEY_ID_INDEX);
// find matching feed item
FeedItem item = getMatchingItemForMedia(mediaId, itemsCopy);
itemsCopy.remove(item);
if (item != null) {
item.setMedia(new FeedMedia(
mediaId,
item,
cursor.getInt(PodDBAdapter.KEY_DURATION_INDEX),
cursor.getInt(PodDBAdapter.KEY_POSITION_INDEX),
cursor.getLong(PodDBAdapter.KEY_SIZE_INDEX),
cursor.getString(PodDBAdapter.KEY_MIME_TYPE_INDEX),
cursor.getString(PodDBAdapter.KEY_FILE_URL_INDEX),
cursor.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX),
cursor.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0));
}
} while (cursor.moveToNext());
cursor.close();
}
}
private FeedItem getMatchingItemForMedia(long mediaId,
ArrayList<FeedItem> items) {
for (FeedItem item : items) {
if (item.getMedia() != null && item.getMedia().getId() == mediaId) {
return item;
}
}
return null;
}
private void extractDownloadLogFromCursor(Context context,
PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting DownloadLog");
Cursor logCursor = adapter.getDownloadLogCursor();
if (logCursor.moveToFirst()) {
do {
long id = logCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
long feedfileId = logCursor
.getLong(PodDBAdapter.KEY_FEEDFILE_INDEX);
int feedfileType = logCursor
.getInt(PodDBAdapter.KEY_FEEDFILETYPE_INDEX);
FeedFile feedfile = null;
switch (feedfileType) {
case PodDBAdapter.FEEDFILETYPE_FEED:
feedfile = getFeed(feedfileId);
break;
case PodDBAdapter.FEEDFILETYPE_FEEDIMAGE:
feedfile = getFeedImage(feedfileId);
break;
case PodDBAdapter.FEEDFILETYPE_FEEDMEDIA:
feedfile = getFeedMedia(feedfileId);
}
if (feedfile != null) { // otherwise ignore status
boolean successful = logCursor
.getInt(PodDBAdapter.KEY_SUCCESSFUL_INDEX) > 0;
int reason = logCursor
.getInt(PodDBAdapter.KEY_REASON_INDEX);
Date completionDate = new Date(
logCursor
.getLong(PodDBAdapter.KEY_COMPLETION_DATE_INDEX));
downloadLog.add(new DownloadStatus(id, feedfile,
successful, reason, completionDate));
}
} while (logCursor.moveToNext());
}
logCursor.close();
}
private void extractQueueFromCursor(Context context, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Queue");
Cursor cursor = adapter.getQueueCursor();
if (cursor.moveToFirst()) {
do {
int index = cursor.getInt(PodDBAdapter.KEY_ID_INDEX);
Feed feed = getFeed(cursor
.getLong(PodDBAdapter.KEY_QUEUE_FEED_INDEX));
if (feed != null) {
FeedItem item = getFeedItem(
cursor.getLong(PodDBAdapter.KEY_FEEDITEM_INDEX),
feed);
if (item != null) {
queue.add(index, item);
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
public List<Feed> getFeeds() {
return feeds;
}
public List<FeedItem> getUnreadItems() {
return unreadItems;
}
public ArrayList<DownloadStatus> getDownloadLog() {
return downloadLog;
}
public List<FeedItem> getQueue() {
return queue;
}
} |
package de.geeksfactory.opacclient.apis;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.objects.SearchResult.Status;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
/**
* Implementation of Fleischmann iOpac, including account support Seems to work
* in all the libraries currently supported without any modifications.
*
* @author Johan von Forstner, 17.09.2013
* */
public class IOpac extends BaseApi implements OpacApi {
protected String opac_url = "";
protected String dir = "/iopac";
protected JSONObject data;
protected boolean initialised = false;
protected Library library;
protected int resultcount = 10;
protected String reusehtml;
protected String rechnr;
protected int results_total;
protected int maxProlongCount = -1;
CookieStore cookieStore = new BasicCookieStore();
protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>();
static {
defaulttypes.put("b", MediaType.BOOK);
defaulttypes.put("o", MediaType.BOOK);
defaulttypes.put("e", MediaType.BOOK);
defaulttypes.put("p", MediaType.BOOK);
defaulttypes.put("j", MediaType.BOOK);
defaulttypes.put("g", MediaType.BOOK);
defaulttypes.put("k", MediaType.BOOK);
defaulttypes.put("a", MediaType.BOOK);
defaulttypes.put("c", MediaType.AUDIOBOOK);
defaulttypes.put("u", MediaType.AUDIOBOOK);
defaulttypes.put("l", MediaType.AUDIOBOOK);
defaulttypes.put("q", MediaType.CD_SOFTWARE);
defaulttypes.put("r", MediaType.CD_SOFTWARE);
defaulttypes.put("v", MediaType.MOVIE);
defaulttypes.put("d", MediaType.CD_MUSIC);
defaulttypes.put("n", MediaType.SCORE_MUSIC);
defaulttypes.put("s", MediaType.BOARDGAME);
defaulttypes.put("z", MediaType.MAGAZINE);
defaulttypes.put("x", MediaType.MAGAZINE);
}
@Override
public void start() throws IOException, NotReachableException {
}
@Override
public void init(Library lib) {
super.init(lib);
this.library = lib;
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
if (data.has("maxprolongcount"))
this.maxProlongCount = data.getInt("maxprolongcount");
if (data.has("dir"))
this.dir = data.getString("dir");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
protected int addParameters(SearchQuery query, List<NameValuePair> params,
int index) {
if (query.getValue().equals(""))
return index;
params.add(new BasicNameValuePair(query.getKey(), query.getValue()));
return index + 1;
}
@Override
public SearchRequestResult search(List<SearchQuery> queries)
throws IOException, NotReachableException, OpacErrorException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
int index = 0;
start();
for (SearchQuery query : queries) {
index = addParameters(query, params, index);
}
params.add(new BasicNameValuePair("Anzahl", "10"));
params.add(new BasicNameValuePair("pshStart", "Suchen"));
if (index == 0) {
throw new OpacErrorException(
stringProvider.getString(StringProvider.NO_CRITERIA_INPUT));
}
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
return parse_search(html, 1);
}
protected SearchRequestResult parse_search(String html, int page)
throws OpacErrorException, NotReachableException {
Document doc = Jsoup.parse(html);
if (doc.select("h4").size() > 0) {
if (doc.select("h4").text().trim().startsWith("0 gefundene Medien")) {
// nothing found
return new SearchRequestResult(new ArrayList<SearchResult>(),
0, 1, 1);
} else if (!doc.select("h4").text().trim()
.contains("gefundene Medien")
&& !doc.select("h4").text().trim()
.contains("Es wurden mehr als")) {
// error
throw new OpacErrorException(doc.select("h4").text().trim());
}
} else if (doc.select("h1").size() > 0) {
if (doc.select("h1").text().trim().contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(stringProvider.getFormattedString(
StringProvider.UNKNOWN_ERROR_WITH_DESCRIPTION, doc
.select("h1").text().trim()));
}
} else {
return null;
}
updateRechnr(doc);
reusehtml = html;
results_total = -1;
if (doc.select("h4").text().trim().contains("Es wurden mehr als")) {
results_total = 200;
} else {
String resultnumstr = doc.select("h4").first().text();
resultnumstr = resultnumstr.substring(0, resultnumstr.indexOf(" "))
.trim();
results_total = Integer.parseInt(resultnumstr);
}
List<SearchResult> results = new ArrayList<SearchResult>();
Elements tables = doc.select("table").first().select("tr:has(td)");
Map<String, Integer> colmap = new HashMap<String, Integer>();
Element thead = doc.select("table").first().select("tr:has(th)")
.first();
int j = 0;
for (Element th : thead.select("th")) {
String text = th.text().trim().toLowerCase(Locale.GERMAN);
if (text.contains("cover"))
colmap.put("cover", j);
else if (text.contains("titel"))
colmap.put("title", j);
else if (text.contains("verfasser"))
colmap.put("author", j);
else if (text.contains("mtyp"))
colmap.put("category", j);
else if (text.contains("jahr"))
colmap.put("year", j);
else if (text.contains("signatur"))
colmap.put("shelfmark", j);
else if (text.contains("info"))
colmap.put("info", j);
else if (text.contains("abteilung"))
colmap.put("department", j);
else if (text.contains("verliehen") || text.contains("verl."))
colmap.put("returndate", j);
else if (text.contains("anz.res"))
colmap.put("reservations", j);
j++;
}
if (colmap.size() == 0) {
colmap.put("cover", 0);
colmap.put("title", 1);
colmap.put("author", 2);
colmap.put("publisher", 3);
colmap.put("year", 4);
colmap.put("department", 5);
colmap.put("shelfmark", 6);
colmap.put("returndate", 7);
colmap.put("category", 8);
}
for (int i = 0; i < tables.size(); i++) {
Element tr = tables.get(i);
SearchResult sr = new SearchResult();
if (tr.select("td").get(colmap.get("cover")).select("img").size() > 0) {
String imgUrl = tr.select("td").get(colmap.get("cover"))
.select("img").first().attr("src");
sr.setCover(imgUrl);
}
// Media Type
if (colmap.get("category") != null) {
String mType = tr.select("td").get(colmap.get("category"))
.text().trim().replace("\u00a0", "");
if (data.has("mediatypes")) {
try {
sr.setType(MediaType.valueOf(data.getJSONObject(
"mediatypes").getString(
mType.toLowerCase(Locale.GERMAN))));
} catch (JSONException e) {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
} catch (IllegalArgumentException e) {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
} else {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
}
// Title and additional info
String title = "";
String additionalInfo = "";
if (colmap.get("info") != null) {
Element info = tr.select("td").get(colmap.get("info"));
title = info.select("a[title=Details-Info]").text().trim();
String authorIn = info.text().substring(0,
info.text().indexOf(title));
if (authorIn.contains(":")) {
authorIn = authorIn.replaceFirst("^([^:]*):(.*)$", "$1");
additionalInfo += " - " + authorIn;
}
} else {
title = tr.select("td").get(colmap.get("title")).text().trim()
.replace("\u00a0", "");
if (title.contains("(")) {
additionalInfo += title.substring(title.indexOf("("));
title = title.substring(0, title.indexOf("(") - 1).trim();
}
// Author
if (colmap.containsKey("author")) {
String author = tr.select("td").get(colmap.get("author"))
.text().trim().replace("\u00a0", "");
additionalInfo += " - " + author;
}
}
// Publisher
if (colmap.containsKey("publisher")) {
String publisher = tr.select("td").get(colmap.get("publisher"))
.text().trim().replace("\u00a0", "");
additionalInfo += " (" + publisher;
}
// Year
if (colmap.containsKey("year")) {
String year = tr.select("td").get(colmap.get("year")).text()
.trim().replace("\u00a0", "");
additionalInfo += ", " + year + ")";
}
sr.setInnerhtml("<b>" + title + "</b><br>" + additionalInfo);
// Status
String status = tr.select("td").get(colmap.get("returndate"))
.text().trim().replace("\u00a0", "");
if (status.equals("")
|| status.toLowerCase(Locale.GERMAN).contains("onleihe")
|| status.contains("verleihbar")
|| status.contains("entleihbar")
|| status.contains("ausleihbar")) {
sr.setStatus(Status.GREEN);
} else {
sr.setStatus(Status.RED);
sr.setInnerhtml(sr.getInnerhtml() + "<br><i>"
+ stringProvider.getString(StringProvider.LENT_UNTIL)
+ " " + status + "</i>");
}
// In some libraries (for example search for "atelier" in Preetz)
// the results are sorted differently than their numbers suggest, so
// we need to detect the number ("recno") from the link
String link = tr.select("a[href^=/cgi-bin/di.exe?page=]").attr(
"href");
Map<String, String> params = getQueryParamsFirst(link);
if (params.containsKey("recno")) {
int recno = Integer.valueOf(params.get("recno"));
sr.setNr(10 * (page - 1) + recno - 1);
} else {
// the above should work, but fall back to this if it doesn't
sr.setNr(10 * (page - 1) + i);
}
// In some libraries (for example Preetz) we can detect the media ID
// here using another link present in the search results
Elements idLinks = tr.select("a[href^=/cgi-bin/di.exe?cMedNr]");
if (idLinks.size() > 0) {
Map<String, String> idParams = getQueryParamsFirst(idLinks.first().attr("href"));
String id = idParams.get("cMedNr");
sr.setId(id);
} else {
sr.setId(null);
}
results.add(sr);
}
resultcount = results.size();
return new SearchRequestResult(results, results_total, page);
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
NotReachableException, OpacErrorException {
if (!initialised)
start();
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&FilNr=",
getDefaultEncoding());
return parse_search(html, page);
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException, NotReachableException {
return null;
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException, NotReachableException {
if (id == null && reusehtml != null) {
return parse_result(reusehtml);
}
String html = httpGet(opac_url + "/cgi-bin/di.exe?cMedNr=" + id
+ "&mode=23", getDefaultEncoding());
return parse_result(html);
}
@Override
public DetailledItem getResult(int position) throws IOException {
int page = Double.valueOf(Math.floor(position / 10)).intValue() + 1;
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&recno=" + (position + 1)
+ "&FilNr=", getDefaultEncoding());
return parse_result(html);
}
protected DetailledItem parse_result(String html) throws IOException {
Document doc = Jsoup.parse(html);
DetailledItem result = new DetailledItem();
String id = null;
if (doc.select("input[name=mednr]").size() > 0)
id = doc.select("input[name=mednr]").first().val().trim();
else {
for (Element a : doc.select("table").last().select("td a")) {
if (a.attr("href").contains("mednr=")) {
id = a.attr("href");
break;
}
}
Integer idPosition = id.indexOf("mednr=") + 6;
id = id.substring(idPosition, id.indexOf("&", idPosition)).trim();
}
result.setId(id);
Elements table = doc.select("table").get(1).select("tr");
// GET COVER IMAGE
String imgUrl = table.get(0)
.select("img[src^=http://images-eu.amazon.com]").attr("src")
.replace("TZZZZZZZ", "L");
result.setCover(imgUrl);
// GET INFORMATION
Map<String, String> e = new HashMap<String, String>();
for (Element element : table) {
String detail = element.select("td").text().trim()
.replace("\u00a0", "");
String title = element.select("th").text().trim()
.replace("\u00a0", "");
if (!title.equals("")) {
if (title.contains("verliehen bis")) {
if (detail.equals("")) {
e.put(DetailledItem.KEY_COPY_STATUS, "verfügbar");
} else {
e.put(DetailledItem.KEY_COPY_STATUS, "verliehen bis "
+ detail);
}
} else if (title.contains("Abteilung")) {
e.put(DetailledItem.KEY_COPY_DEPARTMENT, detail);
} else if (title.contains("Signatur")) {
e.put(DetailledItem.KEY_COPY_SHELFMARK, detail);
} else if (title.contains("Titel")) {
result.setTitle(detail);
} else if (!title.contains("Cover")) {
result.addDetail(new Detail(title, detail));
}
}
}
// GET RESERVATION INFO
if ("verfügbar".equals(e.get(DetailledItem.KEY_COPY_STATUS))
|| doc.select(
"a[href^=/cgi-bin/di.exe?mode=10], input.resbutton")
.size() == 0) {
result.setReservable(false);
} else {
result.setReservable(true);
if (doc.select("a[href^=/cgi-bin/di.exe?mode=10]").size() > 0) {
// Reservation via link
result.setReservation_info(doc
.select("a[href^=/cgi-bin/di.exe?mode=10]").first()
.attr("href").substring(1).replace(" ", ""));
} else {
// Reservation via form (method="get")
Element form = doc.select("input.resbutton").first().parent();
result.setReservation_info(generateQuery(form));
}
}
result.addCopy(e);
return result;
}
private String generateQuery(Element form)
throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(form.attr("action").substring(1));
int i = 0;
for (Element input : form.select("input")) {
builder.append(i == 0 ? "?" : "&");
builder.append(input.attr("name") + "="
+ URLEncoder.encode(input.attr("value"), "UTF-8"));
i++;
}
return builder.toString();
}
@Override
public ReservationResult reservation(DetailledItem item, Account account,
int useraction, String selection) throws IOException {
String reservation_info = item.getReservation_info();
// STEP 1: Login page
String html = httpGet(opac_url + "/" + reservation_info,
getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table").first().text().contains("kann nicht")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
}
if (doc.select("form[name=form1]").size() == 0)
return new ReservationResult(MultiStepResult.Status.ERROR);
Element form = doc.select("form[name=form1]").first();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Reservieren"));
for (Element input : form.select("input[type=hidden]")) {
params.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
// STEP 2: Confirmation page
html = httpPost(opac_url + "/cgi-bin/di.exe", new UrlEncodedFormEntity(
params), getDefaultEncoding());
doc = Jsoup.parse(html);
if (doc.select("form[name=form1]").size() > 0) {
// STEP 3: There is another confirmation needed
form = doc.select("form[name=form1]").first();
html = httpGet(opac_url + "/" + generateQuery(form),
getDefaultEncoding());
doc = Jsoup.parse(html);
}
if (doc.select("h1").text().contains("fehlgeschlagen")
|| doc.select("h1").text().contains("Achtung")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
} else {
return new ReservationResult(MultiStepResult.Status.OK);
}
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String Selection) throws IOException {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table th").size() > 0) {
if (doc.select("h1").size() > 0) {
if (doc.select("h1").first().text().contains("Hinweis")) {
return new ProlongResult(MultiStepResult.Status.ERROR, doc
.select("table th").first().text());
}
}
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=8&kndnr="
+ account.getName() + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Verl%C3%A4ngern",
getDefaultEncoding());
return new ProlongResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
return new ProlongResult(MultiStepResult.Status.ERROR);
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction,
String selection) throws IOException {
return null;
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=9&kndnr="
+ account.getName() + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Stornieren", getDefaultEncoding());
return new CancelResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
throw new NotReachableException();
}
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Login"));
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
Document doc = Jsoup.parse(html);
AccountData res = new AccountData(account.getId());
List<Map<String, String>> medien = new ArrayList<Map<String, String>>();
List<Map<String, String>> reserved = new ArrayList<Map<String, String>>();
if (doc.select("a[name=AUS]").size() > 0) {
parse_medialist(medien, doc, 1);
}
if (doc.select("a[name=RES]").size() > 0) {
parse_reslist(reserved, doc, 1);
}
res.setLent(medien);
res.setReservations(reserved);
if (medien.isEmpty() && reserved.isEmpty()) {
if (doc.select("h1").size() > 0) {
if (doc.select("h4").text().trim()
.contains("keine ausgeliehenen Medien")) {
// There is no lent media, but the server is working
// correctly
} else if (doc.select("h1").text().trim()
.contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(
stringProvider
.getFormattedString(
StringProvider.UNKNOWN_ERROR_ACCOUNT_WITH_DESCRIPTION,
doc.select("h1").text().trim()));
}
} else {
throw new OpacErrorException(
stringProvider
.getString(StringProvider.UNKNOWN_ERROR_ACCOUNT));
}
}
return res;
}
protected void parse_medialist(List<Map<String, String>> medien,
Document doc, int offset) throws ClientProtocolException,
IOException {
Elements copytrs = doc.select("a[name=AUS] ~ table").first()
.select("tr");
doc.setBaseUri(opac_url);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
int trs = copytrs.size();
if (trs < 2)
return;
assert (trs > 0);
JSONObject copymap = new JSONObject();
try {
if (data.has("accounttable"))
copymap = data.getJSONObject("accounttable");
} catch (JSONException e) {
}
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<String, String>();
if (copymap.optInt("title", 0) >= 0)
e.put(AccountData.KEY_LENT_TITLE,
tr.child(copymap.optInt("title", 0)).text().trim()
.replace("\u00a0", ""));
if (copymap.optInt("author", 0) >= 1)
e.put(AccountData.KEY_LENT_AUTHOR,
tr.child(copymap.optInt("author", 1)).text().trim()
.replace("\u00a0", ""));
int prolongCount = 0;
if (copymap.optInt("prolongcount", 3) >= 0)
prolongCount = Integer.parseInt(tr
.child(copymap.optInt("prolongcount", 3)).text().trim()
.replace("\u00a0", ""));
/*
* not needed currently, because in Schleswig books can only be pro-
* longed once, so the prolong count is visible from the renewable
* status e.put(AccountData.KEY_LENT_STATUS,
* String.valueOf(prolongCount) + "x verl.");
*/
if (maxProlongCount != -1) {
e.put(AccountData.KEY_LENT_RENEWABLE,
prolongCount < maxProlongCount ? "Y" : "N");
}
if (copymap.optInt("deadline", 4) >= 0)
e.put(AccountData.KEY_LENT_DEADLINE,
tr.child(copymap.optInt("deadline", 4)).text().trim()
.replace("\u00a0", ""));
try {
e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String
.valueOf(sdf
.parse(e.get(AccountData.KEY_LENT_DEADLINE))
.getTime()));
} catch (ParseException e1) {
e1.printStackTrace();
}
if (copymap.optInt("prolongurl", 5) >= 0) {
String link = tr.child(copymap.optInt("prolongurl", 5))
.select("a").attr("href");
e.put(AccountData.KEY_LENT_LINK, link);
// find media number with regex
Pattern pattern = Pattern.compile("mednr=([^&]*)&");
Matcher matcher = pattern.matcher(link);
matcher.find();
if (matcher.group() != null) {
e.put(AccountData.KEY_LENT_ID, matcher.group(1));
}
}
medien.add(e);
}
assert (medien.size() == trs - 1);
}
protected void parse_reslist(List<Map<String, String>> medien,
Document doc, int offset) throws ClientProtocolException,
IOException {
Elements copytrs = doc.select("a[name=RES] ~ table:contains(Titel)")
.first().select("tr");
doc.setBaseUri(opac_url);
int trs = copytrs.size();
if (trs < 2)
return;
assert (trs > 0);
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<String, String>();
e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(0).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_AUTHOR, tr.child(1).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_READY, tr.child(4).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_CANCEL, tr.child(5).select("a")
.attr("href"));
medien.add(e);
}
assert (medien.size() == trs - 1);
}
private SearchField createSearchField(Element descTd, Element inputTd) {
String name = descTd.select("span, blockquote").text().replace(":", "")
.trim().replace("\u00a0", "");
if (inputTd.select("select").size() > 0
&& !name.equals("Treffer/Seite") && !name.equals("Medientypen")
&& !name.equals("Treffer pro Seite")) {
Element select = inputTd.select("select").first();
DropdownSearchField field = new DropdownSearchField();
field.setDisplayName(name);
field.setId(select.attr("name"));
List<Map<String, String>> options = new ArrayList<Map<String, String>>();
for (Element option : select.select("option")) {
Map<String, String> map = new HashMap<String, String>();
map.put("key", option.attr("value"));
map.put("value", option.text());
options.add(map);
}
field.setDropdownValues(options);
return field;
} else if (inputTd.select("input").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = inputTd.select("input").first();
field.setDisplayName(name);
field.setId(input.attr("name"));
field.setHint("");
return field;
} else {
return null;
}
}
@Override
public List<SearchField> getSearchFields() throws IOException {
List<SearchField> fields = new ArrayList<SearchField>();
// Extract all search fields, except media types
String html;
try {
html = httpGet(opac_url + dir + "/search_expert.htm",
getDefaultEncoding());
} catch (NotReachableException e) {
html = httpGet(opac_url + dir + "/iopacie.htm",
getDefaultEncoding());
}
Document doc = Jsoup.parse(html);
Elements trs = doc
.select("form tr:has(input:not([type=submit], [type=reset])), form tr:has(select)");
for (Element tr : trs) {
Elements tds = tr.select("td");
if (tds.size() == 4) {
// Two search fields next to each other in one row
SearchField field1 = createSearchField(tds.get(0), tds.get(1));
SearchField field2 = createSearchField(tds.get(2), tds.get(3));
if (field1 != null)
fields.add(field1);
if (field2 != null)
fields.add(field2);
} else if (tds.size() == 2
|| (tds.size() == 3 && tds.get(2).children().size() == 0)) {
SearchField field = createSearchField(tds.get(0), tds.get(1));
if (field != null)
fields.add(field);
}
}
if (fields.size() == 0 && doc.select("[name=sleStichwort]").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = doc.select("input[name=sleStichwort]").first();
field.setDisplayName(stringProvider
.getString(StringProvider.FREE_SEARCH));
field.setId(input.attr("name"));
field.setHint("");
fields.add(field);
}
// Extract available media types.
// We have to parse JavaScript. Doing this with RegEx is evil.
// But not as evil as including a JavaScript VM into the app.
// And I honestly do not see another way.
Pattern pattern_key = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"typ\"\\] = \"([^\"]+)\";");
Pattern pattern_value = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"bez\"\\] = \"([^\"]+)\";");
List<Map<String, String>> mediatypes = new ArrayList<Map<String, String>>();
try {
html = httpGet(opac_url + dir + "/mtyp.js", getDefaultEncoding());
String[] parts = html.split("new Array\\(\\);");
for (String part : parts) {
Matcher matcher1 = pattern_key.matcher(part);
String key = "";
String value = "";
if (matcher1.find()) {
key = matcher1.group(1);
}
Matcher matcher2 = pattern_value.matcher(part);
if (matcher2.find()) {
value = matcher2.group(1);
}
if (value != "") {
Map<String, String> mediatype = new HashMap<String, String>();
mediatype.put("key", key);
mediatype.put("value", value);
mediatypes.add(mediatype);
}
}
} catch (IOException e) {
try {
html = httpGet(opac_url + dir
+ "/frames/search_form.php?bReset=1?bReset=1",
getDefaultEncoding());
doc = Jsoup.parse(html);
for (Element opt : doc.select("#imtyp option")) {
Map<String, String> mediatype = new HashMap<String, String>();
mediatype.put("key", opt.attr("value"));
mediatype.put("value", opt.text());
mediatypes.add(mediatype);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (mediatypes.size() > 0) {
DropdownSearchField mtyp = new DropdownSearchField();
mtyp.setDisplayName("Medientypen");
mtyp.setId("Medientyp");
mtyp.setDropdownValues(mediatypes);
fields.add(mtyp);
}
return fields;
}
@Override
public boolean isAccountSupported(Library library) {
if (data.has("account")) {
try {
return data.getBoolean("account");
} catch (JSONException e) {
return true;
}
}
return true;
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account account) throws IOException,
NotReachableException {
return null;
}
@Override
public String getShareUrl(String id, String title) {
return opac_url + "/cgi-bin/di.exe?cMedNr=" + id + "&mode=23";
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT;
}
public void updateRechnr(Document doc) {
String url = null;
for (Element a : doc.select("table a")) {
if (a.attr("href").contains("rechnr=")) {
url = a.attr("href");
break;
}
}
if (url == null)
return;
Integer rechnrPosition = url.indexOf("rechnr=") + 7;
rechnr = url
.substring(rechnrPosition, url.indexOf("&", rechnrPosition));
}
} |
package tigase.cluster;
import tigase.cluster.api.ClusterControllerIfc;
import tigase.cluster.api.ClusteredComponentIfc;
import tigase.cluster.api.SessionManagerClusteredIfc;
import tigase.cluster.strategy.ClusteringStrategyIfc;
import tigase.server.ComponentInfo;
import tigase.server.Message;
import tigase.server.Packet;
import tigase.server.xmppsession.SessionManager;
import tigase.stats.StatisticsList;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.XMPPSession;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
import javax.script.Bindings;
/**
* Class SessionManagerClusteredOld
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class SessionManagerClustered
extends SessionManager
implements ClusteredComponentIfc, SessionManagerClusteredIfc {
/** Field description */
public static final String CLUSTER_STRATEGY_VAR = "clusterStrategy";
/** Field description */
public static final String MY_DOMAIN_NAME_PROP_KEY = "domain-name";
/** Field description */
public static final String STRATEGY_CLASS_PROP_KEY = "sm-cluster-strategy-class";
/** Field description */
public static final String STRATEGY_CLASS_PROP_VAL =
"tigase.cluster.strategy.DefaultClusteringStrategy";
/** Field description */
public static final String STRATEGY_CLASS_PROPERTY = "--sm-cluster-strategy-class";
/** Field description */
public static final int SYNC_MAX_BATCH_SIZE = 1000;
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(SessionManagerClustered.class
.getName());
private ClusterControllerIfc clusterController = null;
private ComponentInfo cmpInfo = null;
private JID my_address = null;
private JID my_hostname = null;
private int nodesNo = 0;
private ClusteringStrategyIfc strategy = null;
/**
* The method checks whether the given JID is known to the installation,
* either user connected to local machine or any of the cluster nodes. False
* result does not mean the user is not connected. It means the method does
* not know anything about the JID. Some clustering strategies may not cache
* online users information.
*
* @param jid
* a user's JID for whom we query information.
*
* @return true if the user is known as online to the installation, false if
* the method does not know.
*/
@Override
public boolean containsJid(BareJID jid) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Called for jid: {0}", jid);
}
return super.containsJid(jid) || strategy.containsJid(jid);
}
/**
* Method description
*
*
* @param packet
*
*
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean fastAddOutPacket(Packet packet) {
return super.fastAddOutPacket(packet);
}
/**
* Method description
*
*
* @param packet
* @param conn
*/
@Override
public void handleLocalPacket(Packet packet, XMPPResourceConnection conn) {
if (strategy != null) {
strategy.handleLocalPacket(packet, conn);
}
}
/**
* Method description
*
*
* @param userId
* @param conn
*/
@Override
public void handleLogin(BareJID userId, XMPPResourceConnection conn) {
super.handleLogin(userId, conn);
strategy.handleLocalUserLogin(userId, conn);
}
/**
* Method description
*
*
* @param binds
*/
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put(CLUSTER_STRATEGY_VAR, strategy);
}
/**
* The method is called on cluster node connection event. This is a
* notification to the component that a new node has connected to the system.
*
* @param node
* is a hostname of a new cluster node connected to the system.
*/
@Override
public void nodeConnected(String node) {
log.log(Level.FINE, "Nodes connected: {0}", node);
JID jid = JID.jidInstanceNS(getName(), node, null);
strategy.nodeConnected(jid);
sendAdminNotification("Cluster node '" + node + "' connected (" + (new Date()) + ")",
"New cluster node connected: " + node, node);
}
/**
* Method is called on cluster node disconnection event. This is a
* notification to the component that there was network connection lost to one
* of the cluster nodes.
*
* @param node
* is a hostname of a cluster node generating the event.
*/
@Override
public void nodeDisconnected(String node) {
log.log(Level.FINE, "Nodes disconnected: {0}", node);
JID jid = JID.jidInstanceNS(getName(), node, null);
strategy.nodeDisconnected(jid);
// Not sure what to do here, there might be still packets
// from the cluster node waiting....
// delTrusted(jid);
sendAdminNotification("Cluster node '" + node + "' disconnected (" + (new Date()) +
")", "Cluster node disconnected: " + node, node);
}
/**
* Concurrency control method. Returns preferable number of threads set for
* this component.
*
*
* @return preferable number of threads set for this component.
*/
@Override
public int processingInThreads() {
return Math.max(nodesNo, super.processingInThreads());
}
/**
* Concurrency control method. Returns preferable number of threads set for
* this component.
*
*
* @return preferable number of threads set for this component.
*/
@Override
public int processingOutThreads() {
return Math.max(nodesNo, super.processingOutThreads());
}
/**
* This is a standard component method for processing packets. The method
* takes care of cases where the packet cannot be processed locally, in such a
* case it is forwarded to another node.
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Received packet: {0}", packet);
}
// long startTime = System.currentTimeMillis();
// int idx = tIdx;
// tIdx = (tIdx + 1) % maxIdx;
// long cmdTm = 0;
// long clTm = 0;
// long chTm = 0;
// long smTm = 0;
if (packet.isCommand() && processCommand(packet)) {
packet.processedBy("SessionManager");
// cmdTm = System.currentTimeMillis() - startTime;
} else {
XMPPResourceConnection conn = getXMPPResourceConnection(packet);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Ressource connection found: {0}", conn);
}
boolean clusterOK = strategy.processPacket(packet, conn);
// clTm = System.currentTimeMillis() - startTime;
if (conn == null) {
if (isBrokenPacket(packet) || processAdminsOrDomains(packet)) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Ignoring/dropping packet: {0}", packet);
}
} else {
// Process is as packet to offline user only if there are no other
// nodes for the packet to be processed.
if (!clusterOK) {
// Process packet for offline user
processPacket(packet, (XMPPResourceConnection) null);
}
}
} else {
processPacket(packet, conn);
// smTm = System.currentTimeMillis() - startTime;
}
}
// commandTime[idx] = cmdTm;
// clusterTime[idx] = clTm;
// checkingTime[idx] = chTm;
// smTime[idx] = smTm;
}
/**
* Method description
*
*
* @param packet
* @param conn
*/
@Override
public void processPacket(Packet packet, XMPPResourceConnection conn) {
super.processPacket(packet, conn);
}
/**
* Allows to obtain various informations about components
*
* @return information about particular component
*/
@Override
public ComponentInfo getComponentInfo() {
cmpInfo = super.getComponentInfo();
cmpInfo.getComponentData().put("ClusteringStrategy", (strategy != null)
? strategy.getClass()
: null);
return cmpInfo;
}
/**
* If the installation knows about user's JID, that he is connected to the
* system, then this method returns all user's connection IDs. As an
* optimization we can forward packets to all user's connections directly from
* a single node.
*
* @param jid
* a user's JID for whom we query information.
*
* @return a list of all user's connection IDs.
*/
@Override
public JID[] getConnectionIdsForJid(BareJID jid) {
JID[] ids = super.getConnectionIdsForJid(jid);
if (ids == null) {
ids = strategy.getConnectionIdsForJid(jid);
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Called for jid: {0}, results: {1}", new Object[] { jid,
Arrays.toString(ids) });
}
return ids;
}
/**
* Loads the component's default configuration to the configuration management
* subsystem.
*
* @param params
* is a Map with system-wide default settings found in
* init.properties file or similar location.
*
* @return a Map with all default component settings generated from the
* default parameters in init.properties file.
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
String strategy_class = (String) params.get(STRATEGY_CLASS_PROPERTY);
if (strategy_class == null) {
strategy_class = STRATEGY_CLASS_PROP_VAL;
}
props.put(STRATEGY_CLASS_PROP_KEY, strategy_class);
try {
ClusteringStrategyIfc strat_tmp = (ClusteringStrategyIfc) Class.forName(
strategy_class).newInstance();
Map<String, Object> strat_defs = strat_tmp.getDefaults(params);
if (strat_defs != null) {
props.putAll(strat_defs);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Can not instantiate clustering strategy for class: " +
strategy_class, e);
}
String[] local_domains = DNSResolver.getDefHostNames();
if (params.get(GEN_VIRT_HOSTS) != null) {
local_domains = ((String) params.get(GEN_VIRT_HOSTS)).split(",");
}
// defs.put(LOCAL_DOMAINS_PROP_KEY, LOCAL_DOMAINS_PROP_VAL);
props.put(MY_DOMAIN_NAME_PROP_KEY, local_domains[0]);
if (params.get(CLUSTER_NODES) != null) {
String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(",");
nodesNo = cl_nodes.length;
}
return props;
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoDescription() {
return super.getDiscoDescription() + " clustered" + strategy.getInfo();
}
// private long calcAverage(long[] timings) {
// long res = 0;
// for (long ppt : timings) {
// res += ppt;
// long processingTime = res / timings.length;
// return processingTime;
/**
* Method generates and returns component's statistics.
*
* @param list
* is a collection with statistics to which this component can add
* own metrics.
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
strategy.getStatistics(list);
// list.add(getName(), "Average commandTime on last " + commandTime.length
// + " runs [ms]", calcAverage(commandTime), Level.FINE);
// list.add(getName(), "Average clusterTime on last " + clusterTime.length
// + " runs [ms]", calcAverage(clusterTime), Level.FINE);
// list.add(getName(), "Average checkingTime on last " + checkingTime.length
// + " runs [ms]", calcAverage(checkingTime), Level.FINE);
// list.add(getName(), "Average smTime on last " + smTime.length +
// " runs [ms]",
// calcAverage(smTime), Level.FINE);
}
/**
* Returns active clustering strategy object.
*
* @return active clustering strategy object.
*/
public ClusteringStrategyIfc getStrategy() {
return strategy;
}
/**
* Method description
*
*
*
* @param p
*
*
*
* @return a value of <code>XMPPResourceConnection</code>
*/
@Override
public XMPPResourceConnection getXMPPResourceConnection(Packet p) {
return super.getXMPPResourceConnection(p);
}
/**
* Method description
*
*
*
*
* @return a value of <code>ConcurrentHashMap<JID,XMPPResourceConnection></code>
*/
@Override
public ConcurrentHashMap<JID, XMPPResourceConnection> getXMPPResourceConnections() {
return connectionsByFrom;
}
/**
* Method description
*
*
*
*
* @return a value of <code>ConcurrentHashMap<BareJID,XMPPSession></code>
*/
@Override
public ConcurrentHashMap<BareJID, XMPPSession> getXMPPSessions() {
return sessionsByNodeId;
}
/**
* Method checks whether the clustering strategy has a complete JIDs info.
* That is whether the strategy knows about all users connected to all nodes.
* Some strategies may choose not to share this information among nodes, hence
* the methods returns false. Other may synchronize this information and can
* provide it to further optimize cluster traffic.
*
*
* @return a true boolean value if the strategy has a complete information
* about all users connected to all cluster nodes.
*/
@Override
public boolean hasCompleteJidsInfo() {
return strategy.hasCompleteJidsInfo();
}
/**
* Set's the configures the cluster controller object for cluster
* communication and API.
*
* @param cl_controller
*/
@Override
public void setClusterController(ClusterControllerIfc cl_controller) {
clusterController = cl_controller;
if (strategy != null) {
strategy.setClusterController(clusterController);
}
// clusterController.removeCommandListener(USER_CONNECTED_CMD, userConnected);
// clusterController.removeCommandListener(USER_DISCONNECTED_CMD, userDisconnected);
// clusterController.removeCommandListener(USER_PRESENCE_CMD, userPresence);
// clusterController.removeCommandListener(REQUEST_SYNCONLINE_CMD, requestSyncOnline);
// clusterController.removeCommandListener(RESPOND_SYNCONLINE_CMD, respondSyncOnline);
// clusterController.setCommandListener(USER_CONNECTED_CMD, userConnected);
// clusterController.setCommandListener(USER_DISCONNECTED_CMD, userDisconnected);
// clusterController.setCommandListener(USER_PRESENCE_CMD, userPresence);
// clusterController.setCommandListener(REQUEST_SYNCONLINE_CMD, requestSyncOnline);
// clusterController.setCommandListener(RESPOND_SYNCONLINE_CMD, respondSyncOnline);
}
/**
* Standard component's configuration method.
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
if (props.get(STRATEGY_CLASS_PROP_KEY) != null) {
String strategy_class = (String) props.get(STRATEGY_CLASS_PROP_KEY);
try {
ClusteringStrategyIfc strategy_tmp = (ClusteringStrategyIfc) Class.forName(
strategy_class).newInstance();
strategy_tmp.setSessionManagerHandler(this);
strategy_tmp.setProperties(props);
// strategy_tmp.init(getName());
strategy = strategy_tmp;
strategy.setSessionManagerHandler(this);
log.log(Level.CONFIG, "Loaded SM strategy: " + strategy_class);
// strategy.nodeConnected(getComponentId());
addTrusted(getComponentId());
if (clusterController != null) {
strategy.setClusterController(clusterController);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Can not clustering strategy instance for class: " +
strategy_class, e);
}
}
try {
if (props.get(MY_DOMAIN_NAME_PROP_KEY) != null) {
my_hostname = JID.jidInstance((String) props.get(MY_DOMAIN_NAME_PROP_KEY));
my_address = JID.jidInstance(getName(), (String) props.get(
MY_DOMAIN_NAME_PROP_KEY), null);
}
} catch (TigaseStringprepException ex) {
log.log(Level.WARNING,
"Creating component source address failed stringprep processing: {0}@{1}",
new Object[] { getName(),
my_hostname });
}
}
/**
* The method intercept user's disconnect event. On user disconnect the method
* takes a list of cluster nodes from the strategy and sends a notification to
* all those nodes about the event.
*
* @see SessionManager#closeSession
*
* @param conn
* @param closeOnly
*/
@Override
protected void closeSession(XMPPResourceConnection conn, boolean closeOnly) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Called for conn: {0}, closeOnly: {1}", new Object[] { conn,
closeOnly });
}
// Exception here should not normally happen, but if it does, then
// consequences might be severe, let's catch it then
try {
if (conn.isAuthorized() && conn.isResourceSet()) {
BareJID userId = conn.getBareJID();
strategy.handleLocalUserLogout(userId, conn);
}
} catch (Exception ex) {
log.log(Level.WARNING, "This should not happen, check it out!, ", ex);
}
// Exception here should not normally happen, but if it does, then
// consequences might be severe, let's catch it then
try {
super.closeSession(conn, closeOnly);
} catch (Exception ex) {
log.log(Level.WARNING, "This should not happen, check it out!, ", ex);
}
}
private void sendAdminNotification(String msg, String subject, String node) {
String message = msg;
if (node != null) {
message = msg + "\n";
}
int cnt = 0;
message += node + " connected to " + getDefHostName();
Packet p_msg = Message.getMessage(my_address, my_hostname, StanzaType.normal,
message, subject, "xyz", newPacketId(null));
sendToAdmins(p_msg);
}
}
//~ Formatted in Tigase Code Convention on 13/10/15 |
package com.helpmobile.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.helpmobile.rest.WorkshopBooking;
import com.helpmobile.rest.RestAccess;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author terra
*/
public class CreateWorkshopBookingTest {
public CreateWorkshopBookingTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void test1() throws IOException {
ObjectMapper mapper = new ObjectMapper();
RestAccess restAccess = new RestAccess();
boolean isBooked = restAccess.createWorkshopBooking(new WorkshopBooking(1409,"10795119"));
assert(isBooked);
}
} |
package de.lmu.ifi.dbs.elki.math;
/**
* Do some simple statistics (mean, average).
*
* This class can repeatedly be fed with data using the add() methods,
* The resulting values for mean and average can be queried at any time using
* getMean() and getVariance().
*
* Trivial code, but replicated a lot. The class is final so it should come at low cost.
*
* @author Erich Schubert
*
*/
public final class MeanVariance {
/**
* Sum of values
*/
public double sum = 0.0;
/**
* Sum of Squares
*/
public double sqrSum = 0.0;
/**
* Number of Samples.
*/
public double count = 0.0;
/**
* Empty constructor
*/
public MeanVariance() {
// nothing to do here, initialization done above.
}
/**
* Constructor from full internal data.
*
* @param sum sum
* @param sqrSum sum of squared values
* @param count sum of weights
*/
public MeanVariance(double sum, double sqrSum, double count) {
this.sum = sum;
this.sqrSum = sqrSum;
this.count = count;
}
/**
* Constructor from other instance
*
* @param other other instance to copy data from.
*/
public MeanVariance(MeanVariance other) {
this.sum = other.sum;
this.sqrSum = other.sqrSum;
this.count = other.count;
}
/**
* Add data with a given weight
*
* @param val data
* @param weight weight
*/
public void addData(double val, double weight) {
sum += weight * val;
sqrSum += weight * val * val;
count += weight;
}
/**
* Add a single value with weight 1.0
*
* @param val Value
*/
public void addData(double val) {
addData(val, 1.0);
}
/**
* Join the data of another MeanVariance instance.
*
* @param other
*/
public void addData(MeanVariance other) {
this.sum += other.sum;
this.sqrSum += other.sqrSum;
this.count += other.count;
}
/**
* Get the number of points the average is based on.
* @return number of data points
*/
public double getCount() {
return count;
}
/**
* Return mean
* @return mean
*/
public double getMean() {
return sum / count;
}
/**
* Return variance
* @return variance
*/
public double getVariance() {
double mu = sum / count;
return (sqrSum / count) - (mu * mu);
}
/**
* Return standard deviation
* @return stddev
*/
public double getStddev() {
return Math.sqrt(getVariance());
}
} |
package uk.co.jemos.podam.api;
import net.jcip.annotations.Immutable;
import net.jcip.annotations.NotThreadSafe;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.jemos.podam.api.DataProviderStrategy.Order;
import uk.co.jemos.podam.common.AttributeStrategy;
import uk.co.jemos.podam.common.ManufacturingContext;
import uk.co.jemos.podam.common.PodamConstants;
import uk.co.jemos.podam.common.PodamConstructor;
import uk.co.jemos.podam.exceptions.PodamMockeryException;
import uk.co.jemos.podam.typeManufacturers.TypeManufacturerUtil;
import javax.xml.ws.Holder;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
/**
* The PODAM factory implementation
*
* @author mtedone
*
* @since 1.0.0
*
*/
@NotThreadSafe
@Immutable
public class PodamFactoryImpl implements PodamFactory {
private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection";
private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object";
/** Application logger */
private static final Logger LOG = LoggerFactory.getLogger(PodamFactoryImpl.class);
/** Empty type map */
private static final Map<String, Type> NULL_TYPE_ARGS_MAP = new HashMap<String, Type>();
/**
* External factory to delegate production this factory cannot handle
* <p>
* The default is {@link NullExternalFactory}.
* </p>
*/
private PodamFactory externalFactory
= NullExternalFactory.getInstance();
/**
* The strategy to use to fill data.
* <p>
* The default is {@link RandomDataProviderStrategyImpl}.
* </p>
*/
private DataProviderStrategy strategy
= new RandomDataProviderStrategyImpl();
/**
* The strategy to use to introspect data.
* <p>
* The default is {@link DefaultClassInfoStrategy}.
* </p>
*/
private ClassInfoStrategy classInfoStrategy
= DefaultClassInfoStrategy.getInstance();
/**
* Default constructor.
*/
public PodamFactoryImpl() {
this(NullExternalFactory.getInstance(),
new RandomDataProviderStrategyImpl());
}
/**
* Constructor with non-default strategy
*
* @param strategy
* The strategy to use to fill data
*/
public PodamFactoryImpl(DataProviderStrategy strategy) {
this(NullExternalFactory.getInstance(), strategy);
}
/**
* Constructor with non-default external factory
*
* @param externalFactory
* External factory to delegate production this factory cannot
* handle
*/
public PodamFactoryImpl(PodamFactory externalFactory) {
this(externalFactory, new RandomDataProviderStrategyImpl());
}
/**
* Full constructor.
*
* @param externalFactory
* External factory to delegate production this factory cannot
* handle
* @param strategy
* The strategy to use to fill data
*/
public PodamFactoryImpl(PodamFactory externalFactory,
DataProviderStrategy strategy) {
this.externalFactory = externalFactory;
this.strategy = strategy;
}
/**
* {@inheritDoc}
*/
@Override
public <T> T manufacturePojoWithFullData(Class<T> pojoClass, Type... genericTypeArgs) {
ManufacturingContext manufacturingCtx = new ManufacturingContext();
manufacturingCtx.getPojos().put(pojoClass, 0);
manufacturingCtx.setConstructorOrdering(Order.HEAVY_FIRST);
return doManufacturePojo(pojoClass, manufacturingCtx, genericTypeArgs);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) {
ManufacturingContext manufacturingCtx = new ManufacturingContext();
manufacturingCtx.getPojos().put(pojoClass, 0);
return doManufacturePojo(pojoClass, manufacturingCtx, genericTypeArgs);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T populatePojo(T pojo, Type... genericTypeArgs) {
ManufacturingContext manufacturingCtx = new ManufacturingContext();
manufacturingCtx.getPojos().put(pojo.getClass(), 0);
final Map<String, Type> typeArgsMap = new HashMap<String, Type>();
Type[] genericTypeArgsExtra = TypeManufacturerUtil.fillTypeArgMap(typeArgsMap,
pojo.getClass(), genericTypeArgs);
try {
return this.populatePojoInternal(pojo, manufacturingCtx, typeArgsMap,
genericTypeArgsExtra);
} catch (InstantiationException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new PodamMockeryException(e.getMessage(), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public DataProviderStrategy getStrategy() {
return strategy;
}
/**
* {@inheritDoc}
*/
@Override
public PodamFactory setStrategy(DataProviderStrategy strategy) {
this.strategy = strategy;
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ClassInfoStrategy getClassStrategy() {
return classInfoStrategy;
}
/**
* {@inheritDoc}
*/
@Override
public PodamFactory setClassStrategy(ClassInfoStrategy classInfoStrategy) {
this.classInfoStrategy = classInfoStrategy;
return this;
}
/**
* {@inheritDoc}
*/
@Override
public PodamFactory getExternalFactory() {
return externalFactory;
}
/**
* {@inheritDoc}
*/
@Override
public PodamFactory setExternalFactory(PodamFactory externalFactory) {
this.externalFactory = externalFactory;
return this;
}
private <T> T instantiatePojoWithFactory(
Class<?> factoryClass, Class<T> pojoClass,
ManufacturingContext manufacturingCtx,
Map<String, Type> typeArgsMap, Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
// If no publicly accessible constructors are available,
// the best we can do is to find a constructor (e.g.
// getInstance())
Method[] declaredMethods = factoryClass.getDeclaredMethods();
strategy.sort(declaredMethods, manufacturingCtx.getConstructorOrdering());
// A candidate factory method is a method which returns the
// Class type
// The parameters to pass to the method invocation
Object[] parameterValues = null;
for (Method candidateConstructor : declaredMethods) {
if (!candidateConstructor.getReturnType().equals(pojoClass)) {
continue;
}
Object factoryInstance = null;
if (!Modifier.isStatic(candidateConstructor.getModifiers())) {
if (factoryClass.equals(pojoClass)) {
continue;
} else {
factoryInstance = manufacturePojo(factoryClass);
}
}
parameterValues = getParameterValuesForMethod(candidateConstructor,
pojoClass, manufacturingCtx, typeArgsMap, genericTypeArgs);
try {
@SuppressWarnings("unchecked")
T retValue = (T) candidateConstructor.invoke(factoryInstance,
parameterValues);
LOG.debug("Could create an instance using "
+ candidateConstructor);
if (retValue != null) {
return retValue;
}
} catch (Exception t) {
LOG.debug(
"PODAM could not create an instance for constructor: "
+ candidateConstructor
+ ". Will try another one...", t);
}
}
LOG.debug("For class {} PODAM could not possibly create"
+ " a value statically. Will try other means.",
pojoClass);
return null;
}
/**
* It creates and returns an instance of the given class if at least one of
* its constructors has been annotated with {@link PodamConstructor}
*
* @param <T>
* The type of the instance to return
*
* @param pojoClass
* The class of which an instance is required
* @param manufacturingCtx
* the manufacturing context
* @param typeArgsMap
* a map relating the generic class arguments ("<T, V>" for
* example) with their actual types
* @param genericTypeArgs
* The generic type arguments for the current generic class
* instance
* @return an instance of the given class if at least one of its
* constructors has been annotated with {@link PodamConstructor}
* @throws SecurityException
* If an security was violated
*/
private <T> T instantiatePojo(Class<T> pojoClass,
ManufacturingContext manufacturingCtx, Map<String, Type> typeArgsMap,
Type... genericTypeArgs)
throws SecurityException {
T retValue = null;
Constructor<?>[] constructors = pojoClass.getConstructors();
if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) {
/* No public constructors, we will try static factory methods */
try {
retValue = instantiatePojoWithFactory(
pojoClass, pojoClass, manufacturingCtx, typeArgsMap, genericTypeArgs);
} catch (Exception e) {
LOG.debug("We couldn't create an instance for pojo: "
+ pojoClass + " with factory methods, will "
+ " try non-public constructors.", e);
}
/* Then non-public constructors */
if (retValue == null) {
constructors = pojoClass.getDeclaredConstructors();
}
}
if (retValue == null && constructors.length > 0) {
strategy.sort(constructors, manufacturingCtx.getConstructorOrdering());
for (Constructor<?> constructor : constructors) {
try {
Object[] parameterValues = getParameterValuesForConstructor(
constructor, pojoClass, manufacturingCtx, typeArgsMap,
genericTypeArgs);
// Security hack
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
@SuppressWarnings("unchecked")
T tmp = (T) constructor.newInstance(parameterValues);
retValue = tmp;
if (retValue != null) {
LOG.debug("We could create an instance with constructor: "
+ constructor);
break;
}
} catch (Exception e) {
LOG.debug("We couldn't create an instance for pojo: {} with"
+ " constructor: {}. Will try with another one.",
pojoClass, constructor, e);
}
}
}
if (retValue == null) {
LOG.debug("For class {} PODAM could not possibly create"
+ " a value. Will try other means.", pojoClass);
}
return retValue;
}
/**
* Manufactures and populates the pojo class
*
* @param <T> The type of the instance to return
* @param pojoClass the class to instantiate
* @param manufacturingCtx the initialized manufacturing context
* @param genericTypeArgs generic arguments for the pojo class
* @return instance of @pojoClass or null in case it cannot be instantiated
*/
private <T> T doManufacturePojo(Class<T> pojoClass,
ManufacturingContext manufacturingCtx, Type... genericTypeArgs) {
try {
Class<?> declaringClass = null;
Object declaringInstance = null;
AttributeMetadata pojoMetadata = new AttributeMetadata(pojoClass,
pojoClass, genericTypeArgs, declaringClass, declaringInstance);
return this.manufacturePojoInternal(pojoClass, pojoMetadata,
manufacturingCtx, genericTypeArgs);
} catch (InstantiationException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new PodamMockeryException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new PodamMockeryException(e.getMessage(), e);
}
}
private <T> T manufacturePojoInternal(Class<T> pojoClass,
AttributeMetadata pojoMetadata, ManufacturingContext manufacturingCtx,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
// reuse object from memoization table
@SuppressWarnings("unchecked")
T objectToReuse = (T) strategy.getMemoizedObject(pojoMetadata);
if (objectToReuse != null) {
LOG.debug("Fetched memoized object for {} with parameters {}",
pojoClass, Arrays.toString(genericTypeArgs));
return objectToReuse;
} else {
LOG.debug("Manufacturing {} with parameters {}",
pojoClass, Arrays.toString(genericTypeArgs));
}
final Map<String, Type> typeArgsMap = new HashMap<String, Type>();
Type[] genericTypeArgsExtra = TypeManufacturerUtil.fillTypeArgMap(typeArgsMap,
pojoClass, genericTypeArgs);
T retValue = (T) strategy.getTypeValue(pojoMetadata, typeArgsMap, pojoClass);
if (null == retValue) {
if (pojoClass.isInterface()) {
return getValueForAbstractType(pojoClass, pojoMetadata,
manufacturingCtx, typeArgsMap, genericTypeArgs);
}
try {
retValue = instantiatePojo(pojoClass, manufacturingCtx, typeArgsMap,
genericTypeArgsExtra);
} catch (SecurityException e) {
throw new PodamMockeryException(
"Security exception while applying introspection.", e);
}
}
if (retValue == null) {
return getValueForAbstractType(pojoClass, pojoMetadata,
manufacturingCtx, typeArgsMap, genericTypeArgs);
} else {
// update memoization cache with new object
// the reference is stored before properties are set so that recursive
// properties can use it
strategy.cacheMemoizedObject(pojoMetadata, retValue);
populatePojoInternal(retValue, manufacturingCtx, typeArgsMap, genericTypeArgsExtra);
}
return retValue;
}
private <T> T populatePojoInternal(T pojo, ManufacturingContext manufacturingCtx,
Map<String, Type> typeArgsMap,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Class<?> pojoClass = pojo.getClass();
if (pojo instanceof Collection && ((Collection<?>)pojo).isEmpty()) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) pojo;
AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
Class<?> elementTypeClass = findInheretedCollectionElementType(collection,
manufacturingCtx, elementGenericTypeArgs, typeArgsMap, genericTypeArgs);
String attributeName = null;
Annotation[] annotations = collection.getClass().getAnnotations();
fillCollection(manufacturingCtx, Arrays.asList(annotations), attributeName,
collection, elementTypeClass, elementGenericTypeArgs.get());
} else if (pojo instanceof Map && ((Map<?,?>)pojo).isEmpty()) {
@SuppressWarnings("unchecked")
Map<Object,Object> map = (Map<Object,Object>)pojo;
MapArguments mapArguments = findInheretedMapElementType(
map, manufacturingCtx, typeArgsMap, genericTypeArgs);
fillMap(mapArguments, manufacturingCtx);
}
Class<?>[] parameterTypes = null;
Class<?> attributeType = null;
ClassInfo classInfo = classInfoStrategy.getClassInfo(pojo.getClass());
Set<ClassAttribute> classAttributes = classInfo.getClassAttributes();
// According to JavaBeans standards, setters should have only
// one argument
Object setterArg = null;
Iterator<ClassAttribute> iter = classAttributes.iterator();
while (iter.hasNext()) {
ClassAttribute attribute = iter.next();
Set<Method> setters = attribute.getSetters();
if (setters.isEmpty()) {
if (attribute.getGetters().isEmpty()) {
iter.remove();
}
continue;
} else {
iter.remove();
}
/* We want to find setter defined the latest */
Method setter = null;
for (Method current : setters) {
if (setter == null || setter.getDeclaringClass().isAssignableFrom(current.getDeclaringClass())) {
setter = current;
}
}
parameterTypes = setter.getParameterTypes();
if (parameterTypes.length != 1) {
LOG.warn("Skipping setter with non-single arguments {}",
setter);
continue;
}
// A class which has got an attribute to itself (e.g.
// recursive hierarchies)
attributeType = parameterTypes[0];
// If an attribute has been annotated with
// PodamAttributeStrategy, it takes the precedence over any
// other strategy. Additionally we don't pass the attribute
// metadata for value customisation; if user went to the extent
// of specifying a PodamAttributeStrategy annotation for an
// attribute they are already customising the value assigned to
// that attribute.
List<Annotation> pojoAttributeAnnotations
= PodamUtils.getAttributeAnnotations(
attribute.getAttribute(), setter);
AttributeStrategy<?> attributeStrategy
= TypeManufacturerUtil.findAttributeStrategy(strategy, pojoAttributeAnnotations, attributeType);
if (null != attributeStrategy) {
LOG.debug("The attribute: " + attribute.getName()
+ " will be filled using the following strategy: "
+ attributeStrategy);
setterArg = TypeManufacturerUtil.returnAttributeDataStrategyValue(attributeType,
attributeStrategy);
} else {
AtomicReference<Type[]> typeGenericTypeArgs
= new AtomicReference<Type[]>(PodamConstants.NO_TYPES);
// If the parameter is a generic parameterized type resolve
// the actual type arguments
Type genericType = setter.getGenericParameterTypes()[0];
final Type[] typeArguments;
if (!(genericType instanceof GenericArrayType)) {
attributeType = TypeManufacturerUtil.resolveGenericParameter(genericType,
typeArgsMap, typeGenericTypeArgs);
typeArguments = typeGenericTypeArgs.get();
} else {
typeArguments = PodamConstants.NO_TYPES;
}
for (int i = 0; i < typeArguments.length; i++) {
if (typeArguments[i] instanceof TypeVariable) {
Class<?> resolvedType = TypeManufacturerUtil.resolveGenericParameter(typeArguments[i],
typeArgsMap, typeGenericTypeArgs);
if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) {
typeArguments[i] = resolvedType;
}
}
}
setterArg = manufactureAttributeValue(pojo, manufacturingCtx,
attributeType, genericType,
pojoAttributeAnnotations, attribute.getName(),
typeArgsMap, typeArguments);
}
try {
setter.invoke(pojo, setterArg);
} catch(IllegalAccessException e) {
LOG.warn("{} is not accessible. Setting it to accessible."
+ " However this is a security hack and your code"
+ " should really adhere to JavaBeans standards.",
setter.toString());
setter.setAccessible(true);
setter.invoke(pojo, setterArg);
}
}
for (ClassAttribute readOnlyAttribute : classAttributes) {
Method getter = readOnlyAttribute.getGetters().iterator().next();
if (getter != null && !getter.getReturnType().isPrimitive()) {
if (getter.getGenericParameterTypes().length == 0) {
Object fieldValue = null;
try {
fieldValue = getter.invoke(pojo, PodamConstants.NO_ARGS);
} catch(Exception e) {
LOG.debug("Cannot access {}, skipping", getter);
}
if (fieldValue != null) {
LOG.debug("Populating read-only field {}", getter);
Type[] genericTypeArgsAll;
Map<String, Type> paramTypeArgsMap;
if (getter.getGenericReturnType() instanceof ParameterizedType) {
paramTypeArgsMap = new HashMap<String, Type>(typeArgsMap);
ParameterizedType paramType
= (ParameterizedType) getter.getGenericReturnType();
Type[] actualTypes = paramType.getActualTypeArguments();
TypeManufacturerUtil.fillTypeArgMap(paramTypeArgsMap,
getter.getReturnType(), actualTypes);
genericTypeArgsAll = TypeManufacturerUtil.fillTypeArgMap(paramTypeArgsMap,
getter.getReturnType(), genericTypeArgs);
} else {
paramTypeArgsMap = typeArgsMap;
genericTypeArgsAll = genericTypeArgs;
}
Class<?> fieldClass = fieldValue.getClass();
Integer depth = manufacturingCtx.getPojos().get(fieldClass);
if (depth == null) {
depth = -1;
}
if (depth <= strategy.getMaxDepth(fieldClass)) {
manufacturingCtx.getPojos().put(fieldClass, depth + 1);
populatePojoInternal(fieldValue, manufacturingCtx, paramTypeArgsMap, genericTypeArgsAll);
manufacturingCtx.getPojos().put(fieldClass, depth);
} else {
LOG.warn("Loop in filling read-only field {} detected.",
getter);
}
}
} else {
LOG.warn("Skipping invalid getter {}", getter);
}
}
}
// It executes any extra methods
Collection<Method> extraMethods = classInfoStrategy.getExtraMethods(pojoClass);
if (null != extraMethods) {
for (Method extraMethod : extraMethods) {
Object[] args = getParameterValuesForMethod(extraMethod, pojoClass,
manufacturingCtx, typeArgsMap, genericTypeArgs);
extraMethod.invoke(pojo, args);
}
}
return pojo;
}
private Object manufactureAttributeValue(Object pojo,
ManufacturingContext manufacturingCtx, Class<?> attributeType,
Type genericAttributeType, List<Annotation> annotations,
String attributeName, Map<String, Type> typeArgsMap,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Object attributeValue = null;
Class<?> pojoClass = (pojo instanceof Class ? (Class<?>) pojo : pojo.getClass());
Class<?> realAttributeType;
if (attributeType != genericAttributeType
&& Object.class.equals(attributeType)
&& genericAttributeType instanceof TypeVariable) {
AtomicReference<Type[]> elementGenericTypeArgs
= new AtomicReference<Type[]>(PodamConstants.NO_TYPES);
realAttributeType = TypeManufacturerUtil.resolveGenericParameter(genericAttributeType,
typeArgsMap, elementGenericTypeArgs);
} else {
realAttributeType = attributeType;
}
Type[] genericTypeArgsAll = TypeManufacturerUtil.mergeActualAndSuppliedGenericTypes(
attributeType, genericAttributeType, genericTypeArgs, typeArgsMap);
AttributeMetadata attributeMetadata = new AttributeMetadata(
attributeName, realAttributeType, genericAttributeType,
genericTypeArgsAll, annotations, pojoClass, pojo);
if (realAttributeType.isArray()) {
// Array type
attributeValue = resolveArrayElementValue(pojo, manufacturingCtx,
attributeMetadata, typeArgsMap);
// Collection
} else if (Collection.class.isAssignableFrom(realAttributeType)) {
attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute(
pojo, manufacturingCtx, attributeMetadata, typeArgsMap);
// Map
} else if (Map.class.isAssignableFrom(realAttributeType)) {
attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo,
manufacturingCtx, attributeMetadata, typeArgsMap);
}
// For any other type, we use the PODAM strategy
if (attributeValue == null) {
Integer depth = manufacturingCtx.getPojos().get(realAttributeType);
if (depth == null) {
depth = -1;
}
if (depth <= strategy.getMaxDepth(pojoClass)) {
manufacturingCtx.getPojos().put(realAttributeType, depth + 1);
attributeValue = this.manufacturePojoInternal(
realAttributeType, attributeMetadata, manufacturingCtx, genericTypeArgsAll);
manufacturingCtx.getPojos().put(realAttributeType, depth);
} else {
attributeValue = resortToExternalFactory(manufacturingCtx,
"Loop in {} production detected. Resorting to {} external factory",
realAttributeType, genericTypeArgsAll);
}
}
return attributeValue;
}
/**
* Delegates POJO manufacturing to an external factory
*
* @param <T>
* The type of the instance to return
* @param manufacturingCtx
* the manufacturing context
* @param msg
* Message to log, must contain two parameters
* @param pojoClass
* The class of which an instance is required
* @param genericTypeArgs
* The generic type arguments for the current generic class
* instance
* @return instance of POJO produced by external factory or null
*/
private <T> T resortToExternalFactory(ManufacturingContext manufacturingCtx,
String msg, Class<T> pojoClass,
Type... genericTypeArgs) {
LOG.warn(msg, pojoClass, externalFactory.getClass().getName());
if (manufacturingCtx.getConstructorOrdering() == Order.HEAVY_FIRST) {
return externalFactory.manufacturePojoWithFullData(pojoClass, genericTypeArgs);
} else {
return externalFactory.manufacturePojo(pojoClass, genericTypeArgs);
}
}
private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute(
Object pojo, ManufacturingContext manufacturingCtx,
AttributeMetadata attributeMetadata, Map<String, Type> typeArgsMap) {
String attributeName = attributeMetadata.getAttributeName();
// This needs to be generic because collections can be of any type
Collection<Object> defaultValue = null;
if (null != pojo && !Character.isDigit(attributeName.charAt(0))) {
defaultValue = PodamUtils.getFieldValue(pojo, attributeName);
}
Collection<Object> retValue = null;
if (null != defaultValue &&
(defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) {
/* Default collection, which is not immutable */
retValue = defaultValue;
} else {
@SuppressWarnings("unchecked")
Class<Collection<Object>> collectionType
= (Class<Collection<Object>>) attributeMetadata.getAttributeType();
retValue = strategy.getTypeValue(attributeMetadata, typeArgsMap, collectionType);
if (null != retValue && null != defaultValue) {
retValue.addAll(defaultValue);
}
}
if (null == retValue) {
return null;
}
try {
Class<?> typeClass = null;
AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
if (ArrayUtils.isEmpty(attributeMetadata.getAttrGenericArgs())) {
typeClass = findInheretedCollectionElementType(retValue,
manufacturingCtx, elementGenericTypeArgs, typeArgsMap, attributeMetadata.getAttrGenericArgs());
} else {
Type actualTypeArgument = attributeMetadata.getAttrGenericArgs()[0];
typeClass = TypeManufacturerUtil.resolveGenericParameter(actualTypeArgument,
typeArgsMap, elementGenericTypeArgs);
}
fillCollection(manufacturingCtx,
attributeMetadata.getAttributeAnnotations(), attributeName,
retValue, typeClass, elementGenericTypeArgs.get());
} catch (SecurityException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
} catch (IllegalArgumentException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
} catch (InstantiationException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
} catch (IllegalAccessException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
} catch (ClassNotFoundException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
} catch (InvocationTargetException e) {
throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR,
e);
}
return retValue;
}
/**
* Tries to find collection element type from collection object
*
* @param collection
* The collection to be filled
* @param manufacturingCtx
* the manufacturing context
* @param elementGenericTypeArgs
* parameter to return generic arguments of collection element
* @param typeArgsMap
* a map relating the generic class arguments ("<T, V>" for
* example) with their actual types
* @param genericTypeArgs
* The generic type arguments for the current generic class
* instance
* @return
* class type of collection element
*/
private Class<?> findInheretedCollectionElementType(
Collection<Object> collection, ManufacturingContext manufacturingCtx,
AtomicReference<Type[]> elementGenericTypeArgs,
Map<String, Type> typeArgsMap, Type... genericTypeArgs) {
Class<?> pojoClass = collection.getClass();
Class<?> collectionClass = pojoClass;
Type[] typeParams = collectionClass.getTypeParameters();
main : while (typeParams.length < 1) {
for (Type genericIface : collectionClass.getGenericInterfaces()) {
Class<?> clazz = TypeManufacturerUtil.resolveGenericParameter(
genericIface,typeArgsMap, elementGenericTypeArgs);
if (Collection.class.isAssignableFrom(clazz)) {
collectionClass = clazz;
typeParams = elementGenericTypeArgs.get();
continue main;
}
}
Type type = collectionClass.getGenericSuperclass();
if (type != null) {
Class<?> clazz = TypeManufacturerUtil.resolveGenericParameter(
type, typeArgsMap, elementGenericTypeArgs);
if (Collection.class.isAssignableFrom(clazz)) {
collectionClass = clazz;
typeParams = elementGenericTypeArgs.get();
continue main;
}
}
if (Collection.class.equals(collectionClass)) {
LOG.warn("Collection {} doesn't have generic types,"
+ "will use Object instead", pojoClass);
typeParams = new Type[] { Object.class };
}
}
Class<?> elementTypeClass = TypeManufacturerUtil.resolveGenericParameter(typeParams[0],
typeArgsMap, elementGenericTypeArgs);
Type[] elementGenericArgs = ArrayUtils.addAll(
elementGenericTypeArgs.get(), genericTypeArgs);
elementGenericTypeArgs.set(elementGenericArgs);
return elementTypeClass;
}
private void fillCollection(ManufacturingContext manufacturingCtx,
List<Annotation> annotations, String attributeName,
Collection<? super Object> collection,
Class<?> collectionElementType, Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
// If the user defined a strategy to fill the collection elements,
// we use it
Holder<AttributeStrategy<?>> elementStrategyHolder
= new Holder<AttributeStrategy<?>>();
Holder<AttributeStrategy<?>> keyStrategyHolder = null;
Integer nbrElements = TypeManufacturerUtil.findCollectionSize(strategy, annotations,
collectionElementType, elementStrategyHolder, keyStrategyHolder);
AttributeStrategy<?> elementStrategy = elementStrategyHolder.value;
try {
if (collection.size() > nbrElements) {
collection.clear();
}
for (int i = collection.size(); i < nbrElements; i++) {
// The default
Object element;
if (null != elementStrategy
&& (elementStrategy instanceof ObjectStrategy)
&& Object.class.equals(collectionElementType)) {
LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy");
element = elementStrategy.getValue();
} else if (null != elementStrategy
&& !(elementStrategy instanceof ObjectStrategy)) {
LOG.debug("Collection elements will be filled using the following strategy: "
+ elementStrategy);
element = TypeManufacturerUtil.returnAttributeDataStrategyValue(
collectionElementType, elementStrategy);
} else {
element = manufactureAttributeValue(collection, manufacturingCtx,
collectionElementType, collectionElementType,
annotations, attributeName, NULL_TYPE_ARGS_MAP, genericTypeArgs);
}
collection.add(element);
}
} catch (UnsupportedOperationException e) {
LOG.warn("Cannot fill immutable collection {}", collection.getClass());
}
}
private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute(
Object pojo, ManufacturingContext manufacturingCtx,
AttributeMetadata attributeMetadata, Map<String, Type> typeArgsMap) {
String attributeName = attributeMetadata.getAttributeName();
Map<Object, Object> defaultValue = null;
if (null != pojo && !Character.isDigit(attributeName.charAt(0))) {
defaultValue = PodamUtils.getFieldValue(pojo, attributeName);
}
Map<Object, Object> retValue;
if (null != defaultValue &&
(defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) {
/* Default map, which is not immutable */
retValue = defaultValue;
} else {
@SuppressWarnings("unchecked")
Class<Map<Object,Object>> mapType
= (Class<Map<Object, Object>>) attributeMetadata.getAttributeType();
retValue = strategy.getTypeValue(attributeMetadata, typeArgsMap, mapType);
if (null != retValue && null != defaultValue) {
retValue.putAll(defaultValue);
}
}
if (null == retValue) {
return null;
}
try {
Class<?> keyClass = null;
Class<?> elementClass = null;
AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
if (ArrayUtils.isEmpty(attributeMetadata.getAttrGenericArgs())) {
MapArguments mapArgs = findInheretedMapElementType(retValue,
manufacturingCtx, typeArgsMap,
attributeMetadata.getAttrGenericArgs());
keyClass = mapArgs.getKeyClass();
elementClass = mapArgs.getElementClass();
} else {
// Expected only key, value type
if (attributeMetadata.getAttrGenericArgs().length != 2) {
throw new IllegalStateException(
"In a Map only key value generic type are expected,"
+ "but received " + Arrays.toString(attributeMetadata.getAttrGenericArgs()));
}
Type[] actualTypeArguments = attributeMetadata.getAttrGenericArgs();
keyClass = TypeManufacturerUtil.resolveGenericParameter(actualTypeArguments[0],
typeArgsMap, keyGenericTypeArgs);
elementClass = TypeManufacturerUtil.resolveGenericParameter(actualTypeArguments[1],
typeArgsMap, elementGenericTypeArgs);
}
MapArguments mapArguments = new MapArguments();
mapArguments.setAttributeName(attributeName);
mapArguments.setAnnotations(attributeMetadata.getAttributeAnnotations());
mapArguments.setMapToBeFilled(retValue);
mapArguments.setKeyClass(keyClass);
mapArguments.setElementClass(elementClass);
mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get());
mapArguments
.setElementGenericTypeArgs(elementGenericTypeArgs.get());
fillMap(mapArguments, manufacturingCtx);
} catch (InstantiationException e) {
throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e);
} catch (IllegalAccessException e) {
throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e);
} catch (SecurityException e) {
throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e);
} catch (ClassNotFoundException e) {
throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e);
} catch (InvocationTargetException e) {
throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e);
}
return retValue;
}
/**
* Finds key and element type arguments
*
* @param map
* The map being initialized
* @param manufacturingCtx
* the manufacturing context
* @param typeArgsMap
* a map relating the generic class arguments ("<T, V>" for
* example) with their actual types
* @param genericTypeArgs
* The generic type arguments for the current generic class
* instance
* @return
* Inherited map key and element types
*
*/
private MapArguments findInheretedMapElementType(Map<Object, Object> map,
ManufacturingContext manufacturingCtx, Map<String, Type> typeArgsMap,
Type... genericTypeArgs) {
Class<?> pojoClass = map.getClass();
Class<?> mapClass = pojoClass;
AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
Type[] typeParams = mapClass.getTypeParameters();
main : while (typeParams.length < 2) {
for (Type genericIface : mapClass.getGenericInterfaces()) {
Class<?> clazz = TypeManufacturerUtil.resolveGenericParameter(
genericIface, typeArgsMap, elementGenericTypeArgs);
if (Map.class.isAssignableFrom(clazz)) {
typeParams = elementGenericTypeArgs.get();
mapClass = clazz;
continue main;
}
}
Type type = mapClass.getGenericSuperclass();
if (type != null) {
Class<?> clazz = TypeManufacturerUtil.resolveGenericParameter(
type, typeArgsMap, elementGenericTypeArgs);
if (Map.class.isAssignableFrom(clazz)) {
typeParams = elementGenericTypeArgs.get();
mapClass = clazz;
continue main;
}
}
if (Map.class.equals(mapClass)) {
LOG.warn("Map {} doesn't have generic types,"
+ "will use Object, Object instead", pojoClass);
typeParams = new Type[] { Object.class, Object.class };
}
}
AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
Class<?> keyClass = TypeManufacturerUtil.resolveGenericParameter(typeParams[0],
typeArgsMap, keyGenericTypeArgs);
Class<?> elementClass = TypeManufacturerUtil.resolveGenericParameter(
typeParams[1], typeArgsMap, elementGenericTypeArgs);
Type[] keyGenericArgs = ArrayUtils.addAll(keyGenericTypeArgs.get(),
genericTypeArgs);
Type[] elementGenericArgs = ArrayUtils.addAll(elementGenericTypeArgs.get(),
genericTypeArgs);
MapArguments mapArguments = new MapArguments();
mapArguments.setAnnotations(Arrays.<Annotation>asList(pojoClass.getAnnotations()));
mapArguments.setMapToBeFilled(map);
mapArguments.setKeyClass(keyClass);
mapArguments.setElementClass(elementClass);
mapArguments.setKeyGenericTypeArgs(keyGenericArgs);
mapArguments.setElementGenericTypeArgs(elementGenericArgs);
return mapArguments;
}
private void fillMap(MapArguments mapArguments, ManufacturingContext manufacturingCtx)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
// If the user defined a strategy to fill the collection elements,
// we use it
Holder<AttributeStrategy<?>> elementStrategyHolder
= new Holder<AttributeStrategy<?>>();
Holder<AttributeStrategy<?>> keyStrategyHolder
= new Holder<AttributeStrategy<?>>();
Integer nbrElements = TypeManufacturerUtil.findCollectionSize(strategy, mapArguments.getAnnotations(),
mapArguments.getElementClass(), elementStrategyHolder,
keyStrategyHolder);
AttributeStrategy<?> keyStrategy = keyStrategyHolder.value;
AttributeStrategy<?> elementStrategy = elementStrategyHolder.value;
Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled();
try {
if (map.size() > nbrElements) {
map.clear();
}
for (int i = map.size(); i < nbrElements; i++) {
Object keyValue = null;
Object elementValue = null;
MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments();
valueArguments.setAttributeName(mapArguments.getAttributeName());
valueArguments.setMapToBeFilled(mapArguments.getMapToBeFilled());
valueArguments.setAnnotations(mapArguments.getAnnotations());
valueArguments.setKeyOrValueType(mapArguments.getKeyClass());
valueArguments.setElementStrategy(keyStrategy);
valueArguments.setGenericTypeArgs(mapArguments
.getKeyGenericTypeArgs());
keyValue = getMapKeyOrElementValue(valueArguments, manufacturingCtx);
valueArguments.setKeyOrValueType(mapArguments.getElementClass());
valueArguments.setElementStrategy(elementStrategy);
valueArguments.setGenericTypeArgs(mapArguments
.getElementGenericTypeArgs());
elementValue = getMapKeyOrElementValue(valueArguments, manufacturingCtx);
/* ConcurrentHashMap doesn't allow null values */
if (elementValue != null || !(map instanceof ConcurrentHashMap)) {
map.put(keyValue, elementValue);
}
}
} catch (UnsupportedOperationException e) {
LOG.warn("Cannot fill immutable map {}", map.getClass());
}
}
private Object getMapKeyOrElementValue(
MapKeyOrElementsArguments keyOrElementsArguments,
ManufacturingContext manufacturingCtx)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Object retValue = null;
if (null != keyOrElementsArguments.getElementStrategy()
&& ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments
.getElementStrategy().getClass())
&& Object.class.equals(keyOrElementsArguments
.getKeyOrValueType())) {
LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy");
retValue = keyOrElementsArguments.getElementStrategy().getValue();
} else if (null != keyOrElementsArguments.getElementStrategy()
&& !ObjectStrategy.class
.isAssignableFrom(keyOrElementsArguments
.getElementStrategy().getClass())) {
LOG.debug("Map key or value will be filled using the following strategy: "
+ keyOrElementsArguments.getElementStrategy());
retValue = TypeManufacturerUtil.returnAttributeDataStrategyValue(
keyOrElementsArguments.getKeyOrValueType(),
keyOrElementsArguments.getElementStrategy());
} else {
retValue = manufactureAttributeValue(
keyOrElementsArguments.getMapToBeFilled(),
manufacturingCtx,
keyOrElementsArguments.getKeyOrValueType(),
keyOrElementsArguments.getKeyOrValueType(),
keyOrElementsArguments.getAnnotations(),
keyOrElementsArguments.getAttributeName(),
NULL_TYPE_ARGS_MAP,
keyOrElementsArguments.getGenericTypeArgs());
}
return retValue;
}
private Object resolveArrayElementValue(Object pojo,
ManufacturingContext manufacturingCtx,
AttributeMetadata attributeMetadata,
Map<String, Type> typeArgsMap) throws InstantiationException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException {
@SuppressWarnings("unchecked")
Class<Object> arrayType
= (Class<Object>) attributeMetadata.getAttributeType();
Object array = strategy.getTypeValue(attributeMetadata, typeArgsMap, arrayType);
Class<?> componentType = array.getClass().getComponentType();
Type genericComponentType;
AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>(
PodamConstants.NO_TYPES);
Type genericType = attributeMetadata.getAttributeGenericType();
if (genericType instanceof GenericArrayType) {
genericComponentType = ((GenericArrayType) genericType).getGenericComponentType();
if (genericComponentType instanceof TypeVariable) {
TypeVariable<?> componentTypeVariable
= (TypeVariable<?>) genericComponentType;
final Type resolvedType
= typeArgsMap.get(componentTypeVariable.getName());
componentType
= TypeManufacturerUtil.resolveGenericParameter(resolvedType, typeArgsMap,
genericTypeArgs);
}
} else {
genericComponentType = componentType;
}
// If the user defined a strategy to fill the collection elements,
// we use it
Holder<AttributeStrategy<?>> elementStrategyHolder
= new Holder<AttributeStrategy<?>>();
Holder<AttributeStrategy<?>> keyStrategyHolder = null;
Integer nbrElements = TypeManufacturerUtil.findCollectionSize(strategy,
attributeMetadata.getAttributeAnnotations(),
attributeMetadata.getAttributeType(),
elementStrategyHolder, keyStrategyHolder);
AttributeStrategy<?> elementStrategy = elementStrategyHolder.value;
Object arrayElement = null;
for (int i = 0; i < nbrElements; i++) {
// The default
if (null != elementStrategy
&& (elementStrategy instanceof ObjectStrategy)
&& Object.class.equals(componentType)) {
LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy");
arrayElement = elementStrategy.getValue();
} else if (null != elementStrategy
&& !(elementStrategy instanceof ObjectStrategy)) {
LOG.debug("Array elements will be filled using the following strategy: "
+ elementStrategy);
arrayElement = TypeManufacturerUtil.returnAttributeDataStrategyValue(componentType,
elementStrategy);
} else {
arrayElement = manufactureAttributeValue(array, manufacturingCtx,
componentType, genericComponentType,
attributeMetadata.getAttributeAnnotations(),
attributeMetadata.getAttributeName(),
typeArgsMap, genericTypeArgs.get());
}
Array.set(array, i, arrayElement);
}
return array;
}
private Object[] getParameterValuesForConstructor(
Constructor<?> constructor, Class<?> pojoClass,
ManufacturingContext manufacturingCtx, Map<String, Type> typeArgsMap,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Class<?>[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == 0) {
return PodamConstants.NO_ARGS;
} else {
Object[] parameterValues = new Object[parameterTypes.length];
Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();
Type[] genericTypes = constructor.getGenericParameterTypes();
String ctorName = Arrays.toString(genericTypes);
for (int idx = 0; idx < parameterTypes.length; idx++) {
List<Annotation> annotations = Arrays
.asList(parameterAnnotations[idx]);
Type genericType = (idx < genericTypes.length) ?
genericTypes[idx] : parameterTypes[idx];
parameterValues[idx] = manufactureParameterValue(pojoClass,
idx + ctorName, parameterTypes[idx], genericType,
annotations, typeArgsMap, manufacturingCtx, genericTypeArgs);
}
return parameterValues;
}
}
private Object[] getParameterValuesForMethod(
Method method, Class<?> pojoClass,
ManufacturingContext manufacturingCtx, Map<String, Type> typeArgsMap,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
return PodamConstants.NO_ARGS;
} else {
Object[] parameterValues = new Object[parameterTypes.length];
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Type[] genericTypes = method.getGenericParameterTypes();
String methodName = Arrays.toString(genericTypes);
for (int idx = 0; idx < parameterTypes.length; idx++) {
List<Annotation> annotations = Arrays
.asList(parameterAnnotations[idx]);
Type genericType = (idx < genericTypes.length) ?
genericTypes[idx] : parameterTypes[idx];
parameterValues[idx] = manufactureParameterValue(pojoClass,
idx + methodName, parameterTypes[idx], genericType,
annotations, typeArgsMap, manufacturingCtx, genericTypeArgs);
}
return parameterValues;
}
}
private Object manufactureParameterValue(Class<?> pojoClass,
String parameterName, Class<?> parameterType, Type genericType,
final List<Annotation> annotations, final Map<String, Type> typeArgsMap,
ManufacturingContext manufacturingCtx,
Type... genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
AttributeStrategy<?> attributeStrategy
= TypeManufacturerUtil.findAttributeStrategy(strategy, annotations, parameterType);
if (null != attributeStrategy) {
LOG.debug("The parameter: " + genericType
+ " will be filled using the following strategy: "
+ attributeStrategy);
return TypeManufacturerUtil.returnAttributeDataStrategyValue(parameterType,
attributeStrategy);
}
Map<String, Type> typeArgsMapForParam;
if (genericType instanceof ParameterizedType) {
typeArgsMapForParam = new HashMap<String, Type>(typeArgsMap);
ParameterizedType parametrizedType =
(ParameterizedType) genericType;
TypeVariable<?>[] argumentTypes = parameterType.getTypeParameters();
Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments();
for (int k = 0; k < argumentTypes.length; k++) {
if (argumentGenericTypes[k] instanceof Class) {
Class<?> genericParam = (Class<?>) argumentGenericTypes[k];
typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam);
}
}
} else {
typeArgsMapForParam = typeArgsMap;
}
return manufactureAttributeValue(pojoClass, manufacturingCtx, parameterType,
genericType, annotations, parameterName, typeArgsMapForParam,
genericTypeArgs);
}
private <T> T getValueForAbstractType(Class<T> pojoClass,
AttributeMetadata pojoMetadata,
ManufacturingContext manufacturingCtx,
Map<String, Type> typeArgsMap,
Type[] genericTypeArgs)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Class<? extends T> specificClass = strategy.getSpecificClass(pojoClass);
if (!specificClass.equals(pojoClass)) {
return this.manufacturePojoInternal(specificClass, pojoMetadata,
manufacturingCtx, genericTypeArgs);
}
Class<?> factory = strategy.getFactoryClass(pojoClass);
if (factory != null) {
T retValue = instantiatePojoWithFactory(factory, pojoClass,
manufacturingCtx, typeArgsMap, genericTypeArgs);
if (retValue != null) {
return retValue;
}
}
return resortToExternalFactory(manufacturingCtx,
"Cannot instantiate a class {}. Resorting to {} external factory",
pojoClass, genericTypeArgs);
}
} |
package yokohama.unit.translator;
import yokohama.unit.contract.Contract;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Modifier;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import yokohama.unit.ast.AnchorExpr;
import yokohama.unit.ast.AsExpr;
import yokohama.unit.ast.Assertion;
import yokohama.unit.ast.BooleanExpr;
import yokohama.unit.ast.Cell;
import yokohama.unit.ast.CharExpr;
import yokohama.unit.ast.ChoiceBinding;
import yokohama.unit.ast.ChoiceCollectVisitor;
import yokohama.unit.ast.Clause;
import yokohama.unit.ast.CodeBlock;
import yokohama.unit.ast.CodeBlockExtractVisitor;
import yokohama.unit.ast.Definition;
import yokohama.unit.ast.DoesNotMatchPredicate;
import yokohama.unit.ast.EqualToMatcher;
import yokohama.unit.ast.Execution;
import yokohama.unit.ast.FloatingPointExpr;
import yokohama.unit.ast.FourPhaseTest;
import yokohama.unit.ast.Group;
import yokohama.unit.ast.Ident;
import yokohama.unit.ast.InstanceOfMatcher;
import yokohama.unit.ast.InstanceSuchThatMatcher;
import yokohama.unit.ast.IntegerExpr;
import yokohama.unit.ast.InvocationExpr;
import yokohama.unit.ast.Invoke;
import yokohama.unit.ast.IsNotPredicate;
import yokohama.unit.ast.IsPredicate;
import yokohama.unit.ast.Matcher;
import yokohama.unit.ast.MatchesPredicate;
import yokohama.unit.ast.MethodPattern;
import yokohama.unit.ast.NullValueMatcher;
import yokohama.unit.ast.Pattern;
import yokohama.unit.ast.Phase;
import yokohama.unit.ast.Predicate;
import yokohama.unit.ast.Proposition;
import yokohama.unit.ast.QuotedExpr;
import yokohama.unit.ast.RegExpPattern;
import yokohama.unit.ast.ResourceExpr;
import yokohama.unit.ast.Row;
import yokohama.unit.ast.SingleBinding;
import yokohama.unit.ast.StringExpr;
import yokohama.unit.ast.Table;
import yokohama.unit.ast.TableBinding;
import yokohama.unit.ast.TableExtractVisitor;
import yokohama.unit.ast.TableRef;
import yokohama.unit.ast.Test;
import yokohama.unit.ast.ThrowsPredicate;
import yokohama.unit.ast_junit.Annotation;
import yokohama.unit.ast_junit.ArrayExpr;
import yokohama.unit.ast_junit.BooleanLitExpr;
import yokohama.unit.ast_junit.CatchClause;
import yokohama.unit.ast_junit.CharLitExpr;
import yokohama.unit.ast_junit.ClassDecl;
import yokohama.unit.ast_junit.ClassType;
import yokohama.unit.ast_junit.CompilationUnit;
import yokohama.unit.ast_junit.DoubleLitExpr;
import yokohama.unit.ast_junit.EqualToMatcherExpr;
import yokohama.unit.ast_junit.FloatLitExpr;
import yokohama.unit.ast_junit.InstanceOfMatcherExpr;
import yokohama.unit.ast_junit.IntLitExpr;
import yokohama.unit.ast_junit.InvokeExpr;
import yokohama.unit.ast_junit.InvokeStaticExpr;
import yokohama.unit.ast_junit.InvokeStaticVoidStatement;
import yokohama.unit.ast_junit.InvokeVoidStatement;
import yokohama.unit.ast_junit.IsStatement;
import yokohama.unit.ast_junit.LongLitExpr;
import yokohama.unit.ast_junit.Method;
import yokohama.unit.ast_junit.NewExpr;
import yokohama.unit.ast_junit.NullExpr;
import yokohama.unit.ast_junit.NullValueMatcherExpr;
import yokohama.unit.ast_junit.PrimitiveType;
import yokohama.unit.ast_junit.RegExpMatcherExpr;
import yokohama.unit.ast_junit.Statement;
import yokohama.unit.ast_junit.StrLitExpr;
import yokohama.unit.ast_junit.ThisClassExpr;
import yokohama.unit.ast_junit.TryStatement;
import yokohama.unit.ast_junit.Type;
import yokohama.unit.util.Sym;
import yokohama.unit.ast_junit.VarExpr;
import yokohama.unit.ast_junit.VarInitStatement;
import yokohama.unit.position.Position;
import yokohama.unit.position.Span;
import yokohama.unit.util.ClassResolver;
import yokohama.unit.util.FList;
import yokohama.unit.util.GenSym;
import yokohama.unit.util.Lists;
import yokohama.unit.util.Optionals;
import yokohama.unit.util.Pair;
import yokohama.unit.util.SUtils;
@RequiredArgsConstructor
public class AstToJUnitAst {
final String name;
final String packageName;
final ExpressionStrategy expressionStrategy;
final MockStrategy mockStrategy;
final CombinationStrategy combinationStrategy;
final GenSym genSym;
final ClassResolver classResolver;
final TableExtractVisitor tableExtractVisitor;
final CodeBlockExtractVisitor codeBlockExtractVisitor =
new CodeBlockExtractVisitor();
final boolean checkContract;
public CompilationUnit translate(Group group) {
final List<Table> tables = tableExtractVisitor.extractTables(group);
Map<String, CodeBlock> codeBlockMap =
codeBlockExtractVisitor.extractMap(group);
final ChoiceCollectVisitor choiceCollectVisitor =
new ChoiceCollectVisitor(tables);
return new AstToJUnitAstVisitor(
name,
packageName,
expressionStrategy,
mockStrategy,
combinationStrategy,
genSym,
classResolver,
tables,
codeBlockMap,
choiceCollectVisitor,
checkContract)
.translateGroup(group);
}
}
@RequiredArgsConstructor
class AstToJUnitAstVisitor {
final String name;
final String packageName;
final ExpressionStrategy expressionStrategy;
final MockStrategy mockStrategy;
final CombinationStrategy combinationStrategy;
final GenSym genSym;
final ClassResolver classResolver;
final List<Table> tables;
final Map<String, CodeBlock> codeBlockMap;
final ChoiceCollectVisitor choiceCollectVisitor;
final boolean checkContract;
final DataConverterFinder dataConverterFinder = new DataConverterFinder();
static final String MATCHER = "org.hamcrest.Matcher";
static final String CORE_MATCHERS = "org.hamcrest.CoreMatchers";
static final String TEST = "org.junit.Test";
@SneakyThrows(ClassNotFoundException.class)
ClassType classTypeOf(String name) {
return new ClassType(classResolver.lookup(name));
}
Type typeOf(String name) {
return classTypeOf(name).toType();
}
Annotation annotationOf(String name) {
return new Annotation(classTypeOf(name));
}
CompilationUnit translateGroup(Group group) {
List<Definition> definitions = group.getDefinitions();
List<Method> methods =
definitions.stream()
.flatMap(definition -> definition.accept(
test -> translateTest(test).stream(),
fourPhaseTest ->
translateFourPhaseTest(
fourPhaseTest).stream(),
table -> Stream.empty(),
codeBlock -> Stream.empty(),
heading -> Stream.empty()))
.collect(Collectors.toList());
ClassDecl testClass =
new ClassDecl(true, name, Optional.empty(), Arrays.asList(), methods);
Stream<ClassDecl> auxClasses = Stream.concat(
expressionStrategy.auxClasses().stream(),
mockStrategy.auxClasses().stream());
List<ClassDecl> classes =
Stream.concat(auxClasses, Stream.of(testClass))
.collect(Collectors.toList());
return new CompilationUnit(packageName, classes);
}
List<Method> translateTest(Test test) {
final String name = test.getName();
List<Assertion> assertions = test.getAssertions();
return IntStream.range(0, assertions.size())
.mapToObj(Integer::new)
.flatMap(assertionNo -> {
Sym env = genSym.generate("env");
List<List<Statement>> bodies =
translateAssertion(
assertions.get(assertionNo), env);
return IntStream.range(0, bodies.size())
.mapToObj(Integer::new)
.map(bodyNo -> {
String methodName = SUtils.toIdent(name)
+ "_" + assertionNo + "_" + bodyNo;
return new Method(
Arrays.asList(annotationOf(TEST)),
methodName,
Arrays.asList(),
Optional.empty(),
Arrays.asList(ClassType.EXCEPTION),
ListUtils.union(
expressionStrategy.env(env),
bodies.get(bodyNo)));
});
})
.collect(Collectors.toList());
}
List<List<Statement>> translateAssertion(Assertion assertion, Sym env) {
List<Clause> clauses = assertion.getClauses();
return assertion.getFixture().accept(
() -> {
List<Statement> body = clauses.stream()
.flatMap(clause ->
translateClause(clause, env))
.collect(Collectors.toList());
return Arrays.asList(body);
},
tableRef -> {
List<List<Statement>> table =
translateTableRef(tableRef, env);
return IntStream.range(0, table.size())
.mapToObj(Integer::new)
.map(i -> {
return ListUtils.union(
table.get(i),
clauses.stream()
.flatMap(clause ->
translateClause(clause, env))
.collect(Collectors.toList()));
}).collect(Collectors.toList());
},
bindings -> {
List<Pair<List<Ident>, List<List<yokohama.unit.ast.Expr>>>> candidates =
choiceCollectVisitor.visitBindings(bindings).collect(Collectors.toList());
List<Map<Ident, yokohama.unit.ast.Expr>> choices = candidatesToChoices(candidates);
return choices.stream()
.map((Map<Ident, yokohama.unit.ast.Expr> choice) ->
Stream.concat(
bindings.getBindings()
.stream()
.flatMap(binding ->
translateBinding(binding, choice, env)),
clauses.stream()
.flatMap(clause ->
translateClause(clause, env)))
.collect(Collectors.toList()))
.collect(Collectors.toList());
});
}
private List<Map<Ident, yokohama.unit.ast.Expr>> candidatesToChoices(
List<Pair<List<Ident>, List<List<yokohama.unit.ast.Expr>>>> candidates) {
return combinationStrategy.generate(candidates)
.stream()
.map((List<Pair<List<Ident>, List<yokohama.unit.ast.Expr>>> choice) ->
choice.stream()
.map(p -> Pair.zip(p.getFirst(), p.getSecond()))
.flatMap(List::stream))
.map((Stream<Pair<Ident, yokohama.unit.ast.Expr>> choice) ->
choice.<Map<Ident, yokohama.unit.ast.Expr>>collect(
() -> new HashMap<>(),
(m, kv) -> m.put(kv.getFirst(), kv.getSecond()),
(m1, m2) -> m1.putAll(m2)))
.collect(Collectors.toList());
}
Stream<Statement> translateClause(Clause clause, Sym envVar) {
/* Disjunctive clause is translated as follows:
try {
assertThat(...);
} catch (Throwable e) {
try {
assertThat(...);
} catch (Throwable e) {
assertThat(...);
}
}
*/
FList<Proposition> revPropositions =
FList.fromReverseList(clause.getPropositions());
return revPropositions.match(
() -> {
throw new TranslationException(
"clause is empty", clause.getSpan());
},
(last, init) -> {
Stream<Statement> lastStatements =
translateProposition(last, envVar);
return init.foldLeft(
lastStatements,
(statements, prop) -> {
Stream<Statement> propStatements =
translateProposition(prop, envVar);
Sym e = genSym.generate("e");
CatchClause catchClause =
new CatchClause(
ClassType.THROWABLE,
e,
statements.collect(
Collectors.toList()));
Statement tryStatement =
new TryStatement(
propStatements.collect(
Collectors.toList()),
Arrays.asList(catchClause),
Collections.emptyList());
return Stream.of(tryStatement);
});
});
}
Stream<Statement> translateProposition(
Proposition proposition, Sym envVar) {
yokohama.unit.ast.Expr subject = proposition.getSubject();
Predicate predicate = proposition.getPredicate();
return predicate.<Stream<Statement>>accept(
isPredicate -> translateIsPredicate(subject, isPredicate, envVar),
isNotPredicate -> translateIsNotPredicate(subject, isNotPredicate, envVar),
throwsPredicate -> translateThrowsPredicate(subject, throwsPredicate, envVar),
matchesPredicate ->
translateMatchesPredicate(
subject, matchesPredicate, envVar),
doesNotMatchPredicate ->
translateDoesNotMatchPredicate(
subject, doesNotMatchPredicate, envVar));
}
Stream<Statement> translateIsPredicate(
yokohama.unit.ast.Expr subject, IsPredicate isPredicate, Sym envVar) {
Sym message = genSym.generate("message");
Sym actual = genSym.generate("actual");
return StreamCollector.<Statement>empty()
.append(translateExpr(subject, actual, Object.class, envVar))
.append(translateMatcher(
isPredicate.getComplement(),
actual,
matcherVar -> StreamCollector.<Statement>empty()
.append(expressionStrategy.dumpEnv(message, envVar))
.append(new IsStatement(
message,
actual,
matcherVar,
isPredicate.getSpan()))
.getStream(),
envVar))
.getStream();
}
Stream<Statement> translateIsNotPredicate(
yokohama.unit.ast.Expr subject, IsNotPredicate isNotPredicate, Sym envVar) {
// inhibit `is not instance e of Exception such that...`
isNotPredicate.getComplement().accept(
equalTo -> null,
instanceOf -> null,
instanceSuchThat -> {
throw new TranslationException(
"`instance _ of _ such that` cannot follow `is not`",
instanceSuchThat.getSpan());
},
nullValue -> null);
Sym message = genSym.generate("message");
Sym actual = genSym.generate("actual");
Sym expected = genSym.generate("expected");
return StreamCollector.<Statement>empty()
.append(translateExpr(subject, actual, Object.class, envVar))
.append(translateMatcher(
isNotPredicate.getComplement(),
actual,
matcherVar -> StreamCollector.<Statement>empty()
.append(new VarInitStatement(
typeOf(MATCHER),
expected,
new InvokeStaticExpr(
classTypeOf(CORE_MATCHERS),
Arrays.asList(),
"not",
Arrays.asList(typeOf(MATCHER)),
Arrays.asList(matcherVar),
typeOf(MATCHER)),
isNotPredicate.getSpan()))
.append(expressionStrategy.dumpEnv(message, envVar))
.append(new IsStatement(
message,
actual,
expected,
isNotPredicate.getSpan()))
.getStream(),
envVar))
.getStream();
}
Stream<Statement> translateThrowsPredicate(
yokohama.unit.ast.Expr subject, ThrowsPredicate throwsPredicate, Sym envVar) {
Sym message = genSym.generate("message");
Sym actual = genSym.generate("actual");
Sym __ = genSym.generate("tmp");
return StreamCollector.<Statement>empty()
.append(bindThrown(
actual,
translateExpr(subject, __, Object.class, envVar)
.collect(Collectors.toList()),
envVar))
.append(translateMatcher(
throwsPredicate.getThrowee(),
actual,
matcherVar -> StreamCollector.<Statement>empty()
.append(expressionStrategy.dumpEnv(message, envVar))
.append(new IsStatement(
message,
actual,
matcherVar,
throwsPredicate.getSpan()))
.getStream(),
envVar))
.getStream();
}
Stream<Statement> bindThrown(
Sym actual, List<Statement> statements, Sym envVar) {
Sym e = genSym.generate("ex");
/*
Throwable actual;
try {
// statements
actual = null;
} catch (XXXXException e) { // extract the cause if wrapped: inserted by the strategy
actual = e.get...;
} catch (Throwable e) {
actual = e;
}
*/
return Stream.of(new TryStatement(
ListUtils.union(
statements,
Arrays.asList(new VarInitStatement(
Type.THROWABLE,
actual,
new NullExpr(),
Span.dummySpan()))),
Stream.concat(Optionals.toStream(
expressionStrategy.catchAndAssignCause(actual)),
Stream.of(new CatchClause(
ClassType.THROWABLE,
e,
Arrays.asList(new VarInitStatement(
Type.THROWABLE,
actual,
new VarExpr(e),
Span.dummySpan())))))
.collect(Collectors.toList()),
Arrays.asList()));
}
Stream<Statement> translateMatchesPredicate(
yokohama.unit.ast.Expr subject,
MatchesPredicate matchesPredicate,
Sym envVar) {
Pattern pattern = matchesPredicate.getPattern();
Sym message = genSym.generate("message");
Sym actual = genSym.generate("actual");
Sym expected = genSym.generate("expected");
return StreamCollector.<Statement>empty()
.append(translateExpr(subject, actual, Object.class, envVar))
.append(translatePattern(pattern, expected, envVar))
.append(expressionStrategy.dumpEnv(message, envVar))
.append(new IsStatement(
message, actual, expected, matchesPredicate.getSpan()))
.getStream();
}
Stream<Statement> translateDoesNotMatchPredicate(
yokohama.unit.ast.Expr subject,
DoesNotMatchPredicate doesNotMatchPredicate,
Sym envVar) {
Pattern pattern = doesNotMatchPredicate.getPattern();
Sym message = genSym.generate("message");
Sym actual = genSym.generate("actual");
Sym unexpected = genSym.generate("unexpected");
Sym expected = genSym.generate("expected");
return StreamCollector.<Statement>empty()
.append(translateExpr(subject, actual, Object.class, envVar))
.append(translatePattern(pattern, unexpected, envVar))
.append(new VarInitStatement(
typeOf(MATCHER),
expected,
new InvokeStaticExpr(
classTypeOf(CORE_MATCHERS),
Arrays.asList(),
"not",
Arrays.asList(typeOf(MATCHER)),
Arrays.asList(unexpected),
typeOf(MATCHER)),
doesNotMatchPredicate.getSpan()))
.append(expressionStrategy.dumpEnv(message, envVar))
.append(new IsStatement(
message, actual, expected, doesNotMatchPredicate.getSpan()))
.getStream();
}
private String lookupClassName(String name, Span span) {
try {
return classResolver.lookup(name).getCanonicalName();
} catch (ClassNotFoundException e) {
throw new TranslationException(e.getMessage(), span, e);
}
}
Stream<Statement> translateMatcher(
Matcher matcher,
Sym actual,
Function<Sym, Stream<Statement>> cont,
Sym envVar) {
Sym matcherVar = genSym.generate("matcher");
return matcher.<Stream<Statement>>accept((EqualToMatcher equalTo) -> {
Sym objVar = genSym.generate("obj");
return StreamCollector.<Statement>empty()
.append(translateExpr(equalTo.getExpr(),
objVar,
Object.class,
envVar))
.append(new VarInitStatement(
typeOf(MATCHER),
matcherVar,
new EqualToMatcherExpr(objVar),
equalTo.getSpan()))
.append(cont.apply(matcherVar))
.getStream();
},
(InstanceOfMatcher instanceOf) -> {
return StreamCollector.<Statement>empty()
.append(new VarInitStatement(
typeOf(MATCHER),
matcherVar,
new InstanceOfMatcherExpr(
ClassType.of(
instanceOf.getClazz(),
classResolver)),
instanceOf.getSpan()))
.append(cont.apply(matcherVar))
.getStream();
},
(InstanceSuchThatMatcher instanceSuchThat) -> {
Ident bindVar = instanceSuchThat.getVar();
yokohama.unit.ast.ClassType clazz = instanceSuchThat.getClazz();
List<Proposition> propositions = instanceSuchThat.getPropositions();
Span span = instanceSuchThat.getSpan();
Sym instanceOfVar = genSym.generate("instanceOfMatcher");
Stream<Statement> instanceOfStatements =
StreamCollector.<Statement>empty()
.append(new VarInitStatement(
typeOf(MATCHER),
instanceOfVar,
new InstanceOfMatcherExpr(
ClassType.of(
instanceSuchThat.getClazz(),
classResolver)),
clazz.getSpan()))
.append(cont.apply(instanceOfVar))
.getStream();
Stream<Statement> bindStatements =
expressionStrategy.bind(envVar, bindVar, actual).stream();
Stream<Statement> suchThatStatements =
propositions
.stream()
.flatMap(proposition ->
translateProposition(proposition, envVar));
return StreamCollector.<Statement>empty()
.append(instanceOfStatements)
.append(bindStatements)
.append(suchThatStatements)
.getStream();
},
(NullValueMatcher nullValue) -> {
return StreamCollector.<Statement>empty()
.append(new VarInitStatement(
typeOf(MATCHER),
matcherVar,
new NullValueMatcherExpr(),
nullValue.getSpan()))
.append(cont.apply(matcherVar))
.getStream();
});
}
Stream<Statement> translatePattern(
Pattern pattern, Sym var, Sym envVar) {
return pattern.accept((Function<RegExpPattern, Stream<Statement>>)
regExpPattern ->
translateRegExpPattern(regExpPattern, var, envVar));
}
Stream<Statement> translateRegExpPattern(
RegExpPattern regExpPattern, Sym var, Sym envVar) {
regExpPattern.getRegexp();
return Stream.of(
new VarInitStatement(
typeOf(MATCHER),
var,
new RegExpMatcherExpr(regExpPattern.getRegexp()),
regExpPattern.getSpan()));
}
Stream<Statement> translateBinding(
yokohama.unit.ast.Binding binding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar) {
return binding.accept(
singleBinding -> translateSingleBinding(singleBinding, envVar),
choiceBinding -> translateChoiceBinding(choiceBinding, choice, envVar),
tableBinding -> translateTableBinding(tableBinding, choice, envVar));
}
Stream<Statement> translateBindingWithContract(
yokohama.unit.ast.Binding binding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar,
Sym contractVar) {
return binding.accept(
singleBinding -> translateSingleBindingWithContract(singleBinding, envVar, contractVar),
choiceBinding -> translateChoiceBindingWithContract(choiceBinding, choice, envVar, contractVar),
tableBinding -> translateTableBindingWithContract(tableBinding, choice, envVar, contractVar));
}
Stream<Statement> insertContract(Sym contractVar, Sym objVar) {
return checkContract
? Stream.of(
new InvokeVoidStatement(
ClassType.fromClass(Contract.class),
contractVar,
"assertSatisfied",
Arrays.asList(Type.OBJECT),
Arrays.asList(objVar),
Span.dummySpan()))
: Stream.empty();
}
Stream<Statement> translateSingleBinding(
SingleBinding singleBinding, Sym envVar) {
Ident name = singleBinding.getName();
Sym var = genSym.generate(name.getName());
return Stream.concat(
translateExpr(singleBinding.getValue(), var, Object.class, envVar),
expressionStrategy.bind(envVar, name, var).stream());
}
Stream<Statement> translateSingleBindingWithContract(
SingleBinding singleBinding, Sym envVar, Sym contractVar) {
Ident name = singleBinding.getName();
Sym var = genSym.generate(name.getName());
return StreamCollector.<Statement>empty()
.append(translateExpr(singleBinding.getValue(), var, Object.class, envVar))
.append(insertContract(contractVar, var))
.append(expressionStrategy.bind(envVar, name, var).stream())
.getStream();
}
Stream<Statement> translateChoiceBinding(
ChoiceBinding choiceBinding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar) {
Ident name = choiceBinding.getName();
yokohama.unit.ast.Expr expr = choice.get(name);
Sym var = genSym.generate(name.getName());
return Stream.concat(
translateExpr(expr, var, Object.class, envVar),
expressionStrategy.bind(envVar, name, var).stream());
}
Stream<Statement> translateChoiceBindingWithContract(
ChoiceBinding choiceBinding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar,
Sym contractVar) {
Ident name = choiceBinding.getName();
yokohama.unit.ast.Expr expr = choice.get(name);
Sym var = genSym.generate(name.getName());
return StreamCollector.<Statement>empty()
.append(translateExpr(expr, var, Object.class, envVar))
.append(insertContract(contractVar, var))
.append(expressionStrategy.bind(envVar, name, var).stream())
.getStream();
}
Stream<Statement> translateTableBinding(
TableBinding tableBinding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar) {
List<Ident> idents = tableBinding.getIdents();
return idents.stream().flatMap(ident -> {
yokohama.unit.ast.Expr expr = choice.get(ident);
Sym var = genSym.generate(ident.getName());
return Stream.concat(
translateExpr(expr, var, Object.class, envVar),
expressionStrategy.bind(envVar, ident, var).stream());
});
}
Stream<Statement> translateTableBindingWithContract(
TableBinding tableBinding,
Map<Ident, yokohama.unit.ast.Expr> choice,
Sym envVar,
Sym contractVar) {
List<Ident> idents = tableBinding.getIdents();
return idents.stream().flatMap(ident -> {
yokohama.unit.ast.Expr expr = choice.get(ident);
Sym var = genSym.generate(ident.getName());
return StreamCollector.<Statement>empty()
.append(translateExpr(expr, var, Object.class, envVar))
.append(insertContract(contractVar, var))
.append(expressionStrategy.bind(envVar, ident, var).stream())
.getStream();
});
}
Stream<Statement> translateExpr(
yokohama.unit.ast.Expr expr,
Sym var,
Class<?> expectedType,
Sym envVar) {
Sym exprVar = genSym.generate("expr");
Stream<Statement> statements = expr.accept(
quotedExpr -> {
return expressionStrategy.eval(
exprVar,
quotedExpr,
Type.fromClass(expectedType).box().toClass(),
envVar).stream();
},
stubExpr -> {
return mockStrategy.stub(
exprVar,
stubExpr,
this,
envVar).stream();
},
invocationExpr -> {
return translateInvocationExpr(invocationExpr, exprVar, envVar);
},
integerExpr -> {
return translateIntegerExpr(integerExpr, exprVar, envVar);
},
floatingPointExpr -> {
return translateFloatingPointExpr(floatingPointExpr, exprVar, envVar);
},
booleanExpr -> {
return translateBooleanExpr(booleanExpr, exprVar, envVar);
},
charExpr -> {
return translateCharExpr(charExpr, exprVar, envVar);
},
stringExpr -> {
return translateStringExpr(stringExpr, exprVar, envVar);
},
anchorExpr -> {
return translateAnchorExpr(anchorExpr, exprVar, envVar);
},
asExpr -> {
return translateAsExpr(asExpr, exprVar, envVar);
},
resourceExpr -> {
return translateResourceExpr(resourceExpr, exprVar, envVar);
});
// box or unbox if needed
Stream<Statement> boxing =
boxOrUnbox(Type.fromClass(expectedType),
var,
typeOfExpr(expr),
exprVar);
return Stream.concat(statements, boxing);
}
Stream<Statement> translateInvocationExpr(
InvocationExpr invocationExpr,
Sym var,
Sym envVar) {
yokohama.unit.ast.ClassType classType = invocationExpr.getClassType();
Class<?> clazz = classType.toClass(classResolver);
MethodPattern methodPattern = invocationExpr.getMethodPattern();
String methodName = methodPattern.getName();
List<yokohama.unit.ast.Type> argTypes = methodPattern.getParamTypes();
boolean isVararg = methodPattern.isVararg();
Optional<yokohama.unit.ast.Expr> receiver = invocationExpr.getReceiver();
List<yokohama.unit.ast.Expr> args = invocationExpr.getArgs();
Type returnType = typeOfExpr(invocationExpr);
Pair<List<Sym>, Stream<Statement>> argVarsAndStatements =
setupArgs(argTypes, isVararg, args, envVar);
List<Sym> argVars = argVarsAndStatements.getFirst();
Stream<Statement> setupStatements = argVarsAndStatements.getSecond();
Stream<Statement> invocation = generateInvoke(
var,
classType,
methodName,
argTypes,
isVararg,
argVars,
receiver,
returnType,
envVar,
invocationExpr.getSpan());
return Stream.concat(setupStatements, invocation);
}
Stream<Statement> translateIntegerExpr(
IntegerExpr integerExpr,
Sym var,
Sym envVar) {
return integerExpr.match(intValue -> {
return Stream.<Statement>of(new VarInitStatement(
Type.INT,
var,
new IntLitExpr(intValue),
integerExpr.getSpan()));
},
longValue -> {
return Stream.<Statement>of(new VarInitStatement(
Type.LONG,
var,
new LongLitExpr(longValue),
integerExpr.getSpan()));
});
}
Stream<Statement> translateFloatingPointExpr(
FloatingPointExpr floatingPointExpr,
Sym var,
Sym envVar) {
return floatingPointExpr.match(floatValue -> {
return Stream.<Statement>of(new VarInitStatement(
Type.FLOAT,
var,
new FloatLitExpr(floatValue),
floatingPointExpr.getSpan()));
},
doubleValue -> {
return Stream.<Statement>of(new VarInitStatement(
Type.DOUBLE,
var,
new DoubleLitExpr(doubleValue),
floatingPointExpr.getSpan()));
});
}
Stream<Statement> translateBooleanExpr(
BooleanExpr booleanExpr, Sym var, Sym envVar) {
boolean booleanValue = booleanExpr.getValue();
return Stream.<Statement>of(new VarInitStatement(
Type.BOOLEAN,
var,
new BooleanLitExpr(booleanValue),
booleanExpr.getSpan()));
}
Stream<Statement> translateCharExpr(
CharExpr charExpr, Sym var, Sym envVar) {
char charValue = charExpr.getValue();
return Stream.<Statement>of(new VarInitStatement(
Type.CHAR,
var,
new CharLitExpr(charValue),
charExpr.getSpan()));
}
Stream<Statement> translateStringExpr(
StringExpr stringExpr, Sym var, Sym envVar) {
String strValue = stringExpr.getValue();
return Stream.<Statement>of(new VarInitStatement(
Type.STRING,
var,
new StrLitExpr(strValue),
stringExpr.getSpan()));
}
Stream<Statement> translateAnchorExpr(
AnchorExpr anchorExpr, Sym var, Sym envVar) {
String anchor = anchorExpr.getAnchor();
CodeBlock codeBlock = codeBlockMap.get(anchor);
String code = codeBlock.getCode();
return Stream.<Statement>of(new VarInitStatement(
Type.STRING,
var,
new StrLitExpr(code),
anchorExpr.getSpan()));
}
private Stream<Statement> translateAsExpr(AsExpr asExpr, Sym exprVar, Sym envVar) {
Sym sourceVar = genSym.generate("source");
Stream<Statement> source = translateExpr(asExpr.getSourceExpr(), sourceVar, String.class, envVar);
yokohama.unit.ast.ClassType classType = asExpr.getClassType();
Class<?> returnType = classType.toClass(classResolver);
Stream<Statement> convert = Optionals.match(
dataConverterFinder.find(returnType, classResolver.getClassLoader()),
() -> {
throw new TranslationException(
"converter method for " + classType.getName() + " not found",
asExpr.getSpan());
},
method -> {
Class<?> clazz = method.getDeclaringClass();
int modifier = method.getModifiers();
if (Modifier.isStatic(modifier)) {
return Stream.of(
new VarInitStatement(
Type.fromClass(returnType),
exprVar,
new InvokeStaticExpr(
ClassType.fromClass(clazz),
Collections.emptyList(),
method.getName(),
Arrays.asList(Type.STRING),
Arrays.asList(sourceVar),
Type.fromClass(returnType)),
asExpr.getSpan()));
} else {
throw new UnsupportedOperationException("non static method");
}
});
return Stream.concat(source, convert);
}
private Stream<Statement> translateResourceExpr(
ResourceExpr resourceExpr, Sym exprVar, Sym envVar) {
Sym classVar = genSym.generate("clazz");
Sym nameVar = genSym.generate("name");
Stream<Statement> classAndName = Stream.of(
new VarInitStatement(
Type.CLASS,
classVar,
new ThisClassExpr(),
resourceExpr.getSpan()),
new VarInitStatement(
Type.STRING,
nameVar,
new StrLitExpr(resourceExpr.getName()),
resourceExpr.getSpan()));
Stream<Statement> getResource = Optionals.match(
resourceExpr.getClassType(),
() -> {
return Stream.of(
new VarInitStatement(
Type.URL,
exprVar,
new InvokeExpr(
ClassType.CLASS,
classVar,
"getResource",
Arrays.asList(Type.STRING),
Arrays.asList(nameVar),
Type.URL),
resourceExpr.getSpan()));
},
classType -> {
if (classType.toClass(classResolver).equals(java.io.InputStream.class)) {
return Stream.of(
new VarInitStatement(
typeOf("java.io.InputStream"),
exprVar,
new InvokeExpr(
ClassType.CLASS,
classVar,
"getResourceAsStream",
Arrays.asList(Type.STRING),
Arrays.asList(nameVar),
typeOf("java.io.InputStream")),
resourceExpr.getSpan()));
} else if (classType.toClass(classResolver).equals(java.net.URI.class)) {
Sym urlVar = genSym.generate("url");
return Stream.of(
new VarInitStatement(
Type.URL,
urlVar,
new InvokeExpr(
ClassType.CLASS,
classVar,
"getResource",
Arrays.asList(Type.STRING),
Arrays.asList(nameVar),
Type.URL),
resourceExpr.getSpan()),
new VarInitStatement(
typeOf("java.net.URI"),
exprVar,
new InvokeExpr(
classTypeOf("java.net.URL"),
urlVar,
"toURI",
Arrays.asList(),
Arrays.asList(),
typeOf("java.net.URI")),
resourceExpr.getSpan()));
} else {
throw new TranslationException(
"Conversion into " + classType + "not supported",
resourceExpr.getSpan());
}
});
return Stream.concat(classAndName, getResource);
}
Stream<Statement> boxOrUnbox(
Type toType, Sym toVar, Type fromType, Sym fromVar) {
return fromType.<Stream<Statement>>matchPrimitiveOrNot(
primitiveType -> {
return fromPrimitive(
toType, toVar, primitiveType, fromVar);
},
nonPrimitiveType -> {
return fromNonPrimtive(toType, toVar, fromVar);
});
}
private Stream<Statement> fromPrimitive(
Type toType, Sym toVar, PrimitiveType fromType, Sym fromVar) {
return toType.<Stream<Statement>>matchPrimitiveOrNot(
primitiveType -> {
return Stream.of(
new VarInitStatement(
toType,
toVar,
new VarExpr(fromVar),
Span.dummySpan()));
},
nonPrimitiveType -> {
return Stream.of(new VarInitStatement(
nonPrimitiveType,
toVar,
new InvokeStaticExpr(
fromType.box(),
Arrays.asList(),
"valueOf",
Arrays.asList(fromType.toType()),
Arrays.asList(fromVar),
fromType.box().toType()),
Span.dummySpan()));
});
}
private Stream<Statement> fromNonPrimtive(
Type toType, Sym toVar, Sym fromVar) {
// precondition: fromVar is not primitive
return toType.<Stream<Statement>>matchPrimitiveOrNot(primitiveType -> {
Sym boxVar = genSym.generate("box");
ClassType boxType;
String unboxMethodName;
switch (primitiveType.getKind()) {
case BOOLEAN:
boxType = primitiveType.box();
unboxMethodName = "booleanValue";
break;
case BYTE:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "byteValue";
break;
case SHORT:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "shortValue";
break;
case INT:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "intValue";
break;
case LONG:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "longValue";
break;
case CHAR:
boxType = primitiveType.box();
unboxMethodName = "charValue";
break;
case FLOAT:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "floatValue";
break;
case DOUBLE:
boxType = ClassType.fromClass(Number.class);
unboxMethodName = "doubleValue";
break;
default:
throw new RuntimeException("should not reach here");
}
return Stream.of(
new VarInitStatement(
boxType.toType(),
boxVar,
new VarExpr(fromVar),
Span.dummySpan()),
new VarInitStatement(
toType,
toVar,
new InvokeExpr(
boxType,
fromVar,
unboxMethodName,
Collections.emptyList(),
Collections.emptyList(),
toType),
Span.dummySpan()));
},
nonPrimitiveType -> {
return Stream.of(
new VarInitStatement(
nonPrimitiveType,
toVar,
new VarExpr(fromVar),
Span.dummySpan()));
});
}
private Type typeOfExpr(yokohama.unit.ast.Expr expr) {
return expr.accept(
quotedExpr -> Type.OBJECT,
stubExpr -> Type.of(
stubExpr.getClassToStub().toType(), classResolver),
invocationExpr -> {
MethodPattern mp = invocationExpr.getMethodPattern();
return mp.getReturnType(
invocationExpr.getClassType(),
classResolver)
.map(type -> Type.of(type, classResolver))
.get();
},
integerExpr -> integerExpr.match(
intValue -> Type.INT,
longValue -> Type.LONG),
floatingPointExpr -> floatingPointExpr.match(
floatValue -> Type.FLOAT,
doubleValue -> Type.DOUBLE),
booleanExpr -> Type.BOOLEAN,
charExpr -> Type.CHAR,
stringExpr -> Type.STRING,
anchorExpr -> Type.STRING,
asExpr -> Type.of(asExpr.getClassType().toType(), classResolver),
resourceExpr ->
resourceExpr.getClassType()
.map(classType ->
Type.of(classType.toType(), classResolver))
.orElse(Type.URL));
}
List<List<Statement>> translateTableRef(
TableRef tableRef,
Sym envVar) {
String name = tableRef.getName();
List<Ident> idents = tableRef.getIdents();
try {
switch(tableRef.getType()) {
case INLINE:
return translateTable(tables.stream()
.filter(table -> table.getName().equals(name))
.findFirst()
.get(),
idents,
envVar);
case CSV:
return parseCSV(name, CSVFormat.DEFAULT.withHeader(), idents, envVar);
case TSV:
return parseCSV(name, CSVFormat.TDF.withHeader(), idents, envVar);
case EXCEL:
return parseExcel(name, idents, envVar);
}
throw new IllegalArgumentException(
"'" + Objects.toString(tableRef) + "' is not a table reference.");
} catch (InvalidFormatException | IOException e) {
throw new TranslationException(e.getMessage(), tableRef.getSpan(), e);
}
}
List<List<Statement>> translateTable(
Table table,
List<Ident> idents,
Sym envVar) {
return table.getRows()
.stream()
.map(row ->
translateRow(row, table.getHeader(), idents, envVar))
.collect(Collectors.toList());
}
List<Statement> translateRow(
Row row,
List<Ident> header,
List<Ident> idents,
Sym envVar) {
return IntStream.range(0, header.size())
.filter(i -> idents.contains(header.get(i)))
.mapToObj(Integer::new)
.flatMap(i -> {
Cell cell = row.getCells().get(i);
return cell.accept(exprCell -> {
Sym var = genSym.generate(header.get(i).getName());
return Stream.concat(translateExpr(exprCell.getExpr(), var, Object.class, envVar),
expressionStrategy.bind(envVar, header.get(i), var).stream());
},
predCell -> {
throw new TranslationException(
"Expected expression but found predicate",
predCell.getSpan());
});
})
.collect(Collectors.toList());
}
List<List<Statement>> parseCSV(
String fileName, CSVFormat format, List<Ident> idents, Sym envVar)
throws IOException {
Map<String, Ident> nameToIdent = idents.stream()
.collect(() -> new TreeMap<>(),
(map, ident) -> map.put(ident.getName(), ident),
(m1, m2) -> m1.putAll(m2));
try ( final InputStream in = getClass().getResourceAsStream(fileName);
final Reader reader = new InputStreamReader(in, "UTF-8");
final CSVParser parser = new CSVParser(reader, format)) {
return StreamSupport.stream(parser.spliterator(), false)
.map(record ->
parser.getHeaderMap().keySet()
.stream()
.filter(key -> idents.stream().anyMatch(ident -> ident.getName().equals(key)))
.map(key -> nameToIdent.get(key))
.flatMap(ident -> {
Sym var = genSym.generate(ident.getName());
return Stream.concat(expressionStrategy.eval(var,
new yokohama.unit.ast.QuotedExpr(
record.get(ident.getName()),
new yokohama.unit.position.Span(
Optional.of(Paths.get(fileName)),
new Position((int)parser.getCurrentLineNumber(), -1),
new Position(-1, -1))),
Object.class, envVar).stream(),
expressionStrategy.bind(envVar, ident, var).stream());
})
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}
List<List<Statement>> parseExcel(
String fileName, List<Ident> idents, Sym envVar)
throws InvalidFormatException, IOException {
Map<String, Ident> nameToIdent = idents.stream()
.collect(() -> new TreeMap<>(),
(map, ident) -> map.put(ident.getName(), ident),
(m1, m2) -> m1.putAll(m2));
try (InputStream in = getClass().getResourceAsStream(fileName)) {
final Workbook book = WorkbookFactory.create(in);
final Sheet sheet = book.getSheetAt(0);
final int top = sheet.getFirstRowNum();
final int left = sheet.getRow(top).getFirstCellNum();
List<String> names = StreamSupport.stream(sheet.getRow(top).spliterator(), false)
.map(cell -> cell.getStringCellValue())
.collect(Collectors.toList());
return StreamSupport.stream(sheet.spliterator(), false)
.skip(1)
.map(row ->
IntStream.range(0, names.size())
.filter(i -> idents.stream().anyMatch(ident -> ident.getName().equals(names.get(i))))
.mapToObj(Integer::new)
.flatMap(i -> {
Ident ident = nameToIdent.get(names.get(i));
Sym var = genSym.generate(names.get(i));
return Stream.concat(expressionStrategy.eval(var,
new yokohama.unit.ast.QuotedExpr(
row.getCell(left + i).getStringCellValue(),
new yokohama.unit.position.Span(
Optional.of(Paths.get(fileName)),
new Position(row.getRowNum() + 1, left + i + 1),
new Position(-1, -1))),
Object.class, envVar).stream(),
expressionStrategy.bind(envVar, ident, var).stream());
})
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}
List<Method> translateFourPhaseTest(FourPhaseTest fourPhaseTest) {
Sym env = genSym.generate("env");
Sym contractVar = genSym.generate("contract");
List<Statement> contract =
checkContract
? Arrays.asList(
new VarInitStatement(
Type.fromClass(Contract.class),
contractVar,
new NewExpr(
"yokohama.unit.contract.GroovyContract",
Collections.emptyList(),
Collections.emptyList()),
fourPhaseTest.getSpan()))
: Collections.emptyList();
List<Pair<List<Ident>, List<List<yokohama.unit.ast.Expr>>>> candidates =
Optionals.toStream(
fourPhaseTest
.getSetup()
.map(Phase::getLetStatements)
.map(List::stream))
.flatMap(x -> x)
.flatMap(choiceCollectVisitor::visitLetStatement)
.collect(Collectors.toList());
List<Map<Ident, yokohama.unit.ast.Expr>> choices = candidatesToChoices(candidates);
IntStream indexes = IntStream.range(0, choices.size());
return indexes.mapToObj(index -> {
Map<Ident, yokohama.unit.ast.Expr> choice = choices.get(index);
String testName = SUtils.toIdent(fourPhaseTest.getName()) + "_" + index;
final Stream<Statement> bindings;
final List<String> vars;
if (fourPhaseTest.getSetup().isPresent()) {
Phase setup = fourPhaseTest.getSetup().get();
bindings = setup.getLetStatements().stream()
.flatMap(letStatement ->
letStatement.getBindings().stream()
.flatMap(binding ->
checkContract
? translateBindingWithContract(binding, choice, env, contractVar)
: translateBinding(binding, choice, env)));
vars = setup.getLetStatements().stream()
.flatMap(s ->
s.getBindings().stream()
.flatMap(b -> b.accept(
singleBinding -> Stream.of(singleBinding.getName()),
choiceBinding -> Stream.of(choiceBinding.getName()),
tableBinding -> tableBinding.getIdents().stream())))
.map(Ident::getName)
.collect(Collectors.toList());
} else {
bindings = Stream.empty();
vars = Collections.emptyList();
}
Optional<Stream<Statement>> setupActions =
fourPhaseTest.getSetup()
.map(Phase::getStatements)
.map(statements -> translateStatements(statements, env));
Optional<Stream<Statement>> exerciseActions =
fourPhaseTest.getExercise()
.map(Phase::getStatements)
.map(statements -> translateStatements(statements, env));
Stream<Statement> testStatements =
fourPhaseTest.getVerify().getAssertions().stream()
.flatMap(assertion ->
translateAssertion(assertion, env)
.stream().flatMap(s -> s.stream()));
Stream<Statement> contractAfterExercise = checkContract
? vars.stream()
.flatMap(name -> {
Sym objVar = genSym.generate("obj");
return Stream.concat(
expressionStrategy.eval(
objVar,
new QuotedExpr(
name, Span.dummySpan()),
Object.class,
env).stream(),
insertContract(contractVar, objVar));
})
: Stream.empty();
List<Statement> statements =
Lists.fromStreams(
bindings,
setupActions.isPresent()
? setupActions.get()
: Stream.empty(),
exerciseActions.isPresent()
? exerciseActions.get()
: Stream.empty(),
contractAfterExercise,
testStatements);
List<Statement> actionsAfter;
if (fourPhaseTest.getTeardown().isPresent()) {
Phase teardown = fourPhaseTest.getTeardown().get();
actionsAfter =
translateStatements(teardown.getStatements(), env)
.collect(Collectors.toList());
} else {
actionsAfter = Arrays.asList();
}
return new Method(
Arrays.asList(annotationOf(TEST)),
testName,
Arrays.asList(),
Optional.empty(),
Arrays.asList(ClassType.EXCEPTION),
Lists.concat(
expressionStrategy.env(env),
contract,
actionsAfter.size() > 0
? Arrays.asList(
new TryStatement(
statements,
Arrays.asList(),
actionsAfter))
: statements));
}).collect(Collectors.toList());
}
Stream<Statement> translateStatements(
List<yokohama.unit.ast.Statement> statements, Sym envVar) {
return statements.stream()
.flatMap(statement -> statement.accept(execution -> translateExecution(execution, envVar),
invoke -> translateInvoke(invoke, envVar)));
}
Stream<Statement> translateExecution(
Execution execution, Sym envVar) {
Sym __ = genSym.generate("__");
return execution.getExpressions().stream()
.flatMap(expression ->
expressionStrategy.eval(__, expression, Object.class, envVar).stream());
}
Stream<Statement> translateInvoke(Invoke invoke, Sym envVar) {
yokohama.unit.ast.ClassType classType = invoke.getClassType();
Class<?> clazz = classType.toClass(classResolver);
MethodPattern methodPattern = invoke.getMethodPattern();
String methodName = methodPattern.getName();
List<yokohama.unit.ast.Type> argTypes = methodPattern.getParamTypes();
boolean isVararg = methodPattern.isVararg();
Optional<yokohama.unit.ast.Expr> receiver = invoke.getReceiver();
List<yokohama.unit.ast.Expr> args = invoke.getArgs();
Pair<List<Sym>, Stream<Statement>> argVarsAndStatements =
setupArgs(argTypes, isVararg, args, envVar);
List<Sym> argVars = argVarsAndStatements.getFirst();
Stream<Statement> setupStatements = argVarsAndStatements.getSecond();
Optional<Type> returnType = invoke.getMethodPattern()
.getReturnType(classType, classResolver)
.map(type -> Type.of(type, classResolver));
Stream<Statement> invocation;
if (returnType.isPresent()) {
invocation = generateInvoke(genSym.generate("__"),
classType,
methodName,
argTypes,
isVararg,
argVars,
receiver,
returnType.get(),
envVar,
invoke.getSpan());
} else {
invocation = generateInvokeVoid(classType,
methodName,
argTypes,
isVararg,
argVars,
receiver,
envVar,
invoke.getSpan());
}
return Stream.concat(setupStatements, invocation);
}
Pair<List<Sym>, Stream<Statement>> setupArgs(
List<yokohama.unit.ast.Type> argTypes,
boolean isVararg,
List<yokohama.unit.ast.Expr> args,
Sym envVar) {
List<Pair<Sym, Stream<Statement>>> setupArgs;
if (isVararg) {
int splitAt = argTypes.size() - 1;
List<Pair<yokohama.unit.ast.Type, List<yokohama.unit.ast.Expr>>> typesAndArgs =
Pair.zip(
argTypes,
Lists.split(args, splitAt).map((nonVarargs, varargs) ->
ListUtils.union(
Lists.map(nonVarargs, Arrays::asList),
Arrays.asList(varargs))));
setupArgs = Lists.mapInitAndLast(typesAndArgs,
typeAndArg -> typeAndArg.map((t, arg) -> {
Sym argVar = genSym.generate("arg");
Type paramType = Type.of(t, classResolver);
Stream<Statement> expr = translateExpr(arg.get(0), argVar, paramType.toClass(), envVar);
return Pair.of(argVar, expr);
}),
typeAndArg -> typeAndArg.map((t, varargs) -> {
Type paramType = Type.of(t, classResolver);
List<Pair<Sym, Stream<Statement>>> exprs = varargs.stream().map(vararg -> {
Sym varargVar = genSym.generate("vararg");
Stream<Statement> expr = translateExpr(vararg,
varargVar,
paramType.toClass(),
envVar);
return Pair.of(varargVar, expr);
}).collect(Collectors.toList());
List<Sym> varargVars = Pair.unzip(exprs).getFirst();
Stream<Statement> varargStatements = exprs.stream().flatMap(Pair::getSecond);
Sym argVar = genSym.generate("arg");
Stream<Statement> arrayStatement = Stream.of(
new VarInitStatement(
paramType.toArray(),
argVar,
new ArrayExpr(paramType.toArray(), varargVars),
t.getSpan()));
return Pair.of(argVar, Stream.concat(varargStatements, arrayStatement));
}));
} else {
List<Pair<yokohama.unit.ast.Type, yokohama.unit.ast.Expr>> pairs =
Pair.<yokohama.unit.ast.Type, yokohama.unit.ast.Expr>zip(
argTypes, args);
setupArgs = pairs.stream().map(pair -> pair.map((t, arg) -> {
// evaluate actual args and coerce to parameter types
Sym argVar = genSym.generate("arg");
Type paramType = Type.of(t, classResolver);
Stream<Statement> expr = translateExpr(arg, argVar, paramType.toClass(), envVar);
return Pair.of(argVar, expr);
})).collect(Collectors.toList());
}
List<Sym> argVars = Pair.unzip(setupArgs).getFirst();
Stream<Statement> setupStatements =
setupArgs.stream().flatMap(Pair::getSecond);
return Pair.of(argVars, setupStatements);
}
Stream<Statement> generateInvoke(
Sym var,
yokohama.unit.ast.ClassType classType,
String methodName,
List<yokohama.unit.ast.Type> argTypes,
boolean isVararg,
List<Sym> argVars,
Optional<yokohama.unit.ast.Expr> receiver,
Type returnType,
Sym envVar,
Span span) {
Class<?> clazz = classType.toClass(classResolver);
if (receiver.isPresent()) {
// invokevirtual
Sym receiverVar = genSym.generate("receiver");
Stream<Statement> getReceiver = translateExpr(receiver.get(), receiverVar, clazz, envVar);
return Stream.concat(getReceiver, Stream.of(new VarInitStatement(
returnType,
var,
new InvokeExpr(
ClassType.of(classType, classResolver),
receiverVar,
methodName,
Lists.mapInitAndLast(
Type.listOf(argTypes, classResolver),
type -> type,
type -> isVararg ? type.toArray(): type),
argVars,
returnType),
span)));
} else {
// invokestatic
return Stream.of(new VarInitStatement(
returnType,
var,
new InvokeStaticExpr(
ClassType.of(classType, classResolver),
Collections.emptyList(),
methodName,
Lists.mapInitAndLast(
Type.listOf(argTypes, classResolver),
type -> type,
type -> isVararg ? type.toArray(): type),
argVars,
returnType),
span));
}
}
Stream<Statement> generateInvokeVoid(
yokohama.unit.ast.ClassType classType,
String methodName,
List<yokohama.unit.ast.Type> argTypes,
boolean isVararg,
List<Sym> argVars,
Optional<yokohama.unit.ast.Expr> receiver,
Sym envVar,
Span span) {
Class<?> clazz = classType.toClass(classResolver);
if (receiver.isPresent()) {
// invokevirtual
Sym receiverVar = genSym.generate("receiver");
Stream<Statement> getReceiver = translateExpr(receiver.get(), receiverVar, clazz, envVar);
return Stream.concat(getReceiver, Stream.of(
new InvokeVoidStatement(
ClassType.of(classType, classResolver),
receiverVar,
methodName,
Lists.mapInitAndLast(
Type.listOf(argTypes, classResolver),
type -> type,
type -> isVararg ? type.toArray(): type),
argVars,
span)));
} else {
// invokestatic
return Stream.of(
new InvokeStaticVoidStatement(
ClassType.of(classType, classResolver),
Collections.emptyList(),
methodName,
Lists.mapInitAndLast(
Type.listOf(argTypes, classResolver),
type -> type,
type -> isVararg ? type.toArray(): type),
argVars,
span));
}
}
}
@RequiredArgsConstructor
class StreamCollector<T> {
@Getter final Stream<T> stream;
StreamCollector<T> append(Stream<T> stream_) {
return new StreamCollector<>(Stream.concat(stream, stream_));
}
StreamCollector<T> append(List<T> list) {
return new StreamCollector<>(Stream.concat(stream, list.stream()));
}
StreamCollector<T> append(T element) {
return new StreamCollector<>(Stream.concat(stream, Stream.of(element)));
}
public static <T> StreamCollector<T> empty() {
return new StreamCollector<>(Stream.empty());
}
} |
package com.cedarsoftware.ncube;
import org.junit.Test;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class TestJsonFormatter {
@Test
public void testJsonFormatter() throws Exception {
// when running a single test.
//List<String> s = new ArrayList<String>();
//s.add("testEmptyColumnList.json");
List<String> s = getAllTestFiles();
runAllTests(s);
}
public List<String> getAllTestFiles()
{
URL u = getClass().getClassLoader().getResource("");
File dir = new File(u.getFile());
File[] files = dir.listFiles(new FilenameFilter()
{
// The *CubeError.json are files that have intentional parsing errors
// testCubeList.json is an array of cubes and JsonFormatter only knows aboue one cube at a time.
public boolean accept(File f, String s)
{
return s != null && s.endsWith(".json") &&
!(s.endsWith("idBasedCubeError.json") ||
s.endsWith("idBasedCubeError2.json") ||
s.endsWith("testCubeList.json"));
}
});
List<String> names = new ArrayList<String>(files.length);
for (File f : files) {
names.add(f.getName());
}
return names;
}
public void runAllTests(List<String> strings)
{
for (String f : strings)
{
//System.out.println("Starting " + f);
NCube ncube = NCubeManager.getNCubeFromResource(f);
String s = ncube.toFormattedJson();
//System.out.println(s);
NCube res = NCube.fromSimpleJson(s);
assertEquals(res, ncube);
}
}
} |
package org.traccar.protocol;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
public class TotemProtocolDecoderTest {
@Test
public void testDecode() throws Exception {
TotemProtocolDecoder decoder = new TotemProtocolDecoder(null);
decoder.setDataManager(new TestDataManager());
assertNull(decoder.decode(null, null,
"$$BB862170017856731|AA$GPRMC,000000.00,V,0000.0000,N,00000.0000,E,000.0,000.0,000000,,,A*73|00.0|00.0|00.0|000000001000|20000000000000|13790000|00000000|00000000|00000000|0.0000|0007|8C23"));
assertNotNull(decoder.decode(null, null,
"$$B2359772032984289|AA$GPRMC,104446.000,A,5011.3944,N,01439.6637,E,0.00,,290212,,,A*7D|01.8|00.9|01.5|000000100000|20120229104446|14151221|00050000|046D085E|0000|0.0000|1170|29A7"));
assertNotNull(decoder.decode(null, null,
"$$8B862170017861566|AA180613080657|A|2237.1901|N|11402.1369|E|1.579|178|8.70|100000001000|13811|00000000|253162F5|00000000|0.0000|0014|2B16"));
}
} |
package org.xwalk.core;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.FrameLayout;
import org.xwalk.core.client.XWalkDefaultClient;
import org.xwalk.core.client.XWalkDefaultDownloadListener;
import org.xwalk.core.client.XWalkDefaultNavigationHandler;
import org.xwalk.core.client.XWalkDefaultWebChromeClient;
public class XWalkView extends FrameLayout {
private XWalkContent mContent;
private XWalkDevToolsServer mDevToolsServer;
private Activity mActivity;
private Context mContext;
public XWalkView(Context context, Activity activity) {
super(context, null);
// Make sure mActivity is initialized before calling 'init' method.
mActivity = activity;
mContext = context;
init(context, null);
}
public Activity getActivity() {
if (mActivity != null) {
return mActivity;
} else if (getContext() instanceof Activity) {
return (Activity)getContext();
}
// Never achieve here.
assert(false);
return null;
}
public Context getViewContext() {
return mContext;
}
/**
* Constructors for inflating via XML.
*/
public XWalkView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
// Intialize library, paks and others.
XWalkViewDelegate.init(context);
initXWalkContent(context, attrs);
}
private void initXWalkContent(Context context, AttributeSet attrs) {
mContent = new XWalkContent(context, attrs, this);
addView(mContent,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// Set default XWalkDefaultClient.
setXWalkClient(new XWalkDefaultClient(context, this));
// Set default XWalkWebChromeClient and DownloadListener. The default actions
// are provided via the following clients if special actions are not needed.
setXWalkWebChromeClient(new XWalkDefaultWebChromeClient(context, this));
setDownloadListener(new XWalkDefaultDownloadListener(context));
setNavigationHandler(new XWalkDefaultNavigationHandler(context));
}
public void loadUrl(String url) {
mContent.loadUrl(url);
}
public void reload() {
mContent.reload();
}
public void addJavascriptInterface(Object object, String name) {
mContent.addJavascriptInterface(object, name);
}
public String getUrl() {
return mContent.getUrl();
}
public String getTitle() {
return mContent.getTitle();
}
public void clearCache(boolean includeDiskFiles) {
mContent.clearCache(includeDiskFiles);
}
public void clearHistory() {
mContent.clearHistory();
}
public boolean canGoBack() {
return mContent.canGoBack();
}
public void goBack() {
mContent.goBack();
}
public boolean canGoForward() {
return mContent.canGoForward();
}
public void goForward() {
mContent.goForward();
}
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
return false;
}
public void setLayoutParams(ViewGroup.LayoutParams params) {
super.setLayoutParams(params);
}
public XWalkSettings getSettings() {
return mContent.getSettings();
}
public String getOriginalUrl() {
return mContent.getOriginalUrl();
}
public void setNetworkAvailable(boolean networkUp) {
}
public void setInitialScale(int scaleInPercent) {
}
public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
mContent.setXWalkWebChromeClient(client);
}
public void setXWalkClient(XWalkClient client) {
mContent.setXWalkClient(client);
}
public void stopLoading() {
mContent.stopLoading();
}
public void pauseTimers() {
mContent.pauseTimers();
}
public void resumeTimers() {
mContent.resumeTimers();
}
public void setDownloadListener(DownloadListener listener) {
mContent.setDownloadListener(listener);
}
public void setNavigationHandler(XWalkNavigationHandler handler) {
mContent.setNavigationHandler(handler);
}
// Enables remote debugging and returns the URL at which the dev tools server is listening
// for commands.
public String enableRemoteDebugging() {
// Chrome looks for "devtools_remote" pattern in the name of a unix domain socket
// to identify a debugging page
final String socketName = getContext().getApplicationContext().getPackageName() + "_devtools_remote";
if (mDevToolsServer == null) {
mDevToolsServer = new XWalkDevToolsServer(socketName);
mDevToolsServer.setRemoteDebuggingEnabled(true);
}
// devtools/page is hardcoded in devtools_http_handler_impl.cc (kPageUrlPrefix)
return "ws://" + socketName + "/devtools/page/" + mContent.devToolsAgentId();
}
public void disableRemoteDebugging() {
if (mDevToolsServer == null) return;
if (mDevToolsServer.isRemoteDebuggingEnabled()) {
mDevToolsServer.setRemoteDebuggingEnabled(false);
}
mDevToolsServer.destroy();
mDevToolsServer = null;
}
public void onPause() {
mContent.onPause();
}
public void onResume() {
mContent.onResume();
}
public void onDestroy() {
disableRemoteDebugging();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mContent.onActivityResult(requestCode, resultCode, data);
}
public String getVersion() {
return mContent.getVersion();
}
// TODO(shouqun): requestFocusFromTouch, setVerticalScrollBarEnabled are
// from android.view.View;
// For instrumentation test.
public XWalkContent getXWalkViewContentForTest() {
return mContent;
}
} |
package eco;
public class popMethods {
//public static int[] unfilledpops = new int[1000];
public static void scanPops(){
// System.out.println("efa");
int x = 0;
int y = 0;
while(Main.popArray.length > x){
if((Main.popArray[x].people < 100)&& (Main.popArray[x].isUsed == true )){
y= 100- Main.popArray[x].people;
Main.unfilledpops[x] = y;
// System.out.println(Main.popArray[x].isFarmer);
// System.out.println(y);
//System.out.println("Wdfe");
}
x++;
}
}
public static void unusedAcresFarmersAssignment(){
int x = 0;
int y = 0;
//int[][] unemployedfarmersArray = new int[1000][200];// put this is in main
// System.out.println(x);
while((Main.popArray.length > x) && (Main.unusedacres > 5)){
if((Main.popArray[x].acres < 500) && (Main.popArray[x].isFarmer == true) /*&& (Main.popArray[x].people*5 > acres/5)*/ && Main.popArray[x].isUsed == true ){
if(Main.unusedacres < 500){
y = Main.unusedacres;
Main.unusedacres = 0;
}
else {
y = 500;
Main.unusedacres = Main.unusedacres - 500;
}
Main.popArray[x].acres = Main.popArray[x].acres + y;
y = 0;
//System.out.println("fsdf");
}
x++;
// System.out.println(x);
}
// System.out.println("efsf");
}
public static void popAssigner(){
int x = 0;
int y = 0;
while(Main.popArray.length > x){
if((Main.popArray[x].people < 100)&&(Main.unusedpops > 0) && (Main.popArray[x].isUsed == true)) {
//System.out.println("Kek");
y = Main.unfilledpops[x];
if(Main.unusedpops < y){
// System.out.println("Tres");
Main.popArray[x].people = Main.popArray[x].people + Main.unusedpops;
Main.unusedpops = 0;
}
else {
Main.unusedpops = Main.unusedpops - y;
Main.popArray[x].people = Main.popArray[x].people + y;}
Main.unfilledpops[x] = 0;
y = 0;
}
x++;
}
}
public static int farmertotal(){
int x = 0;
int y = 0;
while(Main.popArray.length > x) {
if(Main.popArray[x].isFarmer == true) {
y = y +Main.popArray[x].people;
// System.out.println("kejk" +y);
}
x++;
}
return y;
}
public static int warriortotal() {
int x = 0;
int y = 0;
while(Main.popArray.length > x) {
if(Main.popArray[x].isWarrior == true) {
y = y + Main.popArray[x].people;
}
x++;
}
return y;
}
public static int unemployedFarmerspops() {
int x = 0;
int y = 0;
while(Main.popArray.length > x) {
y = y +Main.popArray[x].unemployedfarmers;
x++;
}
return y;
}
public static int employedFarmerspops() {
int x = 0;
int y = 0;
while(Main.popArray.length > x){
y = y +Main.popArray[x].employedfarmers;
x++;
}
return y;
}
public static int usedacres() {
int x = 0;
int y = 0;
while(Main.popArray.length > x){
y = y +Main.popArray[x].acres;
x++;
}
return y;
}
public static void consumecyclewarrior() {
//food
int x = 0;
int y = 0;
int p = 0;
while(Main.popArray.length > x) {
if(Main.popArray[x].isWarrior == true){
y = Warrior.wHunger(Main.popArray[x].people);
Main.popArray[x].groupmoney = Main.popArray[x].groupmoney + (Main.wheatPrice*100);
Main.uneatenwheat = Main.uneatenwheat - y;
}
x++;
}
}
public static void farmerconsumecycle() {
int x = 0;
int y =0;
int k = 0;
int r = 0;
int w = 0;
int h = 0;
int m =0;
// System.out.println("here1");
while(Main.popArray.length > x){
if(Main.popArray[x].isFarmer == true){
y = Wheat.farmPacks(Main.popArray[x].acres);
k = Wheat.unemployedFarmers(y, Main.popArray[x].people);
r = Wheat.employedFarmers(Main.popArray[x].people,k);
w = Wheat.tWheat(r);
h = Farmer.fHunger(Main.popArray[x].people);
m = Farmer.checkStarvation(h, w);
if( m > 0){
w = 0;
h = 0;
Main.popArray[x].people = Main.popArray[x].people - m;
}
Main.uneatenwheat = Main.uneatenwheat + (w-h);
Main.popArray[x].groupmoney = Main.popArray[x].groupmoney + (Main.wheatPrice*w);
// System.out.println(Main.popArray[x].groupmoney+ "kel");
}
x++;
}
}
public static void popBuilder(int prefrence){
boolean iscomplete = false;
int x = 0;
int y = 0;
int l = Main.unusedacres;
int m = 0;
int r = 0;
boolean k = false;
switch(prefrence){
case 1:
while(Main.unusedpops > 0){
while(iscomplete == false){
// System.out.println("eke");
if(Main.unusedpops < 100){
r= Main.unusedpops;
// System.out.println("yell");
}
if(Main.unusedpops >= 100){
r = 100;
}
if(Main.unusedpops == 0){
iscomplete = true;
}
if(Main.unusedacres < 500){
m= Main.unusedacres;
// Main.unusedacres = Main.unusedacres - m;
}
if(Main.unusedacres >= 500){
m = 500;
// Main.unusedacres = 0;
}
Main.unusedacres = Main.unusedacres - m;
Main.unusedpops = Main.unusedpops - r;
Main.popArray[Main.unusedarray].isUsed = true;
Main.popArray[Main.unusedarray].isFarmer = true;
Main.popArray[Main.unusedarray].acres = m;
Main.popArray[Main.unusedarray].people = r;
Main.popArray[Main.unusedarray].groupmoney = 100;
m = 0;
r = 0;
Main.unusedarray++;
x++;
if(x == 2){
iscomplete = true;
// System.out.println(iscomplete);
}
//iscomplete =false;
// x =0;
}
iscomplete =false;
x =0;
while(iscomplete == false){
// System.out.println("eke2");
if(Main.unusedpops < 100){
r= Main.unusedpops;
// Main.unusedpops; =
}
if(Main.unusedpops >= 100){
r = 100;
}
if(Main.unusedpops == 0){
iscomplete = true;
}
Main.unusedpops = Main.unusedpops - r;
Main.popArray[Main.unusedarray].isUsed = true;
Main.popArray[Main.unusedarray].isWarrior = true;
Main.popArray[Main.unusedarray].people = r;
Main.popArray[Main.unusedarray].groupmoney = 100000;
Main.unusedarray++;
r =0;
x++;
if(x == 1){
iscomplete = true;
}
}
}
break;
}
}
} |
package com.clxcommunications.xms;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.theInstance;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.ContentType;
import org.junit.Rule;
import org.junit.Test;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneOffset;
import com.clxcommunications.testsupport.TestUtils;
import com.clxcommunications.xms.api.ApiError;
import com.clxcommunications.xms.api.BatchId;
import com.clxcommunications.xms.api.MtBatchBinarySmsResult;
import com.clxcommunications.xms.api.MtBatchBinarySmsResultImpl;
import com.clxcommunications.xms.api.MtBatchBinarySmsUpdate;
import com.clxcommunications.xms.api.MtBatchSmsResult;
import com.clxcommunications.xms.api.MtBatchTextSmsCreate;
import com.clxcommunications.xms.api.MtBatchTextSmsResult;
import com.clxcommunications.xms.api.MtBatchTextSmsResultImpl;
import com.clxcommunications.xms.api.MtBatchTextSmsUpdate;
import com.clxcommunications.xms.api.Page;
import com.clxcommunications.xms.api.PagedBatchResultImpl;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import uk.org.lidalia.slf4jtest.TestLoggerFactoryResetRule;
public class ApiConnectionIT {
/**
* A convenient {@link FutureCallback} for use in tests. By default all
* callback methods will call {@link #fail(String)}. Override the one that
* should succeed.
*
* @param <T>
* the callback result type
*/
private static class TestCallback<T> implements FutureCallback<T> {
@Override
public void failed(Exception e) {
fail("API call unexpectedly failed with '" + e.getMessage() + "'");
}
@Override
public void completed(T result) {
fail("API call unexpectedly completed with '" + result + "'");
}
@Override
public void cancelled() {
fail("API call unexpectedly cancelled");
}
}
private final ApiObjectMapper json = new ApiObjectMapper();
@Rule
public WireMockRule wm = new WireMockRule(
WireMockConfiguration.options()
.dynamicPort()
.dynamicHttpsPort());
@Rule
public TestLoggerFactoryResetRule testLoggerFactoryResetRule =
new TestLoggerFactoryResetRule();
@Test
public void canPostSimpleBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
MtBatchTextSmsCreate sms =
ClxApi.buildBatchTextSms()
.from("12345")
.addTo("123456789")
.addTo("987654321")
.body("Hello, world!")
.build();
MtBatchTextSmsResult expectedResponse =
MtBatchTextSmsResultImpl.builder()
.from(sms.from())
.to(sms.to())
.body(sms.body())
.canceled(false)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String path = "/xms/v1/" + username + "/batches";
stubPostResponse(expectedResponse, path);
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
MtBatchTextSmsResult result = conn.sendBatch(sms);
assertThat(result, is(expectedResponse));
} finally {
conn.close();
}
verifyPostRequest(path, sms);
}
@Test
public void canPostBatchWithSubstitutions() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
MtBatchTextSmsCreate sms =
ClxApi.buildBatchTextSms()
.from("12345")
.addTo("123456789")
.addTo("987654321")
.body("Hello, ${name}!")
.putParameter("name",
ClxApi.buildSubstitution()
.putSubstitution("123456789", "Jane")
.defaultValue("world")
.build())
.build();
MtBatchTextSmsResult expectedResponse =
MtBatchTextSmsResultImpl.builder()
.from(sms.from())
.to(sms.to())
.body(sms.body())
.parameters(sms.parameters())
.canceled(false)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String path = "/xms/v1/" + username + "/batches";
stubPostResponse(expectedResponse, path);
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
MtBatchTextSmsResult result = conn.sendBatch(sms);
assertThat(result, is(expectedResponse));
} finally {
conn.close();
}
verifyPostRequest(path, sms);
}
@Test(expected = ApiException.class)
public void canHandleBatchPostWithError() throws Throwable {
String username = TestUtils.freshUsername();
MtBatchTextSmsCreate sms =
ClxApi.buildBatchTextSms()
.from("12345")
.addTo("123456789")
.addTo("987654321")
.body("Hello, world!")
.build();
ApiError apiError = ApiError.of("syntax_constraint_violation",
"The syntax constraint was violated");
String response = json.writeValueAsString(apiError);
String path = "/xms/v1/" + username + "/batches";
wm.stubFor(post(urlEqualTo(path))
.willReturn(aResponse()
.withStatus(400)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
conn.sendBatch(sms);
fail("Expected exception, got none");
} catch (ApiException e) {
assertThat(e.getCode(), is(apiError.code()));
assertThat(e.getText(), is(apiError.text()));
throw e;
} finally {
conn.close();
}
}
@Test(expected = JsonParseException.class)
public void canHandleBatchPostWithInvalidJson() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
MtBatchTextSmsCreate sms =
ClxApi.buildBatchTextSms()
.from("12345")
.addTo("123456789")
.addTo("987654321")
.body("Hello, world!")
.build();
String response = String.join("\n",
"{",
" 'to': [",
" '123456789',",
" '987654321'",
" ],",
" 'body': 'Hello, world!',",
" 'type' 'mt_text',",
" 'canceled': false,",
" 'id': '" + batchId.id() + "',",
" 'from': '12345',",
" 'created_at': '2016-10-02T09:34:28.542Z',",
" 'modified_at': '2016-10-02T09:34:28.542Z'",
"}").replace('\'', '"');
String path = "/xms/v1/" + username + "/batches";
wm.stubFor(post(urlEqualTo(path))
.willReturn(aResponse()
.withStatus(400)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
conn.sendBatch(sms);
fail("Expected exception, got none");
} finally {
conn.close();
}
}
@Test
public void canUpdateSimpleTextBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
MtBatchTextSmsUpdate sms =
ClxApi.buildBatchTextSmsUpdate()
.from("12345")
.body("Hello, world!")
.unsetDeliveryReport()
.unsetExpireAt()
.build();
MtBatchTextSmsResult expectedResponse =
MtBatchTextSmsResultImpl.builder()
.from(sms.from())
.addTo("123")
.body(sms.body())
.canceled(false)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String path = "/xms/v1/" + username + "/batches/" + batchId.id();
stubPostResponse(expectedResponse, path);
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
MtBatchTextSmsResult result =
conn.updateBatchAsync(batchId, sms, null).get();
assertThat(result, is(expectedResponse));
} finally {
conn.close();
}
verifyPostRequest(path, sms);
}
@Test
public void canUpdateSimpleBinaryBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
Set<String> tags = new TreeSet<String>();
tags.add("tag1");
tags.add("tag2");
MtBatchBinarySmsUpdate sms =
ClxApi.buildBatchBinarySmsUpdate()
.from("12345")
.body("howdy".getBytes(TestUtils.US_ASCII))
.unsetExpireAt()
.build();
MtBatchBinarySmsResult expectedResponse =
MtBatchBinarySmsResultImpl.builder()
.from(sms.from())
.addTo("123")
.body(sms.body())
.udh((byte) 1, (byte) 0xff)
.canceled(false)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String path = "/xms/v1/" + username + "/batches/" + batchId.id();
stubPostResponse(expectedResponse, path);
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("toktok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
MtBatchBinarySmsResult result =
conn.updateBatchAsync(batchId, sms, null).get();
assertThat(result, is(expectedResponse));
} finally {
conn.close();
}
verifyPostRequest(path, sms);
}
@Test
public void canFetchBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
String path = "/xms/v1/" + username + "/batches/" + batchId.id();
final MtBatchTextSmsResult expected =
MtBatchTextSmsResultImpl.builder()
.from("12345")
.addTo("123456789", "987654321")
.body("Hello, world!")
.canceled(false)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String response = json.writeValueAsString(expected);
wm.stubFor(get(
urlEqualTo(path))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("tok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
FutureCallback<MtBatchTextSmsResult> testCallback =
new TestCallback<MtBatchTextSmsResult>() {
@Override
public void completed(MtBatchTextSmsResult result) {
assertThat(result, is(expected));
}
};
MtBatchTextSmsResult result =
conn.fetchBatch(batchId, testCallback).get();
assertThat(result, is(expected));
} finally {
conn.close();
}
wm.verify(getRequestedFor(
urlEqualTo(path))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
}
@Test
public void canHandle404WhenFetchingBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
String path = "/xms/v1/" + username + "/batches/" + batchId.id();
wm.stubFor(get(
urlEqualTo(path))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type",
ContentType.TEXT_PLAIN.toString())
.withBody("BAD")));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("tok")
.endpointHost("localhost", wm.port(), "http")
.start();
/*
* The exception we'll receive in the callback. Need to store it to
* verify that it is the same exception as received from #get().
*/
final AtomicReference<Exception> failException =
new AtomicReference<Exception>();
try {
/*
* Used to make sure callback and test thread are agreeing about the
* failException variable.
*/
final CyclicBarrier barrier = new CyclicBarrier(2);
FutureCallback<MtBatchTextSmsResult> testCallback =
new TestCallback<MtBatchTextSmsResult>() {
@Override
public void failed(Exception exception) {
if (!failException.compareAndSet(null,
exception)) {
fail("failed called multiple times");
}
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
Future<MtBatchTextSmsResult> future =
conn.fetchBatch(batchId, testCallback);
// Give plenty of time for the callback to be called.
barrier.await(1, TimeUnit.SECONDS);
future.get();
fail("unexpected future get success");
} catch (ExecutionException executionException) {
/*
* The exception cause should be the same as we received in the
* callback.
*/
assertThat(failException.get(),
is(theInstance(executionException.getCause())));
assertThat(executionException.getCause(),
is(instanceOf(UnexpectedResponseException.class)));
UnexpectedResponseException ure =
(UnexpectedResponseException) executionException.getCause();
assertThat(ure.getResponse(), notNullValue());
assertThat(ure.getResponse().getStatusLine()
.getStatusCode(), is(404));
assertThat(
ure.getResponse().getEntity().getContentType().getValue(),
is(ContentType.TEXT_PLAIN.toString()));
byte[] buf = new byte[100];
int read;
InputStream contentStream = null;
try {
contentStream = ure.getResponse().getEntity().getContent();
read = contentStream.read(buf);
} catch (IOException ioe) {
throw new AssertionError(
"unexpected exception: "
+ ioe.getMessage(),
ioe);
} finally {
if (contentStream != null) {
try {
contentStream.close();
} catch (IOException ioe) {
throw new AssertionError(
"unexpected exception: " + ioe.getMessage(),
ioe);
}
}
}
assertThat(read, is(3));
assertThat(Arrays.copyOf(buf, 3),
is(new byte[] { 'B', 'A', 'D' }));
} finally {
conn.close();
}
wm.verify(getRequestedFor(
urlEqualTo(path))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
}
@Test
public void canCancelBatch() throws Throwable {
String username = TestUtils.freshUsername();
BatchId batchId = TestUtils.freshBatchId();
OffsetDateTime smsTime = OffsetDateTime.of(2016, 10, 2, 9, 34, 28,
542000000, ZoneOffset.UTC);
String path = "/xms/v1/" + username + "/batches/" + batchId.id();
MtBatchTextSmsResult expected =
MtBatchTextSmsResultImpl.builder()
.from("12345")
.addTo("123456789", "987654321")
.body("Hello, world!")
.canceled(true)
.id(batchId)
.createdAt(smsTime)
.modifiedAt(smsTime)
.build();
String response = json.writeValueAsString(expected);
wm.stubFor(delete(
urlEqualTo(path))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("tok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
MtBatchTextSmsResult result = conn.cancelBatch(batchId).get();
assertThat(result, is(expected));
} finally {
conn.close();
}
wm.verify(deleteRequestedFor(
urlEqualTo(path))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
}
@Test
public void canListBatchesWithEmpty() throws Exception {
String username = TestUtils.freshUsername();
String path = "/xms/v1/" + username + "/batches?page=0";
BatchFilter filter = BatchFilterImpl.builder().build();
final Page<MtBatchSmsResult> expected =
PagedBatchResultImpl.builder()
.page(0)
.size(0)
.numPages(0)
.build();
String response = json.writeValueAsString(expected);
wm.stubFor(get(
urlEqualTo(path))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("tok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
FutureCallback<Page<MtBatchSmsResult>> testCallback =
new TestCallback<Page<MtBatchSmsResult>>() {
@Override
public void completed(Page<MtBatchSmsResult> result) {
assertThat(result, is(expected));
}
};
PagedFetcher<MtBatchSmsResult> fetcher =
conn.fetchBatches(filter, testCallback);
Page<MtBatchSmsResult> result =
fetcher.fetchAsync(0, testCallback).get();
assertThat(result, is(expected));
} finally {
conn.close();
}
wm.verify(getRequestedFor(
urlEqualTo(path))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
}
@Test
public void canListBatchesWithTwoPages() throws Exception {
String username = TestUtils.freshUsername();
BatchFilter filter = BatchFilterImpl.builder().build();
// Prepare first page.
String path1 = "/xms/v1/" + username + "/batches?page=0";
final Page<MtBatchSmsResult> expected1 =
PagedBatchResultImpl.builder()
.page(0)
.size(0)
.numPages(2)
.build();
String response1 = json.writeValueAsString(expected1);
wm.stubFor(get(
urlEqualTo(path1))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response1)));
// Prepare second page.
String path2 = "/xms/v1/" + username + "/batches?page=1";
final Page<MtBatchSmsResult> expected2 =
PagedBatchResultImpl.builder()
.page(1)
.size(0)
.numPages(2)
.build();
String response2 = json.writeValueAsString(expected2);
wm.stubFor(get(
urlEqualTo(path2))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(response2)));
ApiConnection conn = ApiConnection.builder()
.username(username)
.token("tok")
.endpointHost("localhost", wm.port(), "http")
.start();
try {
FutureCallback<Page<MtBatchSmsResult>> testCallback =
new TestCallback<Page<MtBatchSmsResult>>() {
@Override
public void completed(Page<MtBatchSmsResult> result) {
switch (result.page()) {
case 0:
assertThat(result, is(expected1));
break;
case 1:
assertThat(result, is(expected2));
break;
default:
fail("unexpected page: " + result);
}
}
};
PagedFetcher<MtBatchSmsResult> fetcher =
conn.fetchBatches(filter, testCallback);
Page<MtBatchSmsResult> actual1 =
fetcher.fetchAsync(0, testCallback).get();
assertThat(actual1, is(expected1));
Page<MtBatchSmsResult> actual2 =
fetcher.fetchAsync(1, testCallback).get();
assertThat(actual2, is(expected2));
} finally {
conn.close();
}
wm.verify(getRequestedFor(
urlEqualTo(path1))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
wm.verify(getRequestedFor(
urlEqualTo(path2))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer tok")));
}
/**
* Helper that sets up WireMock to respond using a JSON body.
*
* @param response
* the response to give, serialized to JSON
* @param path
* the path on which to listen
* @throws JsonProcessingException
* if the given response object could not be serialized
*/
private void stubPostResponse(Object response, String path)
throws JsonProcessingException {
byte[] body = json.writeValueAsBytes(response);
wm.stubFor(post(urlEqualTo(path))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type",
"application/json; charset=UTF-8")
.withBody(body)));
}
/**
* Helper that sets up WireMock to verify that a request matches a given
* object in JSON format.
*
* @param path
* the request path to match
* @param request
* the request object whose JSON serialization should match
* @throws JsonProcessingException
* if the given request object could not be serialized
*/
private void verifyPostRequest(String path, Object request)
throws JsonProcessingException {
String expectedRequest = json.writeValueAsString(request);
wm.verify(postRequestedFor(
urlEqualTo(path))
.withRequestBody(equalToJson(expectedRequest))
.withHeader("Content-Type",
matching("application/json; charset=UTF-8"))
.withHeader("Accept",
equalTo("application/json; charset=UTF-8"))
.withHeader("Authorization", equalTo("Bearer toktok")));
}
} |
package com.github.arteam.jgcompare;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class IterablesTest {
Iterable<String> source = Lists.newArrayList("as", "q", "def");
Stream<String> stream = Stream.of("as", "q", "def");
@Test
public void testAll() {
assertThat(Iterables.all(source, it -> !it.isEmpty())).isTrue();
assertThat(stream.allMatch(it -> !it.isEmpty())).isTrue();
}
@Test
public void testAny() {
assertThat(Iterables.any(source, it -> it.length() > 2)).isTrue();
assertThat(stream.anyMatch(it -> it.length() > 2)).isTrue();
}
@Test
public void testConcat() {
List<String> addition = ImmutableList.of("ger", "d", "fm");
List<String> result = ImmutableList.of("as", "q", "def", "ger", "d", "fm");
assertThat(ImmutableList.copyOf(Iterables.concat(source, addition))).isEqualTo(result);
assertThat(Stream.concat(stream, addition.stream()).collect(Collectors.toList())).isEqualTo(result);
}
@Test
public void testContains() {
assertThat(Iterables.contains(source, "q")).isTrue();
assertThat(stream.anyMatch(s -> s.equals("q"))).isTrue();
}
@Test
public void testCycle() {
ImmutableList<String> expected = ImmutableList.of("as", "q", "def", "as", "q", "def", "as", "q", "def", "as");
Iterator<String> iterator = Iterables.cycle(source).iterator();
List<String> cycled = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
cycled.add(iterator.next());
}
assertThat(expected).isEqualTo(cycled);
String[] streamAsArray = stream.toArray(String[]::new);
assertThat(expected).isEqualTo(IntStream.iterate(0, i -> (i + 1) % 3)
.mapToObj(i -> streamAsArray[i])
.limit(10)
.collect(Collectors.toList()));
}
@Test
public void testFilter() {
Iterable<String> result = Iterables.filter(Iterables.filter(source, s -> s.length() > 1),
s -> s.startsWith("d"));
assertThat(ImmutableList.copyOf(result)).isEqualTo(ImmutableList.of("def"));
assertThat(stream
.filter(s -> s.length() > 1)
.filter(s -> s.startsWith("d"))
.collect(Collectors.toList())).isEqualTo(ImmutableList.of("def"));
}
@Test
public void testFind() {
assertThat(Iterables.find(source, it -> it.length() == 1)).isEqualTo("q");
assertThat(stream.filter(it -> it.length() == 1).findAny().get()).isEqualTo("q");
}
@Test
public void testFindDefaultValue() {
assertThat(Iterables.find(source, it -> it.length() == 4, "abcd")).isEqualTo("abcd");
assertThat(stream.filter(it -> it.length() == 4).findAny().orElse("abcd")).isEqualTo("abcd");
}
@Test
public void testFrequency() {
List<String> source = ImmutableList.<String>builder()
.addAll(this.source)
.add("def")
.add("try")
.add("q")
.add("def")
.build();
Stream<String> stream = source.stream();
assertThat(Iterables.frequency(source, "def")).isEqualTo(3);
assertThat(stream
.filter(s -> s.equals("def"))
.count()).isEqualTo(3);
}
@Test
public void testGetFirst() {
assertThat(Iterables.getFirst(source, "")).isEqualTo("as");
assertThat(stream.findFirst().orElse("")).isEqualTo("as");
}
@Test
public void testGetLast() {
assertThat(Iterables.getLast(source, "")).isEqualTo("def");
assertThat(stream.reduce((l, r) -> r).get()).isEqualTo("def");
}
@Test
public void testGetOnlyElement() {
assertThat(Iterables.getOnlyElement(Iterables.filter(source, s -> s.length() == 3))).isEqualTo("def");
assertThat(stream.filter(s -> s.length() == 3).findFirst().get()).isEqualTo("def");
}
@Test
public void testGetOnlyElementWithDefault() {
assertThat(Iterables.getOnlyElement(Iterables.filter(source, s -> s.length() == 4), "mann")).isEqualTo("mann");
assertThat(stream.filter(s -> s.length() == 4).findFirst().orElse("mann")).isEqualTo("mann");
}
@Test
public void testIndexOf() {
assertThat(Iterables.indexOf(source, it -> it.length() == 1)).isEqualTo(1);
// Rather tricky way
assertThat(StreamUtils.withIndex(stream)
.filter(e -> e.getElement().length() == 1)
.map(e -> e.getIndex())
.findFirst()
.get())
.isEqualTo(1);
}
@Test
public void testIsEmpty() {
assertThat(Iterables.isEmpty(source)).isEqualTo(false);
assertThat(stream.noneMatch(s -> true)).isEqualTo(false);
}
@Test
public void testLimit() {
assertThat(Lists.newArrayList(Iterables.limit(source, 2))).isEqualTo(Arrays.asList("as", "q"));
assertThat(stream.limit(2).collect(Collectors.toList())).isEqualTo(Arrays.asList("as", "q"));
}
@Test
@SuppressWarnings("unchecked")
public void testPartition() {
List<String> source = ImmutableList.of("trash", "talk", "arg", "loose", "fade", "cross", "dump", "bust");
assertThat(Iterables.partition(source, 3)).containsExactly(
ImmutableList.of("trash", "talk", "arg"),
ImmutableList.of("loose", "fade", "cross"),
ImmutableList.of("dump", "bust"));
int partitionSize = 3;
List<List<String>> partitions = StreamUtils.withIndex(source.stream())
.collect(ArrayList::new, (lists, el) -> {
int place = el.getIndex() % partitionSize;
List<String> part;
if (place == 0) {
part = new ArrayList<>();
lists.add(part);
} else {
part = lists.get(lists.size() - 1);
}
part.add(el.getElement());
}, ArrayList::addAll);
assertThat(partitions).containsExactly(
ImmutableList.of("trash", "talk", "arg"),
ImmutableList.of("loose", "fade", "cross"),
ImmutableList.of("dump", "bust"));
}
@Test
public void testRemoveAll() {
List<String> removed = ImmutableList.of("q", "d");
Iterables.removeAll(source, removed);
assertThat(source).containsExactly("as", "def");
assertThat(stream.filter(s -> !removed.contains(s))
.collect(Collectors.toList())).containsExactly("as", "def");
}
@Test
public void testRemoveIf() {
Iterables.removeIf(source, it -> it.length() < 3);
assertThat(Arrays.asList("def")).isEqualTo(source);
List<String> removed = stream
.filter(((Predicate<String>) it -> it.length() < 3).negate())
.collect(Collectors.toList());
assertThat(Arrays.asList("def")).isEqualTo(removed);
}
@Test
public void testRetainAll() {
List<String> removed = ImmutableList.of("q", "d");
Iterables.retainAll(source, removed);
assertThat(source).containsExactly("q");
assertThat(stream.filter(s -> removed.contains(s))
.collect(Collectors.toList())).containsExactly("q");
}
@Test
public void testTransform() {
assertThat(Lists.newArrayList(Iterables.transform(source, String::length))).isEqualTo(Arrays.asList(2, 1, 3));
assertThat(stream.map(String::length).collect(Collectors.toList())).isEqualTo(Arrays.asList(2, 1, 3));
}
@Test
public void testTryFind() {
assertThat(Iterables.tryFind(source, it -> it.length() == 4).or("abcd")).isEqualTo("abcd");
assertThat(stream.filter(it -> it.length() == 4).findAny().orElse("abcd")).isEqualTo("abcd");
}
@Test
public void testSkip() {
assertThat(Lists.newArrayList(Iterables.skip(source, 2))).isEqualTo(Arrays.asList("def"));
assertThat(stream.skip(2).collect(Collectors.toList())).isEqualTo(Arrays.asList("def"));
}
} |
package com.oltruong.teamag.rest;
import com.oltruong.teamag.model.Member;
import com.oltruong.teamag.model.Task;
import com.oltruong.teamag.model.builder.EntityFactory;
import com.oltruong.teamag.model.enumeration.MemberType;
import com.oltruong.teamag.service.MemberService;
import com.oltruong.teamag.service.TaskService;
import com.oltruong.teamag.transformer.TaskWebBeanTransformer;
import com.oltruong.teamag.utils.TestUtils;
import com.oltruong.teamag.webbean.TaskWebBean;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.slf4j.Logger;
import java.util.List;
import java.util.function.Supplier;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import javax.ws.rs.core.Response;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class TaskEndPointTest extends AbstractEndPointTest {
@Mock
private TaskService mockTaskService;
@Mock
private MemberService mockMemberService;
@Mock
private Logger mockLogger;
private TaskEndPoint taskEndPoint;
private Task task;
@Before
public void prepare() {
super.setup();
taskEndPoint = new TaskEndPoint();
TestUtils.setPrivateAttribute(taskEndPoint, mockTaskService, "taskService");
TestUtils.setPrivateAttribute(taskEndPoint, mockMemberService, "memberService");
TestUtils.setPrivateAttribute(taskEndPoint, AbstractEndPoint.class, mockLogger, "LOGGER");
TestUtils.setPrivateAttribute(taskEndPoint, mockLogger, "LOGGER");
TestUtils.setPrivateAttribute(taskEndPoint, AbstractEndPoint.class, mockUriInfo, "uriInfo");
task = EntityFactory.createTask();
when(mockTaskService.persist(eq(task))).thenReturn(task);
assertThat(taskEndPoint.getService()).isEqualTo(mockTaskService);
}
@Test
public void getTasks() throws Exception {
testFindTasks(mockTaskService::findAll, taskEndPoint::getAll);
verify(mockTaskService, atLeastOnce()).findAll();
}
@Test
public void getTasksWithActivity() throws Exception {
testFindTasks(mockTaskService::findTaskWithActivity, taskEndPoint::getTasksWithActivity);
verify(mockTaskService, atLeastOnce()).findTaskWithActivity();
}
private void testFindTasks(Supplier<List<Task>> taskListSupplier, Supplier<Response> responseSupplier) {
List<Task> taskList = EntityFactory.createList(EntityFactory::createTask);
Task parentTask = EntityFactory.createTask();
parentTask.setId(EntityFactory.createRandomLong());
taskList.forEach(task -> task.setTask(parentTask));
when(taskListSupplier.get()).thenReturn(taskList);
Response response = responseSupplier.get();
checkResponseOK(response);
List<TaskWebBean> taskListReturned = (List<TaskWebBean>) response.getEntity();
assertThat(taskListReturned).hasSameSizeAs(taskList);
}
@Test
public void get() throws Exception {
when(mockTaskService.find(any())).thenReturn(task);
Response response = taskEndPoint.getSingle(randomId);
checkResponseOK(response);
TaskWebBean taskReturned = (TaskWebBean) response.getEntity();
assertThat(taskReturned).isEqualToComparingFieldByField(TaskWebBeanTransformer.transformTask(task));
verify(mockTaskService).find(eq(randomId));
}
@Test
public void create() throws Exception {
task.setId(randomId);
Response response = taskEndPoint.create(task);
checkResponseCreated(response);
verify(mockTaskService).persist(eq(task));
}
@Test
public void createWithParamsNull() throws Exception {
task.setId(randomId);
createWithParams(null, null);
}
@Test
public void createWithParamsYearNull() throws Exception {
task.setId(randomId);
createWithParams(10, null);
}
@Test
public void createWithParamsMonthNull() throws Exception {
task.setId(randomId);
createWithParams(null, 2016);
}
private void createWithParams(Integer month, Integer year) {
Response response = taskEndPoint.create(null, month, year, task);
checkResponseCreated(response);
verify(mockTaskService).persist(eq(task));
}
@Test
public void createWithParams() throws Exception {
task.setId(randomId);
Task taskCreated = EntityFactory.createTask();
taskCreated.setId(randomId);
when(mockTaskService.persist(any(DateTime.class), any(Member.class), eq(task))).thenReturn(taskCreated);
Response response = taskEndPoint.create(randomId, 9, 2015, task);
checkResponseCreated(response);
}
@Test
public void createWithParamsException() throws Exception {
task.setId(randomId);
when(mockTaskService.persist(any(DateTime.class), any(Member.class), eq(task))).thenThrow(new EntityExistsException());
Response response = taskEndPoint.create(randomId, 9, 2015, task);
checkResponseBadRequest(response);
}
@Test
public void create_existing() throws Exception {
task.setId(randomId);
doThrow(new EntityExistsException()).when(mockTaskService).persist(eq(task));
Response response = taskEndPoint.create(task);
checkResponseNotAcceptable(response);
verify(mockTaskService).persist(eq(task));
verify(mockLogger).warn(anyString(), isA(EntityExistsException.class));
}
@Test
public void deleteWithParamsNull() throws Exception {
task.setId(randomId);
deleteWithParams(null, null);
}
@Test
public void deleteWithParamsYearNull() throws Exception {
task.setId(randomId);
deleteWithParams(10, null);
}
@Test
public void deleteWithParamsMonthNull() throws Exception {
task.setId(randomId);
deleteWithParams(null, 2016);
}
private void deleteWithParams(Integer month, Integer year) {
Member member = EntityFactory.createMember();
member.setMemberType(MemberType.ADMINISTRATOR);
when(mockMemberService.find(randomId)).thenReturn(member);
Response response = taskEndPoint.delete(randomId, randomId, month, year);
checkResponseNoContent(response);
verify(mockTaskService).remove(eq(randomId));
}
@Test
public void deleteWithParamsForbidden() {
Member member = EntityFactory.createMember();
member.setMemberType(MemberType.BASIC);
when(mockMemberService.find(randomId)).thenReturn(member);
Response response = taskEndPoint.delete(randomId, randomId, null, null);
checkResponseForbidden(response);
verify(mockTaskService, never()).remove(eq(randomId));
}
@Test
public void deleteWithParams() throws Exception {
task.setId(randomId);
Task taskCreated = EntityFactory.createTask();
taskCreated.setId(randomId);
when(mockTaskService.persist(any(DateTime.class), any(Member.class), eq(task))).thenReturn(taskCreated);
Response response = taskEndPoint.delete(randomId, randomId, 9, 2015);
checkResponseNoContent(response);
verify(mockTaskService).remove(eq(randomId), eq(randomId), isA(DateTime.class));
}
@Test
public void updateTask() throws Exception {
Task task = EntityFactory.createTask();
assertThat(task.getId()).isNull();
Response response = taskEndPoint.updateTask(randomId, task);
checkResponseOK(response);
assertThat(task.getId()).isEqualTo(randomId);
verify(mockTaskService).merge(eq(task));
}
@Test
public void delete() throws Exception {
Response response = taskEndPoint.delete(randomId);
checkResponseNoContent(response);
verify(mockTaskService).remove(eq(randomId));
}
@Test
public void deleteNotFound() throws Exception {
doThrow(new EntityNotFoundException()).when(mockTaskService).remove(anyLong());
Response response = taskEndPoint.delete(randomId);
checkResponseNotFound(response);
verify(mockTaskService).remove(eq(randomId));
}
} |
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle;
import static com.puppycrawl.tools.checkstyle.TestUtils.assertUtilsClassHasPrivateConstructor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Dictionary;
import org.apache.commons.beanutils.ConversionException;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class UtilsTest {
/** After appending to path produces equivalent, but denormalized path */
private static final String PATH_DENORMALIZER = "/levelDown/.././";
/**
* Test Utils.countCharInString.
*/
@Test
public void testLengthExpandedTabs()
throws Exception {
final String s1 = "\t";
assertEquals(8, Utils.lengthExpandedTabs(s1, s1.length(), 8));
final String s2 = " \t";
assertEquals(8, Utils.lengthExpandedTabs(s2, s2.length(), 8));
final String s3 = "\t\t";
assertEquals(16, Utils.lengthExpandedTabs(s3, s3.length(), 8));
final String s4 = " \t ";
assertEquals(9, Utils.lengthExpandedTabs(s4, s4.length(), 8));
assertEquals(0, Utils.lengthMinusTrailingWhitespace(""));
assertEquals(0, Utils.lengthMinusTrailingWhitespace(" \t "));
assertEquals(3, Utils.lengthMinusTrailingWhitespace(" 23"));
assertEquals(3, Utils.lengthMinusTrailingWhitespace(" 23 \t "));
}
@Test(expected = ConversionException.class)
public void testBadRegex() {
Utils.createPattern("[");
}
@Test
public void testFileExtensions() {
final String[] fileExtensions = {"java"};
File file = new File("file.pdf");
assertFalse(Utils.fileExtensionMatches(file, fileExtensions));
assertTrue(Utils.fileExtensionMatches(file, (String[]) null));
file = new File("file.java");
assertTrue(Utils.fileExtensionMatches(file, fileExtensions));
file = new File("file.");
assertTrue(Utils.fileExtensionMatches(file, ""));
}
@Test
public void testBaseClassnameForCanonicalName() {
assertEquals("List", Utils.baseClassname("java.util.List"));
}
@Test
public void testBaseClassnameForSimpleName() {
assertEquals("Set", Utils.baseClassname("Set"));
}
@Test
public void testRelativeNormalizedPath() {
final String relativePath = Utils.relativizeAndNormalizePath("/home", "/home/test");
assertEquals("test", relativePath);
}
@Test
public void testRelativeNormalizedPathWithNullBaseDirectory() {
final String relativePath = Utils.relativizeAndNormalizePath(null, "/tmp");
assertEquals("/tmp", relativePath);
}
@Test
public void testRelativeNormalizedPathWithDenormalizedBaseDirectory() throws IOException {
final String sampleAbsolutePath = new File("src/main/java").getCanonicalPath();
final String absoluteFilePath = sampleAbsolutePath + "/SampleFile.java";
final String basePath = sampleAbsolutePath + PATH_DENORMALIZER;
final String relativePath = Utils.relativizeAndNormalizePath(basePath, absoluteFilePath);
assertEquals("SampleFile.java", relativePath);
}
@Test
public void testIsProperUtilsClass() throws ReflectiveOperationException {
assertUtilsClassHasPrivateConstructor(Utils.class);
}
@Test
public void testInvalidPattern() {
boolean result = Utils.isPatternValid("some[invalidPattern");
assertFalse(result);
}
@Test
public void testGetExistingConstructor() throws NoSuchMethodException {
Constructor<?> constructor = Utils.getConstructor(String.class, String.class);
assertEquals(String.class.getConstructor(String.class), constructor);
}
@Test
public void testGetNonExistingConstructor() throws NoSuchMethodException {
try {
Utils.getConstructor(Math.class);
fail();
}
catch (IllegalStateException expected) {
assertSame(NoSuchMethodException.class, expected.getCause().getClass());
}
}
@Test
public void testInvokeConstructor() throws NoSuchMethodException {
Constructor<String> constructor = String.class.getConstructor(String.class);
String constructedString = Utils.invokeConstructor(constructor, "string");
assertEquals("string", constructedString);
}
@SuppressWarnings("rawtypes")
@Test
public void testInvokeConstructorThatFails() throws NoSuchMethodException {
Constructor<Dictionary> constructor = Dictionary.class.getConstructor();
try {
Utils.invokeConstructor(constructor);
fail();
}
catch (IllegalStateException expected) {
assertSame(InstantiationException.class, expected.getCause().getClass());
}
}
@Test
public void testGetIntFromAccessibleField() throws NoSuchFieldException {
Field field = Integer.class.getField("MAX_VALUE");
assertEquals(Integer.MAX_VALUE, Utils.getIntFromField(field, 0));
}
@Test
public void testGetIntFromInaccessibleField() throws NoSuchFieldException {
Field field = Integer.class.getDeclaredField("value");
try {
Utils.getIntFromField(field, 0);
}
catch (IllegalStateException expected) {
// expected
}
}
@Test
public void testTokenValueIncorrect() throws NoSuchMethodException {
Integer id = Integer.MAX_VALUE - 1;
try {
Utils.getTokenName(id);
fail();
}
catch (IllegalArgumentException expected) {
assertEquals("given id " + id, expected.getMessage());
}
}
@Test
public void testTokenValueIncorrect2() throws NoSuchMethodException, IllegalAccessException {
Integer id = 0;
String[] originalValue = null;
Field fieldToken = null;
try {
// overwrite static field with new value
Field[] fields = Utils.class.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if ("TOKEN_VALUE_TO_NAME".equals(field.getName())) {
fieldToken = field;
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
originalValue = (String[]) field.get(null);
field.set(null, new String[] {null});
}
}
Utils.getTokenName(id);
fail();
}
catch (IllegalArgumentException expected) {
// restoring original value, to let other tests pass
fieldToken.set(null, originalValue);
assertEquals("given id " + id, expected.getMessage());
}
catch (IllegalAccessException e) {
fail();
}
catch (NoSuchFieldException e) {
fail();
}
}
@Test
public void testTokenIdIncorrect() throws NoSuchMethodException {
String id = "NON_EXISTING_VALUE";
try {
Utils.getTokenId(id);
fail();
}
catch (IllegalArgumentException expected) {
assertEquals("given name " + id, expected.getMessage());
}
}
@Test
public void testShortDescriptionIncorrect() throws NoSuchMethodException {
String id = "NON_EXISTING_VALUE";
try {
Utils.getShortDescription(id);
fail();
}
catch (IllegalArgumentException expected) {
assertEquals("given name " + id, expected.getMessage());
}
}
@Test
public void testIsCommentType() throws NoSuchMethodException {
assertTrue(Utils.isCommentType(TokenTypes.SINGLE_LINE_COMMENT));
assertTrue(Utils.isCommentType(TokenTypes.BLOCK_COMMENT_BEGIN));
assertTrue(Utils.isCommentType(TokenTypes.BLOCK_COMMENT_END));
assertTrue(Utils.isCommentType(TokenTypes.COMMENT_CONTENT));
}
@Test
public void testClose() {
Utils.close(null);
Utils.close(new Closeable() {
@Override
public void close() throws IOException {
}
});
}
@Test(expected = IllegalStateException.class)
public void testCloseWithException() {
Utils.close(new Closeable() {
@Override
public void close() throws IOException {
throw new IOException();
}
});
}
} |
package edu.hm.hafner.analysis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import edu.hm.hafner.analysis.ModuleDetector.FileSystem;
import edu.hm.hafner.util.PathUtil;
import edu.hm.hafner.util.ResourceTest;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
/**
* Tests the class {@link ModuleDetector}.
*/
@SuppressFBWarnings("DMI")
class ModuleDetectorTest extends ResourceTest {
private static final String MANIFEST = "MANIFEST.MF";
private static final String MANIFEST_NAME = "MANIFEST-NAME.MF";
private static final Path ROOT = Paths.get(File.pathSeparatorChar == ';' ? "C:\\Windows" : "/tmp");
private static final String PREFIX = new PathUtil().getAbsolutePath(ROOT) + "/";
private static final int NO_RESULT = 0;
private static final String PATH_PREFIX_MAVEN = "path/to/maven/";
private static final String PATH_PREFIX_OSGI = "path/to/osgi/";
private static final String PATH_PREFIX_ANT = "path/to/ant/";
private static final String EXPECTED_MAVEN_MODULE = "ADT Business Logic";
private static final String EXPECTED_ANT_MODULE = "checkstyle";
private static final String EXPECTED_OSGI_MODULE = "de.faktorlogik.prototyp";
private InputStream read(final String fileName) {
return asInputStream(fileName);
}
@Test
void shouldIdentifyModuleByReadingOsgiBundle() {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE});
when(stub.open(anyString())).thenReturn(read(MANIFEST));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt")))
.isEqualTo(EXPECTED_OSGI_MODULE);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt")))
.isEqualTo(EXPECTED_OSGI_MODULE);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt"))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleByReadingOsgiBundleWithVendorInL10nProperties() {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE});
when(stub.open(anyString())).thenReturn(read(MANIFEST), read("l10n.properties"));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
String expectedName = "de.faktorlogik.prototyp (My Vendor)";
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt")))
.isEqualTo(expectedName);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt")))
.isEqualTo(expectedName);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt"))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleByReadingOsgiBundleWithManifestName() {
FileSystem fileSystem = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(
new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE});
when(stub.open(anyString())).thenReturn(read(MANIFEST_NAME), read("l10n.properties"));
});
ModuleDetector detector = new ModuleDetector(ROOT, fileSystem);
String expectedName = "My Bundle";
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt")))
.isEqualTo(expectedName);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt")))
.isEqualTo(expectedName);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt"))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleByReadingMavenPom() {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(
new String[]{PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM});
when(stub.open(anyString())).thenAnswer(fileName -> read(ModuleDetector.MAVEN_POM));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt"))).isEqualTo(
EXPECTED_MAVEN_MODULE);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "in/between/something.txt"))).isEqualTo(
EXPECTED_MAVEN_MODULE);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")).isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleByReadingMavenPomWithoutName() {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM});
when(stub.open(anyString())).thenAnswer(filename -> read("no-name-pom.xml"));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
String artifactId = "com.avaloq.adt.core";
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt")))
.isEqualTo(artifactId);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "in/between/something.txt")))
.isEqualTo(artifactId);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt"))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleByReadingAntProjectFile() {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_ANT + ModuleDetector.ANT_PROJECT});
when(stub.open(anyString())).thenAnswer(filename -> read(ModuleDetector.ANT_PROJECT));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt")))
.isEqualTo(EXPECTED_ANT_MODULE);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "in/between/something.txt")))
.isEqualTo(EXPECTED_ANT_MODULE);
assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt"))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIgnoreExceptionsDuringParsing() {
FileSystem fileSystem = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(new String[NO_RESULT]);
when(stub.open(anyString())).thenThrow(new FileNotFoundException("File not found"));
});
ModuleDetector detector = new ModuleDetector(ROOT, fileSystem);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt")))
.isEqualTo(StringUtils.EMPTY);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt")))
.isEqualTo(StringUtils.EMPTY);
}
@Test
void shouldIdentifyModuleIfThereAreMoreEntries() {
FileSystem factory = createFileSystemStub(stub -> {
String ant = PATH_PREFIX_ANT + ModuleDetector.ANT_PROJECT;
String maven = PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM;
when(stub.find(any(), anyString())).thenReturn(new String[]{ant, maven});
when(stub.open(PREFIX + ant)).thenReturn(read(ModuleDetector.ANT_PROJECT));
when(stub.open(PREFIX + maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt")))
.isEqualTo(EXPECTED_ANT_MODULE);
assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt")))
.isEqualTo(EXPECTED_MAVEN_MODULE);
}
@Test
void shouldEnsureThatMavenHasPrecedenceOverAnt() {
String prefix = "/prefix/";
String ant = prefix + ModuleDetector.ANT_PROJECT;
String maven = prefix + ModuleDetector.MAVEN_POM;
verifyOrder(prefix, ant, maven, new String[]{ant, maven});
verifyOrder(prefix, ant, maven, new String[]{maven, ant});
}
@Test
void shouldEnsureThatOsgiHasPrecedenceOverMavenAndAnt() {
String prefix = "/prefix/";
String ant = prefix + ModuleDetector.ANT_PROJECT;
String maven = prefix + ModuleDetector.MAVEN_POM;
String osgi = prefix + ModuleDetector.OSGI_BUNDLE;
verifyOrder(prefix, ant, maven, osgi, ant, maven, osgi);
verifyOrder(prefix, ant, maven, osgi, ant, osgi, maven);
verifyOrder(prefix, ant, maven, osgi, maven, ant, osgi);
verifyOrder(prefix, ant, maven, osgi, maven, osgi, ant);
verifyOrder(prefix, ant, maven, osgi, osgi, ant, maven);
verifyOrder(prefix, ant, maven, osgi, osgi, maven, osgi);
}
@SuppressWarnings("PMD.UseVarargs")
private void verifyOrder(final String prefix, final String ant, final String maven, final String[] foundFiles) {
FileSystem factory = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(foundFiles);
when(stub.open(ant)).thenReturn(read(ModuleDetector.ANT_PROJECT));
when(stub.open(maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM));
});
ModuleDetector detector = new ModuleDetector(ROOT, factory);
assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_MAVEN_MODULE);
}
private void verifyOrder(final String prefix, final String ant, final String maven, final String osgi,
final String... foundFiles) {
FileSystem fileSystem = createFileSystemStub(stub -> {
when(stub.find(any(), anyString())).thenReturn(foundFiles);
when(stub.open(ant)).thenAnswer(filename -> read(ModuleDetector.ANT_PROJECT));
when(stub.open(maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM));
when(stub.open(osgi)).thenAnswer(filename -> read(MANIFEST));
when(stub.open(prefix + "/" + ModuleDetector.PLUGIN_PROPERTIES)).thenAnswer(filename -> createEmptyStream());
when(stub.open(prefix + "/" + ModuleDetector.BUNDLE_PROPERTIES)).thenAnswer(filename -> createEmptyStream());
});
ModuleDetector detector = new ModuleDetector(ROOT, fileSystem);
assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_OSGI_MODULE);
}
private InputStream createEmptyStream() {
try {
return IOUtils.toInputStream("", "UTF-8");
}
catch (IOException e) {
throw new AssertionError(e);
}
}
private FileSystem createFileSystemStub(final Stub stub) {
try {
FileSystem fileSystem = mock(FileSystem.class);
stub.apply(fileSystem);
return fileSystem;
}
catch (IOException exception) {
throw new AssertionError(exception);
}
}
/**
* Stubs the {@link PackageDetectors.FileSystem} using a lambda.
*/
@FunctionalInterface
private interface Stub {
void apply(FileSystem f) throws IOException;
}
} |
package mho.wheels.misc;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.iterables.IterableProvider;
import mho.wheels.iterables.IterableUtils;
import mho.wheels.iterables.RandomProvider;
import mho.wheels.structures.Pair;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Random;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.misc.BigDecimalUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static org.junit.Assert.*;
public class BigDecimalUtilsProperties {
private static boolean USE_RANDOM;
private static int LIMIT;
private static IterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = new RandomProvider(new Random(0x6af477d9a7e54fcaL));
LIMIT = 1000;
} else {
P = ExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
@Test
public void testAllProperties() {
for (boolean useRandom : Arrays.asList(false, true)) {
System.out.println("Testing BigDecimalUtils properties " + (useRandom ? "randomly" : "exhaustively"));
USE_RANDOM = useRandom;
propertiesSetPrecision();
System.out.println();
}
System.out.println("Done");
System.out.println();
}
private static void propertiesSetPrecision() {
initialize();
System.out.println("testing setPrecision(BigDecimal, int) properties...");
Iterable<Pair<BigDecimal, Integer>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), P.positiveIntegers());
} else {
ps = P.pairs(P.bigDecimals(), ((RandomProvider) P).positiveIntegersGeometric(20));
}
for (Pair<BigDecimal, Integer> p : take(LIMIT, IterableUtils.filter(q -> ne(q.a, BigDecimal.ZERO), ps))) {
assert p.a != null;
assert p.b != null;
BigDecimal bd = setPrecision(p.a, p.b);
assertEquals(p.toString(), bd.precision(), (int) p.b);
assertTrue(p.toString(), ne(bd, BigDecimal.ZERO));
}
Iterable<Pair<BigDecimal, Integer>> zeroPs;
if (P instanceof ExhaustiveProvider) {
Iterable<BigDecimal> zeroes = map(i -> new BigDecimal(BigInteger.ZERO, i), P.integers());
zeroPs = ((ExhaustiveProvider) P).pairsSquareRootOrder(zeroes, P.positiveIntegers());
} else {
Iterable<BigDecimal> zeroes = map(
i -> new BigDecimal(BigInteger.ZERO, i),
((RandomProvider) P).integersGeometric(20)
);
zeroPs = P.pairs(zeroes, ((RandomProvider) P).positiveIntegersGeometric(20));
}
for (Pair<BigDecimal, Integer> p : take(LIMIT, zeroPs)) {
assert p.a != null;
assert p.b != null;
BigDecimal bd = setPrecision(p.a, p.b);
assertTrue(p.toString(), bd.scale() > -1);
assertTrue(p.toString(), eq(bd, BigDecimal.ZERO));
}
for (Pair<BigDecimal, Integer> p : take(LIMIT, filter(q -> q.b > 1, zeroPs))) {
assert p.a != null;
assert p.b != null;
BigDecimal bd = setPrecision(p.a, p.b);
assertTrue(
p.toString(),
bd.toString().equals("0." + replicate(p.b - 1, '0')) || bd.toString().equals("0E-" + (p.b - 1))
);
}
Iterable<Pair<BigDecimal, Integer>> failPs;
if (P instanceof ExhaustiveProvider) {
failPs = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), map(i -> -i, P.naturalIntegers()));
} else {
failPs = P.pairs(P.bigDecimals(), map(i -> -i, ((RandomProvider) P).naturalIntegersGeometric(20)));
}
for (Pair<BigDecimal, Integer> p : take(LIMIT, failPs)) {
assert p.a != null;
assert p.b != null;
try {
setPrecision(p.a, p.b);
fail(p.toString());
} catch (ArithmeticException ignored) {}
}
}
} |
package org.broad.igv.ui.action;
import junit.framework.AssertionFailedError;
import org.broad.igv.AbstractHeadlessTest;
import org.broad.igv.feature.BasicFeature;
import org.broad.igv.feature.NamedFeature;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.util.TestUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.*;
public class SearchCommandTest extends AbstractHeadlessTest {
@Before
public void setUp() throws Exception{
super.setUp();
}
@Test
public void testSingleChromosomes() throws Exception {
int min = 1;
int max = 22;
String[] chrs = new String[max - min + 1];
String[] nums = new String[max - min + 1];
String chr;
for (int cn = min; cn <= max; cn++) {
chr = "chr" + cn;
chrs[cn - min] = chr;
nums[cn - min] = "" + cn;
}
tstFeatureTypes(chrs, SearchCommand.ResultType.CHROMOSOME);
tstFeatureTypes(nums, SearchCommand.ResultType.CHROMOSOME);
}
@Test
public void testChromoWithColon() throws Exception {
List<String> chrNames = Arrays.asList("chr10", "chr1", "chr20");
List<List<String>> aliases = Arrays.asList(
Arrays.asList("abc:123", "abc:456", "abc:789"),
Arrays.asList("xy:12"),
Arrays.asList("aaa:bbb"));
Collection<Collection<String>> synonymsList = new ArrayList<Collection<String>>();
for (int i = 0; i < chrNames.size(); i++) {
List<String> synonyms = new ArrayList<String>();
synonyms.addAll(aliases.get(i));
synonyms.add(chrNames.get(i));
synonymsList.add(synonyms);
}
if (genome instanceof Genome) {
((Genome) genome).addChrAliases(synonymsList);
}
SearchCommand cmd;
for (int i = 0; i < chrNames.size(); i++) {
String chr = chrNames.get(i);
List<String> synonyms = aliases.get(i);
for (String searchStr : synonyms) {
cmd = new SearchCommand(null, searchStr, genome);
List<SearchCommand.SearchResult> results = cmd.runSearch(cmd.searchString);
assertEquals(1, results.size());
assertEquals(SearchCommand.ResultType.CHROMOSOME, results.get(0).type);
assertEquals(chr, results.get(0).chr);
}
}
String[] queries = new String[]{"X:100-1000", "Y:100-1000", "Y:12", "1\t 100", "X\t50", "X\t50\t500"};
tstFeatureTypes(queries, SearchCommand.ResultType.LOCUS);
genome = TestUtils.loadGenome();
}
@Test
public void testSingleFeatures() throws Exception {
String[] features = {"EGFR", "ABO", "BRCA1", "egFr"};
tstFeatureTypes(features, SearchCommand.ResultType.FEATURE);
}
/**
* Test that mutations are parsed correctly. They get returned
* as type LOCUS.
*
* @throws Exception
*/
@Test @Ignore("Fails unless tests are run in separate JVMs")
public void testFeatureMuts() throws Exception {
String[] features = {"EGFR:M1I", "EGFR:G5R", "egfr:g5r", "egfr:r2*"};
tstFeatureTypes(features, SearchCommand.ResultType.LOCUS);
String egfr_seq = "atgcgaccctccgggacggccggggcagcgctcctggcgctgctggctgcgctc";
String[] targets = new String[]{"A", "G", "C", "T", "a", "g", "c", "t"};
String mut_let, tar_let;
for (int let = 0; let < egfr_seq.length(); let++) {
mut_let = egfr_seq.substring(let, let + 1);
if (Math.random() > 0.5) {
mut_let = mut_let.toUpperCase();
}
tar_let = targets[let % targets.length];
String[] features2 = {"EGFR:" + (let + 1) + mut_let + ">" + tar_let};
tstFeatureTypes(features2, SearchCommand.ResultType.LOCUS);
}
}
/*
Run a bunch of queries, test that they all return the same type
*/
private void tstFeatureTypes(String[] queries, SearchCommand.ResultType type) {
SearchCommand cmd;
for (String f : queries) {
cmd = new SearchCommand(null, f, genome);
List<SearchCommand.SearchResult> results = cmd.runSearch(cmd.searchString);
try {
assertTrue(containsType(results, type));
} catch (AssertionFailedError e) {
System.out.println(f + " :" + results.get(0).getMessage());
throw e;
}
}
}
private boolean containsType(List<SearchCommand.SearchResult> results, SearchCommand.ResultType check) {
boolean contains = false;
for (SearchCommand.SearchResult result : results) {
contains |= result.type == check;
}
return contains;
}
@Test
public void testMultiFeatures() throws Exception {
tstMultiFeatures(" ");
tstMultiFeatures(" ");
tstMultiFeatures(" ");
tstMultiFeatures(" ");
tstMultiFeatures("\t");
tstMultiFeatures("\r\n"); //This should never happen
}
public void tstMultiFeatures(String delim) throws Exception {
//Not sure if this is correct behavior or not
String[] tokens = {"EgfR", "ABO", "BRCA1", "chr1:1-100"};
SearchCommand.ResultType[] types = new SearchCommand.ResultType[]{
SearchCommand.ResultType.FEATURE,
SearchCommand.ResultType.FEATURE,
SearchCommand.ResultType.FEATURE,
SearchCommand.ResultType.LOCUS,
SearchCommand.ResultType.CHROMOSOME,
SearchCommand.ResultType.CHROMOSOME
};
String searchStr = tokens[0];
for (int ii = 1; ii < tokens.length; ii++) {
searchStr += delim + tokens[ii];
}
SearchCommand cmd;
cmd = new SearchCommand(null, searchStr, genome);
List<SearchCommand.SearchResult> results = cmd.runSearch(cmd.searchString);
for (int ii = 0; ii < tokens.length; ii++) {
SearchCommand.SearchResult result = results.get(ii);
try {
assertEquals(types[ii], result.type);
assertEquals(tokens[ii].toLowerCase(), result.getLocus().toLowerCase());
} catch (AssertionFailedError e) {
System.out.println(searchStr + " :" + result.getMessage());
throw e;
}
}
}
@Test
public void testMultiChromosomes() throws Exception {
String[] tokens = {"chr1", "chr5", "4", "12", "X", "Y"};
String searchStr = tokens[0];
for (int ii = 1; ii < tokens.length; ii++) {
searchStr += " " + tokens[ii];
}
SearchCommand cmd;
cmd = new SearchCommand(null, searchStr, genome);
List<SearchCommand.SearchResult> results = cmd.runSearch(cmd.searchString);
for (int ii = 0; ii < tokens.length; ii++) {
SearchCommand.SearchResult result = results.get(ii);
assertEquals(SearchCommand.ResultType.CHROMOSOME, result.type);
assertTrue(result.getLocus().contains(tokens[ii]));
}
}
@Test
public void testError() throws Exception {
String[] tokens = {"ueth", "EGFRa", "BRCA56", "EGFR:?1?"};
tstFeatureTypes(tokens, SearchCommand.ResultType.ERROR);
}
/**
* Saving because we might want these test cases, but don't
* want to test checkTokenType specifically
*/
@Deprecated
public void testTokenChecking() {
String[] chromos = {"chr3", "chr20", "chrX", "chrY"};
SearchCommand cmd = new SearchCommand(null, "", genome);
for (String chr : chromos) {
assertEquals(SearchCommand.ResultType.CHROMOSOME, cmd.checkTokenType(chr));
}
String[] starts = {"39,239,480", "958392", "0,4829,44", "5"};
String[] ends = {"40,321,111", "5", "48153181,813156", ""};
for (int ii = 0; ii < starts.length; ii++) {
String tstr = chromos[ii] + ":" + starts[ii] + "-" + ends[ii];
assertEquals(SearchCommand.ResultType.LOCUS, cmd.checkTokenType(tstr));
tstr = chromos[ii] + "\t" + starts[ii] + " " + ends[ii];
assertEquals(SearchCommand.ResultType.LOCUS, cmd.checkTokenType(tstr));
}
String[] errors = {"egfr:1-100", " ", "chr1\t1\t100\tchr2"};
for (String s : errors) {
//System.out.println(s);
assertEquals(SearchCommand.ResultType.ERROR, cmd.checkTokenType(s));
}
}
} |
package org.fcrepo.binary;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.modeshape.jcr.api.JcrConstants.JCR_MIME_TYPE;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.Session;
import org.junit.BeforeClass;
import org.junit.Test;
import org.modeshape.jcr.api.JcrConstants;
/**
* @todo Add Documentation.
* @author cbeer
* @date Apr 25, 2013
*/
public class PolicyDecisionPointTest {
static PolicyDecisionPoint pt;
static private String dummyHint;
static private String tiffHint;
/**
* @todo Add Documentation.
*/
@BeforeClass
public static void setupPdp() {
pt = new PolicyDecisionPoint();
dummyHint = "dummy-store-id";
Policy policy = new MimeTypePolicy("image/x-dummy-type", dummyHint);
pt.addPolicy(policy);
tiffHint = "tiff-store-id";
Policy tiffPolicy = new MimeTypePolicy("image/tiff", tiffHint);
pt.addPolicy(tiffPolicy);
}
/**
* @todo Add Documentation.
*/
@Test
public void testDummyNode() throws Exception {
Session mockSession = mock(Session.class);
Node mockRootNode = mock(Node.class);
Node mockDsNode = mock(Node.class);
when(mockDsNode.getSession()).thenReturn(mockSession);
Property mockProperty = mock(Property.class);
when(mockProperty.getString()).thenReturn("image/x-dummy-type");
Node mockContentNode = mock(Node.class);
when(mockDsNode.getNode(JcrConstants.JCR_CONTENT)).
thenReturn(mockContentNode);
when(mockContentNode.getProperty(JCR_MIME_TYPE)).
thenReturn(mockProperty);
String receivedHint = pt.evaluatePolicies(mockDsNode);
assertThat(receivedHint, is(dummyHint));
}
/**
* @todo Add Documentation.
*/
@Test
public void testTiffNode() throws Exception {
Session mockSession = mock(Session.class);
Node mockRootNode = mock(Node.class);
Node mockDsNode = mock(Node.class);
when(mockDsNode.getSession()).thenReturn(mockSession);
Property mockProperty = mock(Property.class);
when(mockProperty.getString()).thenReturn("image/tiff");
Node mockContentNode = mock(Node.class);
when(mockDsNode.getNode(JcrConstants.JCR_CONTENT)).
thenReturn(mockContentNode);
when(mockContentNode.getProperty(JCR_MIME_TYPE)).
thenReturn(mockProperty);
String receivedHint = pt.evaluatePolicies(mockDsNode);
assertThat(receivedHint, is(tiffHint));
}
/**
* @todo Add Documentation.
*/
@Test
public void testOtherNode() throws Exception {
Session mockSession = mock(Session.class);
Node mockRootNode = mock(Node.class);
Node mockDsNode = mock(Node.class);
when(mockDsNode.getSession()).thenReturn(mockSession);
Property mockProperty = mock(Property.class);
when(mockProperty.getString()).thenReturn("image/x-other");
Node mockContentNode = mock(Node.class);
when(mockDsNode.getNode(JcrConstants.JCR_CONTENT)).
thenReturn(mockContentNode);
when(mockContentNode.getProperty(JCR_MIME_TYPE)).
thenReturn(mockProperty);
String receivedHint = pt.evaluatePolicies(mockDsNode);
assertNull(receivedHint);
}
} |
package org.openlmis.fulfillment.domain;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.openlmis.fulfillment.domain.OrderStatus.FULFILLING;
import static org.openlmis.fulfillment.domain.OrderStatus.IN_ROUTE;
import static org.openlmis.fulfillment.domain.OrderStatus.ORDERED;
import static org.openlmis.fulfillment.domain.OrderStatus.READY_TO_PACK;
import static org.openlmis.fulfillment.domain.OrderStatus.RECEIVED;
import static org.openlmis.fulfillment.domain.OrderStatus.SHIPPED;
import static org.openlmis.fulfillment.domain.OrderStatus.TRANSFER_FAILED;
import org.junit.Test;
import org.openlmis.fulfillment.OrderDataBuilder;
public class OrderTest {
@Test
public void shouldCheckIfStatusIsOrdered() {
Order order = new OrderDataBuilder().withOrderedStatus().build();
assertTrue(order.isOrdered());
order = new OrderDataBuilder().withFulfillingStatus().build();
assertFalse(order.isOrdered());
}
@Test
public void shouldPrepareOrderForLocalFulfill() {
Order order = new OrderDataBuilder().build();
order.prepareToLocalFulfill();
assertEquals(ORDERED, order.getStatus());
}
@Test
public void shouldCheckIfOrderIsExternal() {
assertTrue(new OrderDataBuilder().withStatus(TRANSFER_FAILED).build().isExternal());
assertTrue(new OrderDataBuilder().withStatus(IN_ROUTE).build().isExternal());
assertTrue(new OrderDataBuilder().withStatus(READY_TO_PACK).build().isExternal());
assertFalse(new OrderDataBuilder().withStatus(ORDERED).build().isExternal());
assertFalse(new OrderDataBuilder().withStatus(FULFILLING).build().isExternal());
assertFalse(new OrderDataBuilder().withStatus(SHIPPED).build().isExternal());
assertFalse(new OrderDataBuilder().withStatus(RECEIVED).build().isExternal());
}
@Test
public void shouldCheckIfOrderCanBeShipped() {
Order order = new OrderDataBuilder().withOrderedStatus().build();
assertTrue(order.canBeFulfilled());
order = new OrderDataBuilder().withFulfillingStatus().build();
assertTrue(order.canBeFulfilled());
order.setStatus(IN_ROUTE);
assertFalse(order.canBeFulfilled());
order.setStatus(TRANSFER_FAILED);
assertFalse(order.canBeFulfilled());
order.setStatus(READY_TO_PACK);
assertFalse(order.canBeFulfilled());
order.setStatus(RECEIVED);
assertFalse(order.canBeFulfilled());
order.setStatus(SHIPPED);
assertFalse(order.canBeFulfilled());
}
} |
package com.kennyc.sample;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.kennyc.adapters.ArrayRecyclerAdapter;
import com.kennyc.adapters.BaseRecyclerAdapter;
import com.kennyc.adapters.MenuRecyclerAdapter;
import java.util.ArrayList;
import java.util.List;
public class RVActivity extends AppCompatActivity implements View.OnClickListener {
public static Intent createIntent(Context context, int type) {
return new Intent(context, RVActivity.class).putExtra("type", type);
}
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rv);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
List<String> data = new ArrayList<>(100);
for (int i = 0; i < 100; i++) {
data.add("Position " + i);
}
RecyclerView.Adapter adapter = null;
switch (getIntent().getIntExtra("type", 0)) {
case 0:
adapter = new ArrayRecyclerAdapter<>(this, android.R.layout.simple_list_item_1, data, this);
break;
case 1:
adapter = new CustomAdapter(this, data, this);
break;
case 2:
adapter = new MenuRecyclerAdapter(this, R.menu.test_menu, this);
break;
}
recyclerView.setAdapter(adapter);
}
@Override
public void onClick(View v) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter instanceof ArrayRecyclerAdapter) {
Object item = ((ArrayRecyclerAdapter) adapter).getItem(recyclerView.getChildAdapterPosition(v));
Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
} else if (adapter instanceof CustomAdapter) {
String item = ((CustomAdapter) adapter).getItem(recyclerView.getChildAdapterPosition(v));
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
} else {
MenuItem item = ((MenuRecyclerAdapter) adapter).getItem(recyclerView.getChildAdapterPosition(v));
Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
if (recyclerView.getAdapter() instanceof CustomAdapter) {
((CustomAdapter) recyclerView.getAdapter()).onDestroy();
}
super.onDestroy();
}
private static class CustomAdapter extends BaseRecyclerAdapter<String, CustomAdapter.VH> {
private View.OnClickListener listener;
public CustomAdapter(Context context, List<String> data, View.OnClickListener listener) {
super(context, data);
this.listener = listener;
}
@Override
public CustomAdapter.VH onCreateViewHolder(ViewGroup parent, int viewType) {
VH vh = new VH(inflateView(android.R.layout.simple_list_item_1, parent));
vh.textView.setOnClickListener(listener);
return vh;
}
@Override
public void onDestroy() {
super.onDestroy();
listener = null;
}
@Override
public void onBindViewHolder(CustomAdapter.VH holder, int position) {
holder.textView.setText(getItem(position));
}
public static class VH extends RecyclerView.ViewHolder {
TextView textView;
public VH(View view) {
super(view);
textView = (TextView) view;
}
}
}
} |
package net.hillsdon.reviki.wiki.renderer.creole;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.antlr.v4.runtime.ParserRuleContext;
import com.google.common.base.Optional;
import com.uwyn.jhighlight.renderer.XhtmlRendererFactory;
import net.hillsdon.reviki.vc.AttachmentHistory;
import net.hillsdon.reviki.vc.PageInfo;
import net.hillsdon.reviki.vc.PageStore;
import net.hillsdon.reviki.vc.PageStoreException;
import net.hillsdon.reviki.web.urls.URLOutputFilter;
import net.hillsdon.reviki.wiki.renderer.creole.ast.*;
import net.hillsdon.reviki.wiki.renderer.creole.Creole.*;
/**
* Visitor which walks the parse tree to build a more programmer-friendly AST.
* This also performs some non-standard rearrangement in order to replicate
* functionality from the old renderer.
*
* @author msw
*/
public class Visitor extends CreoleASTBuilder {
/** List of attachments on the page. */
private Collection<AttachmentHistory> _attachments = null;
public Visitor(final Optional<PageStore> store, final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) {
super(store, page, urlOutputFilter, linkHandler, imageHandler);
}
public Visitor(final PageStore store, final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) {
super(store, page, urlOutputFilter, linkHandler, imageHandler);
}
public Visitor(final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) {
super(page, urlOutputFilter, linkHandler, imageHandler);
}
/**
* If a paragraph starts with a sequence of blockable elements, separated by
* newlines, render them as blocks and the remaining text (if any) as a
* paragraph following this.
*
* @param paragraph The paragraph to expand out.
* @param reversed Whether the paragraph is reversed or not. If so, the final
* trailing paragraph has its chunks reversed, to ease re-ordering
* later.
* @return A list of blocks, which may just consist of the original paragraph.
*/
protected List<ASTNode> expandParagraph(final Paragraph paragraph, final boolean reversed) {
ASTNode inline = paragraph.getChildren().get(0);
List<ASTNode> chunks = inline.getChildren();
int numchunks = chunks.size();
// Drop empty inlines, as that means we've examined an entire paragraph.
if (numchunks == 0) {
return new ArrayList<ASTNode>();
}
ASTNode head = chunks.get(0);
String sep = (numchunks > 1) ? chunks.get(1).toXHTML() : "\r\n";
List<ASTNode> tail = (numchunks > 1) ? chunks.subList(1, numchunks) : new ArrayList<ASTNode>();
Paragraph rest = new Paragraph(new Inline(tail));
List<ASTNode> out = new ArrayList<ASTNode>();
// Drop leading whitespace
if (head.toXHTML().matches("^\r?\n$")) {
return expandParagraph(rest, reversed);
}
// Only continue if there is a hope of expanding it
if (head instanceof BlockableNode) {
// Check if we have a valid separator
ASTNode block = null;
if (sep == null || (!reversed && (sep.startsWith("\r\n") || sep.startsWith("\n")) || (reversed && sep.endsWith("\n")) || sep.startsWith("<br"))) {
block = ((BlockableNode) head).toBlock();
}
// Check if we have a match, and build the result list.
if (block != null) {
out.add(block);
out.addAll(expandParagraph(rest, reversed));
return out;
}
}
if (reversed) {
List<ASTNode> rchunks = new ArrayList<ASTNode>(inline.getChildren());
Collections.reverse(rchunks);
out.add(new Paragraph(new Inline(rchunks)));
}
else {
out.add(paragraph);
}
return out;
}
/**
* Render the root node, creole. creole contains zero or more block elements
* separated by linebreaks and paragraph breaks.
*
* The rendering behaviour is to render each block individually, and then
* display them sequentially in order.
*/
@Override
public ASTNode visitCreole(final CreoleContext ctx) {
List<ASTNode> blocks = new ArrayList<ASTNode>();
for (BlockContext btx : ctx.block()) {
ASTNode ren = visit(btx);
// If we have a paragraph, rip off initial and trailing inline code and
// macros.
if (ren instanceof Paragraph) {
List<ASTNode> expandedInit = expandParagraph((Paragraph) ren, false);
List<ASTNode> expandedTail = new ArrayList<ASTNode>();
// Handle trailing things by extracting the chunks of the final
// paragraph, reversing, extracting the prefix again, and then reversing
// the result.
if (expandedInit.size() > 0 && expandedInit.get(expandedInit.size() - 1) instanceof Paragraph) {
Paragraph paragraph = (Paragraph) expandedInit.get(expandedInit.size() - 1);
expandedInit.remove(paragraph);
List<ASTNode> chunks = new ArrayList<ASTNode>(paragraph.getChildren().get(0).getChildren());
Collections.reverse(chunks);
expandedTail = expandParagraph(new Paragraph(new Inline(chunks)), true);
Collections.reverse(expandedTail);
}
blocks.addAll(expandedInit);
blocks.addAll(expandedTail);
continue;
}
// Otherwise, just add the block to the list.
blocks.add(ren);
}
// Remove paragraphs just consisting of whitespace
List<ASTNode> blocksNonEmpty = new ArrayList<ASTNode>();
for (ASTNode block : blocks) {
if (block != null && !(block instanceof Paragraph && ((Paragraph)block).innerXHTML().trim().equals(""))) {
blocksNonEmpty.add(block);
}
}
return new Page(blocksNonEmpty);
}
/**
* Render a heading node. This consists of a prefix, the length of which will
* tell us the heading level, and some content.
*/
@Override
public ASTNode visitHeading(final HeadingContext ctx) {
if (ctx.inline() == null) {
return new Plaintext(ctx.HSt().getText());
}
return new Heading(ctx.HSt().getText().length(), visit(ctx.inline()));
}
/**
* Render a paragraph node. This consists of a single inline element.
*/
@Override
public ASTNode visitParagraph(final ParagraphContext ctx) {
return new Paragraph(visit(ctx.inline()));
}
/**
* Render an inline node. This consists of a list of chunks of smaller markup
* units, which are displayed in order.
*/
@Override
public ASTNode visitInline(final InlineContext ctx) {
List<ASTNode> chunks = new ArrayList<ASTNode>();
// Merge adjacent Any nodes into long Plaintext nodes, to give a more useful
// AST.
ASTNode last = null;
for (InlinestepContext itx : ctx.inlinestep()) {
ASTNode rendered = visit(itx);
if (last == null) {
last = rendered;
}
else {
if (last instanceof Plaintext && rendered instanceof Plaintext) {
last = new Plaintext(((Plaintext) last).getText() + ((Plaintext) rendered).getText());
}
else {
chunks.add(last);
last = rendered;
}
}
}
if (last != null) {
chunks.add(last);
}
return new Inline(chunks);
}
/**
* Render an any node. This consists of some plaintext, which is escaped and
* displayed with no further processing.
*/
@Override
public ASTNode visitAny(final AnyContext ctx) {
return new Plaintext(ctx.getText());
}
/**
* Render a WikiWords link.
*/
@Override
public ASTNode visitWikiwlink(final WikiwlinkContext ctx) {
return new Link(ctx.getText(), ctx.getText(), page(), urlOutputFilter(), linkHandler());
}
/**
* Render an attachment link. If the attachment doesn't exist, it is rendered
* in plain text.
*/
@Override
public ASTNode visitAttachment(final AttachmentContext ctx) {
if (store().isPresent()) {
// Check if the attachment exists
try {
if (_attachments == null) {
_attachments = unsafeStore().attachments(page());
}
for (AttachmentHistory attachment : _attachments) {
// Skip deleted attachments
if (attachment.isAttachmentDeleted()) {
continue;
}
// Render the link if the name matches
if (attachment.getName().equals(ctx.getText())) {
return new Link(ctx.getText(), ctx.getText(), page(), urlOutputFilter(), linkHandler());
}
}
}
catch (PageStoreException e) {
}
}
return new Plaintext(ctx.getText());
}
/**
* Render a raw URL link.
*/
@Override
public ASTNode visitRawlink(final RawlinkContext ctx) {
return new Link(ctx.getText(), ctx.getText(), page(), urlOutputFilter(), linkHandler());
}
/**
* Render bold nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitBold(final BoldContext ctx) {
return renderInlineMarkup(Bold.class, "**", "BEnd", ctx.BEnd(), ctx.inline());
}
/**
* Render italic nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitItalic(final ItalicContext ctx) {
return renderInlineMarkup(Italic.class, "//", "IEnd", ctx.IEnd(), ctx.inline());
}
/**
* Render strikethrough nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitSthrough(final SthroughContext ctx) {
return renderInlineMarkup(Strikethrough.class, "--", "SEnd", ctx.SEnd(), ctx.inline());
}
/**
* Render a link node with no title.
*/
@Override
public ASTNode visitLink(final LinkContext ctx) {
return new Link(ctx.InLink().getText(), ctx.InLink().getText(), page(), urlOutputFilter(), linkHandler());
}
/**
* Render a link node with a title.
*/
@Override
public ASTNode visitTitlelink(final TitlelinkContext ctx) {
String target = (ctx.InLink() == null) ? "" : ctx.InLink().getText();
String title = (ctx.InLinkEnd() == null) ? target : ctx.InLinkEnd().getText();
return new Link(target, title, page(), urlOutputFilter(), linkHandler());
}
/**
* Render an image node.
*/
@Override
public ASTNode visitImglink(final ImglinkContext ctx) {
String target = (ctx.InLink() == null) ? "" : ctx.InLink().getText();
String title = (ctx.InLinkEnd() == null) ? target : ctx.InLinkEnd().getText();
return new Image(target, title, page(), urlOutputFilter(), imageHandler());
}
/**
* Render an image without a title.
*/
@Override
public ASTNode visitSimpleimg(final SimpleimgContext ctx) {
return new Image(ctx.InLink().getText(), ctx.InLink().getText(), page(), urlOutputFilter(), imageHandler());
}
/**
* Render an inline nowiki node. Due to how the lexer works, the contents
* include the ending symbol, which must be chopped off.
*
* TODO: Improve the tokensiation of this.
*/
@Override
public ASTNode visitPreformat(final PreformatContext ctx) {
return renderInlineCode(ctx.EndNoWikiInline(), "}}}");
}
/**
* Render a syntax-highlighted CPP block. This has the same tokenisation
* problem as mentioned in {@link #visitPreformat}.
*/
@Override
public ASTNode visitInlinecpp(final InlinecppContext ctx) {
return renderInlineCode(ctx.EndCppInline(), "[</c++>]", XhtmlRendererFactory.CPLUSPLUS);
}
/**
* Render a block of literal, unescaped, HTML.
*/
@Override
public ASTNode visitInlinehtml(final InlinehtmlContext ctx) {
String code = ctx.EndHtmlInline().getText();
return new Raw(code.substring(0, code.length() - "[</html>]".length()));
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode}. */
@Override
public ASTNode visitInlinejava(final InlinejavaContext ctx) {
return renderInlineCode(ctx.EndJavaInline(), "[</java>]", XhtmlRendererFactory.JAVA);
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode}. */
@Override
public ASTNode visitInlinexhtml(final InlinexhtmlContext ctx) {
return renderInlineCode(ctx.EndXhtmlInline(), "[</xhtml>]", XhtmlRendererFactory.XHTML);
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode}. */
@Override
public ASTNode visitInlinexml(final InlinexmlContext ctx) {
return renderInlineCode(ctx.EndXmlInline(), "[</xml>]", XhtmlRendererFactory.XML);
}
/**
* Render a literal linebreak node.
*/
@Override
public ASTNode visitLinebreak(final LinebreakContext ctx) {
return new Linebreak();
}
/**
* Render a horizontal rule node.
*/
@Override
public ASTNode visitHrule(final HruleContext ctx) {
return new HorizontalRule();
}
/**
* Render an ordered list. List rendering is a bit of a mess at the moment,
* but it basically works like this:
*
* - Lists have a root node, which contains level 1 elements.
*
* - There are levels 1 through 5.
*
* - Each level (other than 5) may have child list elements.
*
* - Each level (other than root) may also have some content, which can be a
* new list (ordered or unordered), or inline text.
*
* The root list node is rendered by displaying all level 1 entities in
* sequence, where level n entities are rendered by displaying their content
* and then any children they have.
*
* TODO: Figure out how to have arbitrarily-nested lists.
*/
@Override
public ASTNode visitOlist(final OlistContext ctx) {
return renderList(ListType.Ordered, ctx.olist1());
}
/** Helper functions for lists. */
protected enum ListCtxType {
List2Context, List3Context, List4Context, List5Context, List6Context, List7Context, List8Context, List9Context, List10Context
};
protected ParserRuleContext olist(final ParserRuleContext ctx) {
switch (ListCtxType.valueOf(ctx.getClass().getSimpleName())) {
case List2Context:
return ((List2Context) ctx).olist2();
case List3Context:
return ((List3Context) ctx).olist3();
case List4Context:
return ((List4Context) ctx).olist4();
case List5Context:
return ((List5Context) ctx).olist5();
case List6Context:
return ((List6Context) ctx).olist6();
case List7Context:
return ((List7Context) ctx).olist7();
case List8Context:
return ((List8Context) ctx).olist8();
case List9Context:
return ((List9Context) ctx).olist9();
case List10Context:
return ((List10Context) ctx).olist10();
default:
throw new RuntimeException("Unknown list context type");
}
}
protected ParserRuleContext ulist(final ParserRuleContext ctx) {
switch (ListCtxType.valueOf(ctx.getClass().getSimpleName())) {
case List2Context:
return ((List2Context) ctx).ulist2();
case List3Context:
return ((List3Context) ctx).ulist3();
case List4Context:
return ((List4Context) ctx).ulist4();
case List5Context:
return ((List5Context) ctx).ulist5();
case List6Context:
return ((List6Context) ctx).ulist6();
case List7Context:
return ((List7Context) ctx).ulist7();
case List8Context:
return ((List8Context) ctx).ulist8();
case List9Context:
return ((List9Context) ctx).ulist9();
case List10Context:
return ((List10Context) ctx).ulist10();
default:
throw new RuntimeException("Unknown list context type");
}
}
protected ASTNode list(final List<? extends ParserRuleContext> ltxs, final InListContext inner) {
List<ListItemContext> children = new ArrayList<ListItemContext>();
if (ltxs != null) {
for (ParserRuleContext ltx : ltxs) {
children.add(new ListItemContext(olist(ltx), ulist(ltx)));
}
}
List<ParserRuleContext> inners = new ArrayList<ParserRuleContext>();
inners.add((ParserRuleContext) inner.olist());
inners.add((ParserRuleContext) inner.ulist());
inners.add((ParserRuleContext) inner.inline());
return renderListItem(children, inners);
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist1(final Olist1Context ctx) {
return list(ctx.list2(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist2(final Olist2Context ctx) {
return list(ctx.list3(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist3(final Olist3Context ctx) {
return list(ctx.list4(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist4(final Olist4Context ctx) {
return list(ctx.list5(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist5(final Olist5Context ctx) {
return list(ctx.list6(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist6(final Olist6Context ctx) {
return list(ctx.list7(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist7(final Olist7Context ctx) {
return list(ctx.list8(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist8(final Olist8Context ctx) {
return list(ctx.list9(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist9(final Olist9Context ctx) {
return list(ctx.list10(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitOlist10(final Olist10Context ctx) {
return list(null, ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist(final UlistContext ctx) {
return renderList(ListType.Unordered, ctx.ulist1());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist1(final Ulist1Context ctx) {
return list(ctx.list2(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist2(final Ulist2Context ctx) {
return list(ctx.list3(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist3(final Ulist3Context ctx) {
return list(ctx.list4(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist4(final Ulist4Context ctx) {
return list(ctx.list5(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist5(final Ulist5Context ctx) {
return list(ctx.list6(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist6(final Ulist6Context ctx) {
return list(ctx.list7(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist7(final Ulist7Context ctx) {
return list(ctx.list8(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist8(final Ulist8Context ctx) {
return list(ctx.list9(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist9(final Ulist9Context ctx) {
return list(ctx.list10(), ctx.inList());
}
/** See {@link #visitOlist}. */
@Override
public ASTNode visitUlist10(final Ulist10Context ctx) {
return list(null, ctx.inList());
}
/**
* Render a NoWiki block node. This has the same tokenisation problem as
* mentioned in {@link #visitPreformat}.
*/
@Override
public ASTNode visitNowiki(final NowikiContext ctx) {
return renderBlockCode(ctx.EndNoWikiBlock(), "}}}");
}
/**
* Like {@link #visitInlinecpp}, but for blocks.
*/
@Override
public ASTNode visitCpp(final CppContext ctx) {
return renderBlockCode(ctx.EndCppBlock(), "[</c++>]", XhtmlRendererFactory.CPLUSPLUS);
}
/**
* Render a block of literal, unescaped, HTML.
*/
@Override
public ASTNode visitHtml(final HtmlContext ctx) {
String code = ctx.EndHtmlBlock().getText();
return new Raw(code.substring(0, code.length() - "[</html>]".length()));
}
/** See {@link #visitCpp} and {@link #renderBlockCode}. */
@Override
public ASTNode visitJava(final JavaContext ctx) {
return renderBlockCode(ctx.EndJavaBlock(), "[</java>]", XhtmlRendererFactory.JAVA);
}
/** See {@link #visitCpp} and {@link #renderBlockCode}. */
@Override
public ASTNode visitXhtml(final XhtmlContext ctx) {
return renderBlockCode(ctx.EndXhtmlBlock(), "[</xhtml>]", XhtmlRendererFactory.XHTML);
}
/** See {@link #visitCpp} and {@link #renderBlockCode}. */
@Override
public ASTNode visitXml(final XmlContext ctx) {
return renderBlockCode(ctx.EndXmlBlock(), "[</xml>]", XhtmlRendererFactory.XML);
}
/**
* Render a table node. This consists of rendering all rows in sequence.
*/
@Override
public ASTNode visitTable(final TableContext ctx) {
List<ASTNode> rows = new ArrayList<ASTNode>();
for (TrowContext rtx : ctx.trow()) {
rows.add(visit(rtx));
}
return new Table(rows);
}
/**
* Render a table row. A table row consists of a number of cells, and a
* possible trailing separator.
*/
@Override
public ASTNode visitTrow(final TrowContext ctx) {
List<ASTNode> cells = new ArrayList<ASTNode>();
for (TcellContext rtx : ctx.tcell()) {
cells.add(visit(rtx));
}
return new TableRow(cells);
}
/**
* Render a table heading cell.
*/
@Override
public ASTNode visitTh(final ThContext ctx) {
return new TableHeaderCell((ctx.inline() != null) ? visit(ctx.inline()) : new Plaintext(""));
}
/**
* Render a table cell.
*/
@Override
public ASTNode visitTd(final TdContext ctx) {
return new TableCell((ctx.inline() != null) ? visit(ctx.inline()) : new Plaintext(""));
}
/**
* Render a macro.
*/
@Override
public ASTNode visitMacro(final MacroContext ctx) {
// If there are no arguments, it's not a macro
if (ctx.MacroEndNoArgs() != null) {
return new Plaintext("<<" + ctx.MacroName().getText() + ">>");
}
return new MacroNode(ctx.MacroName().getText(), cutOffEndTag(ctx.MacroEnd(), ">>"), page(), this);
}
} |
package dr.app.beagle.evomodel.branchmodel;
import java.util.ArrayList;
import java.util.List;
import dr.app.beagle.evomodel.substmodel.SubstitutionModel;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.util.Author;
import dr.util.Citable;
import dr.util.Citation;
/**
* @author Filip Bielejec
* @author Andrew Rambaut
* @author Marc A. Suchard
* @version $Id$
*/
@SuppressWarnings("serial")
public class EpochBranchModel extends AbstractModel implements BranchModel, Citable {
public static final String EPOCH_BRANCH_MODEL = "EpochBranchModel";
public EpochBranchModel(TreeModel tree,
List<SubstitutionModel> substitutionModels,
Parameter epochTimes) {
super(EPOCH_BRANCH_MODEL);
this.substitutionModels = substitutionModels;
if (substitutionModels == null || substitutionModels.size() == 0) {
throw new IllegalArgumentException("EpochBranchModel must be provided with at least one substitution model");
}
this.epochTimes = epochTimes;
this.tree = tree;
for (SubstitutionModel model : substitutionModels) {
addModel(model);
}
addModel(tree);
addVariable(epochTimes);
}// END: Constructor
@Override
public Mapping getBranchModelMapping(NodeRef node) {
int nModels = substitutionModels.size();
int lastTransitionTime = nModels - 2;
double[] transitionTimes = epochTimes.getParameterValues();
double parentHeight = tree.getNodeHeight(tree.getParent(node));
double nodeHeight = tree.getNodeHeight(node);
double branchLength = tree.getBranchLength(node);
List<Double> weightList = new ArrayList<Double>();
List<Integer> orderList = new ArrayList<Integer>();
if (parentHeight <= transitionTimes[0]) {
weightList.add( branchLength );
orderList.add(0);
} else {
// first case: 0-th transition time
if (nodeHeight < transitionTimes[0] && transitionTimes[0] <= parentHeight) {
weightList.add( transitionTimes[0] - nodeHeight );
orderList.add(0);
} else {
// do nothing
}// END: 0-th model check
// second case: i to i+1 transition times
for (int i = 1; i <= lastTransitionTime; i++) {
if (nodeHeight < transitionTimes[i]) {
if (parentHeight <= transitionTimes[i] && transitionTimes[i - 1] < nodeHeight) {
weightList.add( branchLength );
orderList.add(i);
} else {
double startTime = Math.max(nodeHeight, transitionTimes[i - 1]);
double endTime = Math.min(parentHeight, transitionTimes[i]);
if (endTime >= startTime) {
weightList.add( endTime - startTime );
orderList.add(i);
}// END: negative weights check
}// END: full branch in middle epoch check
}// END: i-th model check
}// END: i loop
// third case: last transition time
if (parentHeight >= transitionTimes[lastTransitionTime] && transitionTimes[lastTransitionTime] > nodeHeight) {
weightList.add( parentHeight - transitionTimes[lastTransitionTime] );
orderList.add(nModels - 1);
} else if (nodeHeight > transitionTimes[lastTransitionTime]) {
weightList.add( branchLength );
orderList.add(nModels - 1);
} else {
// nothing to add
}// END: last transition time check
}// END: if branch below first transition time bail out
final int[] order = new int[orderList.size()];
final double[] weights = new double[weightList.size()];
for (int i = 0; i < orderList.size(); i++) {
order[i] = orderList.get(i);
weights[i] = weightList.get(i);
}
return new Mapping() {
@Override
public int[] getOrder() {
return order;
}
@Override
public double[] getWeights() {
return weights;
}
};
}// END: getBranchModelMapping
@Override
public boolean requiresMatrixConvolution() {
return true;
}
@Override
public List<SubstitutionModel> getSubstitutionModels() {
return substitutionModels;
}
@Override
public SubstitutionModel getRootSubstitutionModel() {
return substitutionModels.get(substitutionModels.size() - 1);
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
fireModelChanged();
}// END: handleModelChangedEvent
@SuppressWarnings("rawtypes")
protected void handleVariableChangedEvent(Variable variable, int index,
Parameter.ChangeType type) {
}// END: handleVariableChangedEvent
protected void storeState() {
}// END: storeState
protected void restoreState() {
}// END: restoreState
protected void acceptState() {
}// END: acceptState
/**
* @return a list of citations associated with this object
*/
public List<Citation> getCitations() {
List<Citation> citations = new ArrayList<Citation>();
citations.add(new Citation(new Author[]{new Author("F", "Bielejec"),
new Author("P", "Lemey"), new Author("G", "Baele"), new Author("A", "Rambaut"),
new Author("MA", "Suchard")}, Citation.Status.IN_PREPARATION));
return citations;
}// END: getCitations
private final TreeModel tree;
private final List<SubstitutionModel> substitutionModels;
private final Parameter epochTimes;
}// END: class |
package mobi.hsz.idea.gitignore.util;
import mobi.hsz.idea.gitignore.Common;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherUtilTest extends Common<MatcherUtil> {
@Test
public void testMatch() {
final Pattern pattern = Pattern.compile("foo");
final MatcherUtil util = new MatcherUtil();
assertFalse(util.match(null, null));
assertFalse(util.match(null, "foo"));
assertFalse(util.match(pattern, null));
assertFalse(util.match(pattern, "fo"));
assertTrue(util.match(pattern, "foo"));
assertTrue(util.match(pattern, "xfooy"));
}
@Test
public void testMatchAllParts() {
final String[] partsA = new String[]{"foo"};
final String[] partsB = new String[]{"foo", "bar"};
assertFalse(MatcherUtil.matchAllParts(null, null));
assertFalse(MatcherUtil.matchAllParts(null, "foo"));
assertFalse(MatcherUtil.matchAllParts(partsA, null));
assertFalse(MatcherUtil.matchAllParts(partsA, "fo"));
assertTrue(MatcherUtil.matchAllParts(partsA, "foo"));
assertTrue(MatcherUtil.matchAllParts(partsA, "xfooy"));
assertFalse(MatcherUtil.matchAllParts(partsB, "xfooxba"));
assertTrue(MatcherUtil.matchAllParts(partsB, "xfooxbar"));
}
@Test
public void testMatchAnyPart() {
final String[] partsA = new String[]{"foo"};
final String[] partsB = new String[]{"foo", "bar"};
assertFalse(MatcherUtil.matchAnyPart(null, null));
assertFalse(MatcherUtil.matchAnyPart(null, "foo"));
assertFalse(MatcherUtil.matchAnyPart(partsA, null));
assertFalse(MatcherUtil.matchAnyPart(partsA, "fo"));
assertTrue(MatcherUtil.matchAnyPart(partsA, "foo"));
assertTrue(MatcherUtil.matchAnyPart(partsA, "xfooy"));
assertTrue(MatcherUtil.matchAnyPart(partsB, "xfooxba"));
assertTrue(MatcherUtil.matchAnyPart(partsB, "xfooxbar"));
}
@Test
public void testGetParts() {
Pattern pattern = Pattern.compile("foo[ba]rbuz.*hi");
assertEquals(MatcherUtil.getParts((Pattern) null).length, 0);
assertEquals(MatcherUtil.getParts((Matcher) null).length, 0);
assertEquals(MatcherUtil.getParts(pattern).length, 2);
assertEquals(MatcherUtil.getParts(pattern.matcher("")).length, 2);
pattern = Pattern.compile("$$_!@[fd]");
assertEquals(MatcherUtil.getParts(pattern).length, 0);
assertEquals(MatcherUtil.getParts(pattern.matcher("")).length, 0);
}
} |
package dr.app.beauti.traitspanel;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.TraitGuesser;
import dr.app.beauti.util.PanelUtils;
import dr.app.beauti.*;
import dr.evolution.util.*;
import dr.gui.table.TableSorter;
import org.virion.jam.framework.Exportable;
import org.virion.jam.table.HeaderRenderer;
import org.virion.jam.table.TableEditorStopper;
import org.virion.jam.table.TableRenderer;
import org.virion.jam.panels.ActionPanel;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* @author Andrew Rambaut
* @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $
*/
public class TraitsPanel extends BeautiPanel implements Exportable {
private static final long serialVersionUID = 5283922195494563924L;
private final JTable traitsTable;
private final TraitsTableModel traitsTableModel;
private final JTable dataTable;
private final DataTableModel dataTableModel;
private final ClearTraitAction clearTraitAction = new ClearTraitAction();
private final GuessLocationsAction guessLocationsAction = new GuessLocationsAction();
private final BeautiFrame frame;
private BeautiOptions options = null;
private String selectedTrait = null;
private CreateTraitDialog createTraitDialog = null;
private GuessTraitDialog guessTraitDialog = null;
public TraitsPanel(BeautiFrame parent, Action importTraitsAction) {
this.frame = parent;
traitsTableModel = new TraitsTableModel();
TableSorter sorter = new TableSorter(traitsTableModel);
traitsTable = new JTable(sorter);
sorter.setTableHeader(traitsTable.getTableHeader());
traitsTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
traitsTable.getColumnModel().getColumn(0).setPreferredWidth(80);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable);
traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
traitSelectionChanged();
}
});
JScrollPane scrollPane1 = new JScrollPane(traitsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setOpaque(false);
dataTableModel = new DataTableModel();
sorter = new TableSorter(dataTableModel);
dataTable = new JTable(sorter);
sorter.setTableHeader(dataTable.getTableHeader());
dataTable.getTableHeader().setReorderingAllowed(false);
dataTable.getTableHeader().setDefaultRenderer(
new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setPreferredWidth(80);
TableColumn col = dataTable.getColumnModel().getColumn(1);
ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer();
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable);
dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
// traitSelectionChanged();
}
});
JScrollPane scrollPane2 = new JScrollPane(dataTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setOpaque(false);
JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
toolBar1.setOpaque(false);
toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
JButton button = new JButton(guessLocationsAction);
PanelUtils.setupComponent(button);
toolBar1.add(button);
button = new JButton(clearTraitAction);
PanelUtils.setupComponent(button);
toolBar1.add(button);
// toolBar1.add(new JToolBar.Separator(new Dimension(12, 12)));
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addTraitAction);
actionPanel1.setRemoveAction(removeTraitAction);
removeTraitAction.setEnabled(false);
JToolBar toolBar2 = new JToolBar();
toolBar2.setFloatable(false);
toolBar2.setOpaque(false);
toolBar2.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
button = new JButton(importTraitsAction);
PanelUtils.setupComponent(button);
toolBar2.add(button);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(toolBar2, BorderLayout.NORTH);
panel1.add(scrollPane1, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
panel2.add(toolBar1, BorderLayout.NORTH);
panel2.add(scrollPane2, BorderLayout.CENTER);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
panel1, panel2);
splitPane.setDividerLocation(240);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(splitPane, BorderLayout.CENTER);
}
public void setOptions(BeautiOptions options) {
this.options = options;
int selRow = traitsTable.getSelectedRow();
traitsTableModel.fireTableDataChanged();
if (selRow < 0) {
selRow = 0;
}
traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
if (selectedTrait == null) {
traitsTable.getSelectionModel().setSelectionInterval(0, 0);
}
// traitsTableModel.fireTableDataChanged();
dataTableModel.fireTableDataChanged();
validate();
repaint();
}
public void getOptions(BeautiOptions options) {
int selRow = traitsTable.getSelectedRow();
if (selRow >= 0 && options.selecetedTraits.size() > 0) {
selectedTrait = options.selecetedTraits.get(selRow);
}
// options.datesUnits = unitsCombo.getSelectedIndex();
// options.datesDirection = directionCombo.getSelectedIndex();
}
public JComponent getExportableComponent() {
return dataTable;
}
private void fireTraitsChanged() {
frame.setDirty();
}
private void traitSelectionChanged() {
int selRow = traitsTable.getSelectedRow();
if (selRow >= 0 && options.selecetedTraits.size() > 0) {
selectedTrait = options.selecetedTraits.get(selRow);
removeTraitAction.setEnabled(true);
} else {
selectedTrait = null;
removeTraitAction.setEnabled(false);
}
dataTableModel.fireTableDataChanged();
}
public void clearTrait() {
// for (int i = 0; i < options.taxonList.getTaxonCount(); i++) {
// java.util.Date origin = new java.util.Date(0);
// double d = 0.0;
// Date date = Date.createTimeSinceOrigin(d, Units.Type.YEARS, origin);
// options.taxonList.getTaxon(i).setAttribute("date", date);
// // adjust the dates to the current timescale...
// timeScaleChanged();
dataTableModel.fireTableDataChanged();
}
public void guessTrait() {
if( options.taxonList != null ) { // validation of check empty taxonList
TraitGuesser guesser = options.traitGuesser;
if (guessTraitDialog == null) {
guessTraitDialog = new GuessTraitDialog(frame, guesser);
}
int result = guessTraitDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
guesser.guessTrait = true; // ?? no use?
guessTraitDialog.setupGuesser();
try {
guesser.guessTrait(options);
switch (guesser.traitAnalysisType) {
case TRAIT_SPECIES :
addTrait(TraitGuesser.Traits.TRAIT_SPECIES.toString(), guesser.traitType);
frame.setupSpeciesAnalysis();
break;
default:
throw new IllegalArgumentException("unknown trait selected");
}
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
}
dataTableModel.fireTableDataChanged();
frame.setDirty();
} else {
JOptionPane.showMessageDialog(this, "No taxa loaded yet, please import Alignment file!",
"No taxa loaded", JOptionPane.ERROR_MESSAGE);
}
}
private void addTrait() {
if (createTraitDialog == null) {
createTraitDialog = new CreateTraitDialog(frame);
}
int result = createTraitDialog.showDialog(options);
if (result != JOptionPane.CANCEL_OPTION) {
String name = createTraitDialog.getName();
TraitGuesser.TraitType type = createTraitDialog.getType();
if (!options.selecetedTraits.contains(name)) {
// The createTraitDialog will have already checked if the
// user is overwriting an existing trait
options.selecetedTraits.add(name);
}
options.traitTypes.put(name, type);
traitsTableModel.fireTableDataChanged();
int row = options.selecetedTraits.size() - 1;
traitsTable.getSelectionModel().setSelectionInterval(row, row);
}
fireTraitsChanged();
}
private void addTrait(String traitName, TraitGuesser.TraitType traitType) {
if (!options.selecetedTraits.contains(traitName)) {
options.selecetedTraits.add(traitName);
}
options.traitTypes.put(traitName, traitType);
traitsTableModel.fireTableDataChanged();
int row = options.selecetedTraits.size() - 1;
traitsTable.getSelectionModel().setSelectionInterval(row, row);
}
private void removeTrait() {
int selRow = traitsTable.getSelectedRow();
String trait = options.selecetedTraits.get(selRow);
options.selecetedTraits.remove(trait);
options.traitTypes.remove(trait);
if (trait.equals(TraitGuesser.Traits.TRAIT_SPECIES.toString())) {
frame.removeSepciesAnalysisSetup();
}
traitsTableModel.fireTableDataChanged();
fireTraitsChanged();
}
public class ClearTraitAction extends AbstractAction {
private static final long serialVersionUID = -7281309694753868635L;
public ClearTraitAction() {
super("Clear trait values");
setToolTipText("Use this tool to remove trait values from each taxon");
}
public void actionPerformed(ActionEvent ae) {
clearTrait();
}
}
public class GuessLocationsAction extends AbstractAction {
private static final long serialVersionUID = 8514706149822252033L;
public GuessLocationsAction() {
super("Guess trait values");
setToolTipText("Use this tool to guess the trait values from the taxon labels");
}
public void actionPerformed(ActionEvent ae) {
guessTrait();
}
}
AbstractAction addTraitAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
addTrait();
}
};
AbstractAction removeTraitAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
removeTrait();
}
};
class TraitsTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Trait", "Type"};
public TraitsTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.selecetedTraits == null) return 0;
return options.selecetedTraits.size();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.selecetedTraits.get(row);
case 1:
return options.traitTypes.get(options.selecetedTraits.get(row));
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
if (col == 0) {
options.selecetedTraits.set(row, aValue.toString());
} else if (col == 1) {
options.traitTypes.put(options.selecetedTraits.get(row), (TraitGuesser.TraitType)aValue);
}
}
public boolean isCellEditable(int row, int col) {
// if (col == 0) return true;
return false;
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
class DataTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Taxon", "Value"};
public DataTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.taxonList == null) return 0;
return options.taxonList.getTaxonCount();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.taxonList.getTaxonId(row);
case 1:
Object value = null;
if (selectedTrait != null) {
value = options.taxonList.getTaxon(row).getAttribute(selectedTrait);
}
if (value != null) {
return value;
} else {
return "-";
}
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
if (col == 1) {
// Location location = options.taxonList.getTaxon(row).getLocation();
// if (location != null) {
// options.taxonList.getTaxon(row).setLocation(location);
if (selectedTrait != null) {
options.taxonList.getTaxon(row).setAttribute(selectedTrait, aValue);
}
}
}
public boolean isCellEditable(int row, int col) {
if (col == 1) {
Object t = options.taxonList.getTaxon(row).getAttribute(selectedTrait);
return (t != null);
} else {
return false;
}
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
} |
package net.hillsdon.reviki.wiki.renderer.creole;
import java.util.ArrayList;
import java.util.List;
import org.antlr.v4.runtime.ParserRuleContext;
import com.uwyn.jhighlight.renderer.XhtmlRendererFactory;
import net.hillsdon.reviki.vc.PageInfo;
import net.hillsdon.reviki.web.urls.URLOutputFilter;
import net.hillsdon.reviki.wiki.renderer.creole.ast.*;
import net.hillsdon.reviki.wiki.renderer.creole.Creole.*;
/**
* Visitor which walks the parse tree to build a more programmer-friendly AST.
* This also performs some non-standard rearrangement in order to replicate
* functionality from the old renderer.
*
* @author msw
*/
public class Visitor extends CreoleASTBuilder {
public Visitor(PageInfo page, URLOutputFilter urlOutputFilter, LinkPartsHandler linkHandler, LinkPartsHandler imageHandler) {
super(page, urlOutputFilter, linkHandler, imageHandler);
}
/**
* Render the root node, creole. creole contains zero or more block elements
* separated by linebreaks and paragraph breaks.
*
* The rendering behaviour is to render each block individually, and then
* display them sequentially in order.
*/
@Override
public ASTNode visitCreole(CreoleContext ctx) {
List<ASTNode> blocks = new ArrayList<ASTNode>();
for (BlockContext btx : ctx.block()) {
ASTNode ren = visit(btx);
if (ren != null) {
blocks.add(ren);
}
}
return new Page(blocks);
}
/**
* Render a heading node. This consists of a prefix, the length of which will
* tell us the heading level, and some content.
*/
@Override
public ASTNode visitHeading(HeadingContext ctx) {
return new Heading(ctx.HSt().getText().length(), visit(ctx.inline()));
}
/**
* Render a paragraph node. This consists of a single inline element. Leading
* and trailing newlines are stripped, and if the paragraph consists solely of
* an inline nowiki line, it is instead rendered as a nowiki block, to
* replicate old behaviour.
*/
@Override
public ASTNode visitParagraph(ParagraphContext ctx) {
ASTNode body = visit(ctx.inline());
ASTNode inner = body;
// Drop leading and trailing newlines (TODO: Figure out how to do this in
// the grammar, along with all the other stuff)
if (body instanceof Inline) {
int children = body.getChildren().size();
if (children > 0 && body.getChildren().get(0).toXHTML().equals("\n")) {
body = new Inline(body.getChildren().subList(1, children));
children
}
if (children > 0 && body.getChildren().get(children - 1).toXHTML().equals("\n")) {
body = new Inline(body.getChildren().subList(0, children - 1));
}
}
// If a paragraph contains nothing but an inline nowiki element, render that
// as a block nowiki element. Not quite to spec, but replicates old
// behaviour.
if (body instanceof Inline && body.getChildren().size() == 1) {
inner = body.getChildren().get(0);
}
if (inner instanceof InlineCode) {
return ((InlineCode) inner).toBlock();
}
// If a paragraph contains only a macro node, remove the enclosing
// paragraph.
if (inner instanceof MacroNode) {
return inner;
}
return new Paragraph(body);
}
/**
* Render an inline node. This consists of a list of chunks of smaller markup
* units, which are displayed in order.
*/
@Override
public ASTNode visitInline(InlineContext ctx) {
List<ASTNode> chunks = new ArrayList<ASTNode>();
// Merge adjacent Any nodes into long Plaintext nodes, to give a more useful
// AST.
ASTNode last = null;
for (InlinestepContext itx : ctx.inlinestep()) {
ASTNode rendered = visit(itx);
if (last == null) {
last = rendered;
}
else {
if (last instanceof Plaintext && rendered instanceof Plaintext) {
last = new Plaintext(((Plaintext)last).getText() + ((Plaintext)rendered).getText());
}
else {
chunks.add(last);
last = rendered;
}
}
}
if (last != null) {
chunks.add(last);
}
return new Inline(chunks);
}
/**
* Render an any node. This consists of some plaintext, which is escaped and
* displayed with no further processing.
*/
@Override
public ASTNode visitAny(AnyContext ctx) {
return new Plaintext(ctx.getText());
}
/**
* Render a WikiWords link.
*/
@Override
public ASTNode visitWikiwlink(WikiwlinkContext ctx) {
return new Link(ctx.getText(), ctx.getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render an external bugtracker link
*/
@Override
public ASTNode visitEbuglink(EbuglinkContext ctx) {
String url = String.format(CreoleRenderer.EXTERNAL_BUG_URL, ctx.BugNum().getText());
return new Link(url, ctx.getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render an internal bugtracker link
*/
@Override
public ASTNode visitIbuglink(IbuglinkContext ctx) {
String url = String.format(CreoleRenderer.INTERNAL_BUG_URL, ctx.BugNum().getText());
return new Link(url, ctx.getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render a raw URL link.
*/
@Override
public ASTNode visitRawlink(RawlinkContext ctx) {
return new Link(ctx.getText(), ctx.getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render bold nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitBold(BoldContext ctx) {
return renderInlineMarkup(Bold.class, "**", "BEnd", ctx.BEnd(), ctx.inline());
}
/**
* Render italic nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitItalic(ItalicContext ctx) {
return renderInlineMarkup(Italic.class, "//", "IEnd", ctx.IEnd(), ctx.inline());
}
/**
* Render strikethrough nodes, with error recovery by {@link #renderInline}.
*/
@Override
public ASTNode visitSthrough(SthroughContext ctx) {
return renderInlineMarkup(Strikethrough.class, "--", "SEnd", ctx.SEnd(), ctx.inline());
}
/**
* Render a link node with no title.
*/
@Override
public ASTNode visitLink(LinkContext ctx) {
return new Link(ctx.InLink().getText(), ctx.InLink().getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render a link node with a title.
*/
@Override
public ASTNode visitTitlelink(TitlelinkContext ctx) {
return new Link(ctx.InLink(0).getText(), ctx.InLink(1).getText(), page, urlOutputFilter, linkHandler);
}
/**
* Render an image node.
*/
@Override
public ASTNode visitImglink(ImglinkContext ctx) {
return new Image(ctx.InLink(0).getText(), ctx.InLink(1).getText(), page, urlOutputFilter, imageHandler);
}
/**
* Render an image without a title.
*/
@Override
public ASTNode visitSimpleimg(SimpleimgContext ctx) {
return new Image(ctx.InLink().getText(), ctx.InLink().getText(), page, urlOutputFilter, imageHandler);
}
/**
* Render an inline nowiki node. Due to how the lexer works, the contents
* include the ending symbol, which must be chopped off.
*
* TODO: Improve the tokensiation of this.
*/
@Override
public ASTNode visitPreformat(PreformatContext ctx) {
return renderInlineCode(ctx.EndNoWikiInline(), "}}}");
}
/**
* Render a syntax-highlighted CPP block. This has the same tokenisation
* problem as mentioned in {@link #visitPreformat}.
*/
@Override
public ASTNode visitInlinecpp(InlinecppContext ctx) {
return renderInlineCode(ctx.EndCppInline(), "[</c++>]", XhtmlRendererFactory.CPLUSPLUS);
}
/**
* Render a block of literal, unescaped, HTML.
*/
@Override
public ASTNode visitInlinehtml(InlinehtmlContext ctx) {
String code = ctx.EndHtmlInline().getText();
return new Raw(code.substring(0, code.length() - "[</html>]".length()));
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode} */
@Override
public ASTNode visitInlinejava(InlinejavaContext ctx) {
return renderInlineCode(ctx.EndJavaInline(), "[</java>]", XhtmlRendererFactory.JAVA);
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode} */
@Override
public ASTNode visitInlinexhtml(InlinexhtmlContext ctx) {
return renderInlineCode(ctx.EndXhtmlInline(), "[</xhtml>]", XhtmlRendererFactory.XHTML);
}
/** See {@link #visitInlinecpp} and {@link #renderInlineCode} */
@Override
public ASTNode visitInlinexml(InlinexmlContext ctx) {
return renderInlineCode(ctx.EndXmlInline(), "[</xml>]", XhtmlRendererFactory.XML);
}
/**
* Render a literal linebreak node
*/
@Override
public ASTNode visitLinebreak(LinebreakContext ctx) {
return new Linebreak();
}
/**
* Render a horizontal rule node.
*/
@Override
public ASTNode visitHrule(HruleContext ctx) {
return new HorizontalRule();
}
/**
* Render an ordered list. List rendering is a bit of a mess at the moment,
* but it basically works like this:
*
* - Lists have a root node, which contains level 1 elements.
*
* - There are levels 1 through 5.
*
* - Each level (other than 5) may have child list elements.
*
* - Each level (other than root) may also have some content, which can be a
* new list (ordered or unordered), or inline text.
*
* The root list node is rendered by displaying all level 1 entities in
* sequence, where level n entities are rendered by displaying their content
* and then any children they have.
*
* TODO: Figure out how to have arbitrarily-nested lists.
*/
@Override
public ASTNode visitOlist(OlistContext ctx) {
return renderList(ListType.Ordered, ctx.olist1());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitOlist1(Olist1Context ctx) {
ListType type = (ctx.list2().isEmpty() || ctx.list2().get(0).ulist2() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list2(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitOlist2(Olist2Context ctx) {
ListType type = (ctx.list3().isEmpty() || ctx.list3().get(0).ulist3() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list3(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitOlist3(Olist3Context ctx) {
ListType type = (ctx.list4().isEmpty() || ctx.list4().get(0).ulist4() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list4(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitOlist4(Olist4Context ctx) {
ListType type = (ctx.list5().isEmpty() || ctx.list5().get(0).ulist5() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list5(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitOlist5(Olist5Context ctx) {
return renderListItem(ListType.Ordered, new ArrayList<ParserRuleContext>(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist(UlistContext ctx) {
return renderList(ListType.Unordered, ctx.ulist1());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist1(Ulist1Context ctx) {
ListType type = (ctx.list2().isEmpty() || ctx.list2().get(0).ulist2() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list2(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist2(Ulist2Context ctx) {
ListType type = (ctx.list3().isEmpty() || ctx.list3().get(0).ulist3() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list3(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist3(Ulist3Context ctx) {
ListType type = (ctx.list4().isEmpty() || ctx.list4().get(0).ulist4() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list4(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist4(Ulist4Context ctx) {
ListType type = (ctx.list5().isEmpty() || ctx.list5().get(0).ulist5() == null) ? ListType.Ordered : ListType.Unordered;
return renderListItem(type, ctx.list5(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/** See {@link #visitOlist} */
@Override
public ASTNode visitUlist5(Ulist5Context ctx) {
return renderListItem(ListType.Unordered, new ArrayList<ParserRuleContext>(), ctx.olist(), ctx.ulist(), ctx.inline());
}
/**
* Render a NoWiki block node. This has the same tokenisation problem as
* mentioned in {@link #visitPreformat}.
*/
@Override
public ASTNode visitNowiki(NowikiContext ctx) {
return renderBlockCode(ctx.EndNoWikiBlock(), "}}}");
}
/**
* Like {@link #visitInlinecpp}, but for blocks.
*/
@Override
public ASTNode visitCpp(CppContext ctx) {
return renderBlockCode(ctx.EndCppBlock(), "[</c++>]", XhtmlRendererFactory.CPLUSPLUS);
}
/**
* Render a block of literal, unescaped, HTML.
*/
@Override
public ASTNode visitHtml(HtmlContext ctx) {
String code = ctx.EndHtmlBlock().getText();
return new Raw(code.substring(0, code.length() - "[</html>]".length()));
}
/** See {@link #visitCpp} and {@link #renderBlockCode} */
@Override
public ASTNode visitJava(JavaContext ctx) {
return renderBlockCode(ctx.EndJavaBlock(), "[</java>]", XhtmlRendererFactory.JAVA);
}
/** See {@link #visitCpp} and {@link #renderBlockCode} */
@Override
public ASTNode visitXhtml(XhtmlContext ctx) {
return renderBlockCode(ctx.EndXhtmlBlock(), "[</xhtml>]", XhtmlRendererFactory.XHTML);
}
/** See {@link #visitCpp} and {@link #renderBlockCode} */
@Override
public ASTNode visitXml(XmlContext ctx) {
return renderBlockCode(ctx.EndXmlBlock(), "[</xml>]", XhtmlRendererFactory.XML);
}
/**
* Render a table node. This consists of rendering all rows in sequence.
*/
@Override
public ASTNode visitTable(TableContext ctx) {
List<ASTNode> rows = new ArrayList<ASTNode>();
for (TrowContext rtx : ctx.trow()) {
rows.add(visit(rtx));
}
return new Table(rows);
}
/**
* Render a table row. A table row consists of a number of cells, and a
* possible trailing separator. At the moment, the trailing separator is
* handled explicitly here, rather than nicely in the grammar.
*
* TODO: Handle the trailing separator in the grammar, and remove the check
* here.
*/
@Override
public ASTNode visitTrow(TrowContext ctx) {
List<ASTNode> cells = new ArrayList<ASTNode>();
for (TcellContext rtx : ctx.tcell()) {
cells.add(visit(rtx));
}
// If the last cell is empty, it's a trailing separator - not actually a new
// cell.
if (cells.size() != 0) {
ASTNode last = cells.get(cells.size() - 1);
if (last instanceof TableCell && last.getChildren().get(0).toXHTML().matches("^\\W*$")) {
cells.remove(last);
}
}
return new TableRow(cells);
}
/**
* Render a table heading cell.
*/
@Override
public ASTNode visitTh(ThContext ctx) {
return new TableHeaderCell((ctx.inline() != null) ? visit(ctx.inline()) : new Plaintext(""));
}
/**
* Render a table cell.
*/
@Override
public ASTNode visitTd(TdContext ctx) {
return new TableCell((ctx.inline() != null) ? visit(ctx.inline()) : new Plaintext(""));
}
/**
* Render a macro.
*/
@Override
public ASTNode visitMacro(MacroContext ctx) {
return new MacroNode(ctx.MacroName().getText(), cutOffEndTag(ctx.MacroEnd(), ">>"), page, urlOutputFilter, linkHandler, imageHandler);
}
} |
package org.example;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class App {
private static final byte[] key = "abcdefghijklmnop".getBytes();
private static final byte[] iv = "0123456789012345".getBytes();
private byte[] encrypt(byte[] input) throws Exception {
SecretKeySpec key = new SecretKeySpec(App.key, "AES");
IvParameterSpec iv = new IvParameterSpec(App.iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(input);
}
private byte[] decrypt(byte[] input) throws Exception {
SecretKeySpec key = new SecretKeySpec(App.key, "AES");
IvParameterSpec iv = new IvParameterSpec(App.iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(input);
}
public static void main(String... args) throws Exception {
App app = new App();
{
String original = "your name is";
byte[] input = original.getBytes(StandardCharsets.UTF_8);
byte[] encrpyted = app.encrypt(input);
byte[] decrpypted = app.decrypt(encrpyted);
String result = new String(decrpypted, StandardCharsets.UTF_8);
System.out.println(String.format(" original: '%s'", original));
System.out.println(String.format("encrypted: '%s'", Base64.getEncoder().encodeToString(encrpyted)));
System.out.println(String.format("decrypted: '%s'", Base64.getEncoder().encodeToString(decrpypted)));
System.out.println(String.format(" result: '%s'", result));
System.out.println(String.format(" 123456789 123456789 123456789 123456789"));
}
int loop = 100000;
{
byte[] headOfReturns = new byte[loop];
long from = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
byte[] ret = app.encrypt(String.format("hoge-%d", i).getBytes(StandardCharsets.UTF_8));
headOfReturns[i] = ret[0];
}
long to = System.currentTimeMillis();
System.out.println();
System.out.println(String.format("%d times, elapsed: %d msec,\nreturns: %s", loop, to - from, Base64.getEncoder().encodeToString(headOfReturns)));
}
{
SecretKeySpec key = new SecretKeySpec(App.key, "AES");
IvParameterSpec iv = new IvParameterSpec(App.iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] headOfReturns = new byte[loop];
long from = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
byte[] ret = cipher.doFinal(String.format("hoge-%d", i).getBytes(StandardCharsets.UTF_8));
headOfReturns[i] = ret[0];
}
long to = System.currentTimeMillis();
System.out.println();
System.out.println(String.format("%d times, elapsed: %d msec,\nreturns: %s", loop, to - from, Base64.getEncoder().encodeToString(headOfReturns)));
}
}
} |
package edu.afs.subsystems.drivesubsystem;
import edu.wpi.first.wpilibj.command.PIDSubsystem;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.PIDSource;
import edu.afs.commands.DriveToShotRangeCommand;
import edu.afs.commands.DriveWithJoystickCommand;
import edu.afs.robot.OI;
import edu.afs.robot.RobotMap;
/**
*
* @author User
*/
public class DrivePIDSubsystem extends PIDSubsystem {
// PID tuning parameters.
//TODO: Pick tuning parameters.
private static final double K_PROPORTIONAL = 0.03;
private static final double K_INTEGRAL = 0.0;
private static final double K_DERIVATIVE = 0.0;
private static final double STRAIGHT_AHEAD_STEER_ANGLE = 0.0;
public static final double DRIVE_MAX_INPUT = 1.0;
public static final double DRIVE_MIN_INPUT = -1.0;
RobotDrive m_drive;
Talon m_leftDrive;
Talon m_rightDrive;
Gyro m_gyro;
AnalogChannel m_gyroChannel;
double m_steerAngle;
double m_steeringSetPoint;
// Implement Singleton design pattern. There
// can be only one instance of this subsystem.
static DrivePIDSubsystem instance = null;
public static DrivePIDSubsystem getInstance () {
if (instance == null) {
instance = new DrivePIDSubsystem();
}
return instance;
}
// Constructor is private to enforce Singelton.
private DrivePIDSubsystem() {
super("DrivePIDSubsystem",
K_PROPORTIONAL,
K_INTEGRAL,
K_DERIVATIVE);
// Drive set-up.
m_leftDrive = new Talon(RobotMap.DRIVE_LEFT_MOTOR_CHANNEL);
m_rightDrive = new Talon(RobotMap.DRIVE_RIGHT_MOTOR_CHANNEL);
m_drive = new RobotDrive(m_leftDrive, m_rightDrive);
m_drive.setSafetyEnabled(false);
// Gyro stabilization set-up.
m_gyroChannel = new AnalogChannel (RobotMap.GYRO_CHANNEL);
m_gyro = new Gyro(m_gyroChannel);
getPIDController().disable();
m_steerAngle = 0.0;
m_steeringSetPoint = 0.0;
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(new DriveWithJoystickCommand());
}
public void driveWithJoystick() {
m_drive.arcadeDrive(OI.getInstance().getJoystick());
}
// Move bot forward or backwards at specified speed.
// No gyro-stabilization of bearing is used.
public void driveStraight (double speed) {
// TODO: Do any speed value translation here.
// Speed input ranges from 1.0 (max forward) to -1.0
// (max reverse). Steer angle input ranges from 1.0 (max CW) to -1.0
// (max CCW).
m_drive.drive(speed, STRAIGHT_AHEAD_STEER_ANGLE);
}
// Move bot forward or backwards at specified speed.
// Bearing is gyro-stabilized.
public void driveStraightGyroStabilized (double speed) {
// TODO: Do any speed value and steer angle translation here.
// m_steerAngle is set by PID Controller.
// Speed input ranges from 1.0 (max forward) to -1.0
// (max reverse). Steer angle input ranges from 1.0 (max CW) to -1.0
// (max CCW).
m_drive.drive(speed, m_steerAngle);
}
public void initBearingStabilizer(){
// Add gyro and PID set-up code.
// TODO: Determine correct tolerance for "close enough" to set point.
//getPIDController().setAbsoluteTolerance(???);
// Treat input range as continuous so PID controller will correct
// angle by shortest path.
getPIDController().setContinuous(true);
//TODO: Determine output range from gyro (-360.0 to 360.0 degrees?????)
//getPIDController().setInputRange(???, ???);
getPIDController().setOutputRange(DRIVE_MIN_INPUT, DRIVE_MAX_INPUT);
m_gyro.setPIDSourceParameter(PIDSource.PIDSourceParameter.kAngle);
//TODO: Set Gyro sensitivity
//m_gyro.setSensitivity(?????????????????);
//Set gyro zero point.
m_gyro.reset();
// Establish set point for straight-ahead driving.
// Assume that bot is oriented perpendicular to 10-point goal.
// Use the current reading of the gyro.
//TODO: Verify that pidGet returns the value we want for comparison.
m_steeringSetPoint = m_gyro.pidGet();
getPIDController().setSetpoint(m_steeringSetPoint);
getPIDController().enable();
}
public void disableBearingStabilizer(){
getPIDController().reset();
m_gyro.reset();
getPIDController().disable();
}
//TODO: Make sure that units and range of values make sense for PID inputs
// and outputs!!!!!!!!!!!!!!
// Called every 20 ms by PID Controller.
protected double returnPIDInput() {
// Return your input value for the PID loop.
//TODO: Determine if any value conversion is needed.
return m_gyro.pidGet();
}
//TODO: Make sure that units and range of values make sense for PID inputs
// and outputs!!!!!!!!!!!!!!
// Called every 20 ms by PID Controller.
protected void usePIDOutput(double output) {
// Use output to drive your system.
m_steerAngle = output;
}
} |
package dr.app.beauti.traitspanel;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.BeautiPanel;
import dr.app.beauti.ComboBoxRenderer;
import dr.app.beauti.datapanel.DataPanel;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.TraitData;
import dr.app.beauti.options.TraitGuesser;
import dr.app.beauti.util.PanelUtils;
import dr.app.gui.table.TableEditorStopper;
import dr.app.gui.table.TableSorter;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import jam.framework.Exportable;
import jam.panels.ActionPanel;
import jam.table.TableRenderer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
/**
* @author Andrew Rambaut
* @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $
*/
public class TraitsPanel extends BeautiPanel implements Exportable {
private static final long serialVersionUID = 5283922195494563924L;
private static final int MINIMUM_TABLE_WIDTH = 140;
private static final String ADD_TRAITS_TOOLTIP = "<html>Define a new trait for the current taxa</html>";
private static final String IMPORT_TRAITS_TOOLTIP = "<html>Import one or more traits for these taxa from a tab-delimited<br>" +
"file. Taxa should be in the first column and the trait names<br>" +
"in the first row</html>";
private static final String GUESS_TRAIT_VALUES_TOOLTIP = "<html>This attempts to extract values for this trait that are<br>" +
"encoded in the names of the selected taxa.</html>";
private static final String SET_TRAIT_VALUES_TOOLTIP = "<html>This sets values for this trait for all<br>" +
"the selected taxa.</html>";
private static final String CLEAR_TRAIT_VALUES_TOOLTIP = "<html>This clears all the values currently assigned to taxa for<br>" +
"this trait.</html>";
private static final String CREATE_TRAIT_PARTITIONS_TOOLTIP = "<html>Create a data partition for the selected traits.</html>";
public final JTable traitsTable;
private final TraitsTableModel traitsTableModel;
private final JTable dataTable;
private final DataTableModel dataTableModel;
private final BeautiFrame frame;
private final DataPanel dataPanel;
private BeautiOptions options = null;
private TraitData currentTrait = null; // current trait
private CreateTraitDialog createTraitDialog = null;
private GuessTraitDialog guessTraitDialog = null;
private TraitValueDialog traitValueDialog = null;
AddTraitAction addTraitAction = new AddTraitAction();
Action importTraitsAction;
CreateTraitPartitionAction createTraitPartitionAction = new CreateTraitPartitionAction();
GuessTraitsAction guessTraitsAction = new GuessTraitsAction();
SetValueAction setValueAction = new SetValueAction();
public TraitsPanel(BeautiFrame parent, DataPanel dataPanel, Action importTraitsAction) {
this.frame = parent;
this.dataPanel = dataPanel;
traitsTableModel = new TraitsTableModel();
// TableSorter sorter = new TableSorter(traitsTableModel);
// traitsTable = new JTable(sorter);
// sorter.setTableHeader(traitsTable.getTableHeader());
traitsTable = new JTable(traitsTableModel);
traitsTable.getTableHeader().setReorderingAllowed(false);
traitsTable.getTableHeader().setResizingAllowed(false);
// traitsTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
TableColumn col = traitsTable.getColumnModel().getColumn(1);
ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer(TraitData.TraitType.values());
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable);
traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
traitSelectionChanged();
// dataTableModel.fireTableDataChanged();
}
});
JScrollPane scrollPane1 = new JScrollPane(traitsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setOpaque(false);
dataTableModel = new DataTableModel();
TableSorter sorter = new TableSorter(dataTableModel);
dataTable = new JTable(sorter);
sorter.setTableHeader(dataTable.getTableHeader());
dataTable.getTableHeader().setReorderingAllowed(false);
// dataTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setPreferredWidth(80);
col = dataTable.getColumnModel().getColumn(1);
comboBoxRenderer = new ComboBoxRenderer();
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable);
// dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
// public void valueChanged(ListSelectionEvent evt) {
// traitSelectionChanged();
JScrollPane scrollPane2 = new JScrollPane(dataTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setOpaque(false);
JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
toolBar1.setOpaque(false);
toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
JButton button;
button = new JButton(addTraitAction);
PanelUtils.setupComponent(button);
button.setToolTipText(ADD_TRAITS_TOOLTIP);
toolBar1.add(button);
this.importTraitsAction = importTraitsAction;
button = new JButton(importTraitsAction);
PanelUtils.setupComponent(button);
button.setToolTipText(IMPORT_TRAITS_TOOLTIP);
toolBar1.add(button);
toolBar1.add(new JToolBar.Separator(new Dimension(12, 12)));
button = new JButton(guessTraitsAction);
PanelUtils.setupComponent(button);
button.setToolTipText(GUESS_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
button = new JButton(setValueAction);
PanelUtils.setupComponent(button);
button.setToolTipText(SET_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
// Don't see the need for a clear values button
// button = new JButton(new ClearTraitAction());
// PanelUtils.setupComponent(button);
// button.setToolTipText(CLEAR_TRAIT_VALUES_TOOLTIP);
// toolBar1.add(button);
button = new JButton(createTraitPartitionAction);
PanelUtils.setupComponent(button);
button.setToolTipText(CREATE_TRAIT_PARTITIONS_TOOLTIP);
toolBar1.add(button);
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addTraitAction);
actionPanel1.setRemoveAction(removeTraitAction);
actionPanel1.setAddToolTipText(ADD_TRAITS_TOOLTIP);
removeTraitAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane1, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0));
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
panel2.add(toolBar1, BorderLayout.NORTH);
panel2.add(scrollPane2, BorderLayout.CENTER);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
panel1, panel2);
splitPane.setDividerLocation(MINIMUM_TABLE_WIDTH);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(splitPane, BorderLayout.CENTER);
add(toolBar1, BorderLayout.NORTH);
}
public void setOptions(BeautiOptions options) {
this.options = options;
updateButtons();
// int selRow = traitsTable.getSelectedRow();
// traitsTableModel.fireTableDataChanged();
// if (selRow < 0) {
// selRow = 0;
// traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
// if (selectedTrait == null) {
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
traitsTableModel.fireTableDataChanged();
dataTableModel.fireTableDataChanged();
validate();
repaint();
}
public void getOptions(BeautiOptions options) {
// int selRow = traitsTable.getSelectedRow();
// if (selRow >= 0 && options.traitsOptions.selecetedTraits.size() > 0) {
// selectedTrait = options.traitsOptions.selecetedTraits.get(selRow);
// options.datesUnits = unitsCombo.getSelectedIndex();
// options.datesDirection = directionCombo.getSelectedIndex();
}
public JComponent getExportableComponent() {
return dataTable;
}
public void fireTraitsChanged() {
if (currentTrait != null) {
// if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) {
// frame.setupStarBEAST();
// } else
if (currentTrait != null && currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) {
frame.updateDiscreteTraitAnalysis();
}
// if (selRow > 0) {
// traitsTable.getSelectionModel().setSelectionInterval(selRow-1, selRow-1);
// } else if (selRow == 0 && options.traitsOptions.traits.size() > 0) { // options.traitsOptions.traits.size() after remove
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
traitsTableModel.fireTableDataChanged();
options.updatePartitionAllLinks();
frame.setDirty();
}
}
private void traitSelectionChanged() {
int selRow = traitsTable.getSelectedRow();
if (selRow >= 0) {
currentTrait = options.traits.get(selRow);
// traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
removeTraitAction.setEnabled(true);
// } else {
// currentTrait = null;
// removeTraitAction.setEnabled(false);
}
if (options.traits.size() <= 0) {
currentTrait = null;
removeTraitAction.setEnabled(false);
}
dataTableModel.fireTableDataChanged();
// traitsTableModel.fireTableDataChanged();
}
private void updateButtons() { //TODO: better to merge updateButtons() fireTraitsChanged() traitSelectionChanged() into one
boolean hasData = options.hasData();
addTraitAction.setEnabled(hasData);
importTraitsAction.setEnabled(hasData);
createTraitPartitionAction.setEnabled(hasData && options.traits.size() > 0);
guessTraitsAction.setEnabled(hasData && options.traits.size() > 0);
setValueAction.setEnabled(hasData && options.traits.size() > 0);
}
public void clearTraitValues(String traitName) {
options.clearTraitValues(traitName);
dataTableModel.fireTableDataChanged();
}
public void guessTrait() {
if (options.taxonList == null) { // validation of check empty taxonList
return;
}
if (currentTrait == null) {
if (!addTrait()) {
return; // if addTrait() cancel then false
}
}
int result;
do {
TraitGuesser currentTraitGuesser = new TraitGuesser(currentTrait);
if (guessTraitDialog == null) {
guessTraitDialog = new GuessTraitDialog(frame);
}
guessTraitDialog.setDescription("Extract values for trait '" + currentTrait + "' from taxa labels");
result = guessTraitDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
guessTraitDialog.setupGuesserFromDialog(currentTraitGuesser);
try {
int[] selRows = dataTable.getSelectedRows();
if (selRows.length > 0) {
Taxa selectedTaxa = new Taxa();
for (int row : selRows) {
Taxon taxon = (Taxon) dataTable.getValueAt(row, 0);
selectedTaxa.addTaxon(taxon);
}
currentTraitGuesser.guessTrait(selectedTaxa);
} else {
currentTraitGuesser.guessTrait(options.taxonList);
}
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
result = -1;
}
dataTableModel.fireTableDataChanged();
} while (result < 0);
}
public void setTraitValue() {
if (options.taxonList == null) { // validation of check empty taxonList
return;
}
int result;
do {
if (traitValueDialog == null) {
traitValueDialog = new TraitValueDialog(frame);
}
int[] selRows = dataTable.getSelectedRows();
if (selRows.length > 0) {
traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for selected taxa");
} else {
traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for all taxa");
}
result = traitValueDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
// currentTrait.guessTrait = true; // ?? no use?
String value = traitValueDialog.getTraitValue();
try {
if (selRows.length > 0) {
for (int row : selRows) {
Taxon taxon = (Taxon) dataTable.getValueAt(row, 0);
taxon.setAttribute(currentTrait.getName(), value);
}
} else {
for (Taxon taxon : options.taxonList) {
taxon.setAttribute(currentTrait.getName(), value);
}
}
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
result = -1;
}
dataTableModel.fireTableDataChanged();
} while (result < 0);
}
public boolean addTrait() {
return addTrait("Untitled");
}
public boolean addTrait(String traitName) {
return addTrait(null, traitName, false);
}
public boolean addTrait(String message, String traitName, boolean isSpeciesTrait) {
if (createTraitDialog == null) {
createTraitDialog = new CreateTraitDialog(frame);
}
createTraitDialog.setSpeciesTrait(isSpeciesTrait);
createTraitDialog.setTraitName(traitName);
createTraitDialog.setMessage(message);
int result = createTraitDialog.showDialog();
if (result == JOptionPane.OK_OPTION) {
frame.tabbedPane.setSelectedComponent(this);
String name = createTraitDialog.getName();
TraitData.TraitType type = createTraitDialog.getType();
TraitData newTrait = new TraitData(options, name, "", type);
currentTrait = newTrait;
// The createTraitDialog will have already checked if the
// user is overwriting an existing trait
addTrait(newTrait);
if (createTraitDialog.createTraitPartition()) {
options.createPartitionForTraits(name, newTrait);
}
fireTraitsChanged();
updateButtons();
} else if (result == CreateTraitDialog.OK_IMPORT) {
boolean done = frame.doImportTraits();
if (done) {
if (isSpeciesTrait) {
// check that we did indeed import a 'species' trait
if (!options.traitExists(TraitData.TRAIT_SPECIES)) {
JOptionPane.showMessageDialog(this,
"The imported trait file didn't contain a trait\n" +
"called '" + TraitData.TRAIT_SPECIES + "', required for *BEAST.\n" +
"Please edit it or select a different file.",
"Reserved trait name",
JOptionPane.WARNING_MESSAGE);
return false;
}
}
updateButtons();
}
return done;
} else if (result == JOptionPane.CANCEL_OPTION) {
return false;
}
return true;
}
public void createTraitPartition() {
int[] selRows = traitsTable.getSelectedRows();
java.util.List<TraitData> traits = new ArrayList<TraitData>();
int discreteCount = 0;
int continuousCount = 0;
for (int row : selRows) {
TraitData trait = options.traits.get(row);
traits.add(trait);
if (trait.getTraitType() == TraitData.TraitType.DISCRETE) {
discreteCount ++;
}
if (trait.getTraitType() == TraitData.TraitType.CONTINUOUS) {
continuousCount ++;
}
}
boolean success = false;
if (discreteCount > 0) {
if (continuousCount > 0) {
JOptionPane.showMessageDialog(TraitsPanel.this, "Don't mix discrete and continuous traits when creating partition(s).", "Mixed Trait Types", JOptionPane.ERROR_MESSAGE);
return;
}
// with discrete traits, create a separate partition for each
for (TraitData trait : traits) {
java.util.List<TraitData> singleTrait = new ArrayList<TraitData>();
singleTrait.add(trait);
if (dataPanel.createFromTraits(singleTrait)) {
success = true;
}
}
} else {
// with
success = dataPanel.createFromTraits(traits);
}
if (success) {
frame.switchToPanel(BeautiFrame.DATA_PARTITIONS);
}
}
public void addTrait(TraitData newTrait) {
int selRow = options.addTrait(newTrait);
traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
}
private void removeTrait() {
int selRow = traitsTable.getSelectedRow();
removeTrait(traitsTable.getValueAt(selRow, 0).toString());
}
public void removeTrait(String traitName) {
if (options.useStarBEAST && traitName.equalsIgnoreCase(TraitData.TRAIT_SPECIES)) {
JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used by *BEAST.\nTurn *BEAST off before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE);
return;
}
TraitData traitData = options.getTrait(traitName);
if (options.getTraitPartitions(traitData).size() > 0) {
JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used in a partition.\nRemove the partition before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE);
return;
}
options.removeTrait(traitName);
updateButtons();
fireTraitsChanged();
traitSelectionChanged();
}
public class ClearTraitAction extends AbstractAction {
private static final long serialVersionUID = -7281309694753868635L;
public ClearTraitAction() {
super("Clear trait values");
}
public void actionPerformed(ActionEvent ae) {
if (currentTrait != null) clearTraitValues(currentTrait.getName()); // Clear trait values
}
}
public class GuessTraitsAction extends AbstractAction {
private static final long serialVersionUID = 8514706149822252033L;
public GuessTraitsAction() {
super("Guess trait values");
}
public void actionPerformed(ActionEvent ae) {
guessTrait();
}
}
public class AddTraitAction extends AbstractAction {
public AddTraitAction() {
super("Add trait");
}
public void actionPerformed(ActionEvent ae) {
addTrait();
}
}
AbstractAction removeTraitAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
removeTrait();
}
};
public class SetValueAction extends AbstractAction {
public SetValueAction() {
super("Set trait values");
setToolTipText("Use this button to set the trait values of selected taxa");
}
public void actionPerformed(ActionEvent ae) {
setTraitValue();
}
}
public class CreateTraitPartitionAction extends AbstractAction {
public CreateTraitPartitionAction() {
super("Create partition from trait ...");
}
public void actionPerformed(ActionEvent ae) {
createTraitPartition();
}
}
class TraitsTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Trait", "Type"};
public TraitsTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
return options.traits.size();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.traits.get(row).getName();
case 1:
return options.traits.get(row).getTraitType();
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
switch (col) {
case 0:
String oldName = options.traits.get(row).getName();
options.traits.get(row).setName(aValue.toString());
Object value;
for (Taxon t : options.taxonList) {
value = t.getAttribute(oldName);
t.setAttribute(aValue.toString(), value);
// cannot remvoe attribute in Attributable inteface
}
fireTraitsChanged();
break;
case 1:
options.traits.get(row).setTraitType((TraitData.TraitType) aValue);
break;
}
}
public boolean isCellEditable(int row, int col) {
return !options.useStarBEAST || !options.traits.get(row).getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES.toString());
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
class DataTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Taxon", "Value"};
public DataTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.taxonList == null) return 0;
if (currentTrait == null) return 0;
return options.taxonList.getTaxonCount();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.taxonList.getTaxon(row);
case 1:
Object value = null;
if (currentTrait != null) {
value = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
}
if (value != null) {
return value;
} else {
return "";
}
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
if (col == 1) {
// Location location = options.taxonList.getTaxon(row).getLocation();
// if (location != null) {
// options.taxonList.getTaxon(row).setLocation(location);
if (currentTrait != null) {
options.taxonList.getTaxon(row).setAttribute(currentTrait.getName(), aValue);
}
}
}
public boolean isCellEditable(int row, int col) {
if (col == 1) {
// Object t = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
// return (t != null);
return true;
} else {
return false;
}
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
} |
package tlc2.tool.distributed;
import java.io.EOFException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateVec;
import tlc2.tool.WorkerException;
import tlc2.tool.distributed.selector.IBlockSelector;
import tlc2.tool.fp.FPSet;
import tlc2.tool.queue.IStateQueue;
import tlc2.tool.queue.StateQueue;
import tlc2.util.BitVector;
import tlc2.util.IdThread;
import tlc2.util.LongVec;
public class TLCServerThread extends IdThread {
private static int COUNT = 0;
/**
* Runtime statistics about states send and received by and from the remote
* worker. These stats are shown at the end of model checking for every
* worker thread.
*/
private int receivedStates, sentStates;
/**
* {@link TLCWorker}s maintain a worker-local fingerprint cache. The hit
* ratio is kept here for final statistics. A negative value indicates that
* the statistic has not been gathered yet.
*/
private double cacheRateHitRatio = -1L;
/**
* An {@link IBlockSelector} tunes the amount of states send to a remote
* worker. Depending on its concrete implementation it might employ runtime
* statistics to assign the ideal amount of states.
*
* @see TLCServerThread#states
*/
private final IBlockSelector selector;
/**
* Current unit of work or null
*
* @see TLCServerThread#selector
*/
private TLCState[] states = new TLCState[0];
/**
* Periodically check the remote worker's aliveness by spawning a
* asynchronous task that is automatically scheduled by the JVM for
* re-execution in the defined interval.
* <p>
* It is the tasks responsibility to detect a stale worker and disconnect
* it.
*
* @see TLCServerThread#keepAliveTimer
*/
private final TLCTimerTask task;
/**
* @see TLCServerThread#task
*/
private final Timer keepAliveTimer;
/**
* Synchronized flag used to indicate the correct amount of workers to
* TCLGlobals.
*
* Either {@link TLCServerThread#run()} or
* {@link TLCServerThread#keepAliveTimer} will flip to false causing
* subsequent calls to
* {@link TLCServerThread#handleRemoteWorkerLost(StateQueue)} to be a noop.
*
* Synchronization is required because {@link TLCServerThread#run()} and
* {@link TLCTimerTask#run()} are executed as two separate threads.
*/
private final AtomicBoolean cleanupGlobals = new AtomicBoolean(true);
/**
* An {@link ExecutorService} used to parallelize calls to the _distributed_
* fingerprint set servers ({@link FPSet}).
* <p>
* The fingerprint space is partitioned across all {@link FPSet} servers and
* thus can be accessed concurrently.
*/
private final ExecutorService executorService;
/**
* An RMI proxy for the remote worker.
*
* @see TLCServerThread#tlcServer
*/
private final TLCWorkerRMI worker;
/**
* The {@link TLCServer} master this {@link TLCServerThread} provides the
* service of handling a single remote worker. A {@link TLCServer} uses n
* {@link TLCWorker}s to calculate the next state relation. To invoke
* workers concurrently, it spawns a {@link TLCServerThread} for each
* {@link TLCWorkerRMI} RMI proxy.
* <p>
* {@link TLCServer} and {@link TLCWorkerRMI} form a 1:n mapping and
* {@link TLCServerThread} is this mapping.
*
* @see TLCServerThread#worker
*/
private final TLCServer tlcServer;
/**
* Remote worker's address used to label local threads.
*/
private URI uri;
public TLCServerThread(TLCWorkerRMI worker, URI aURI, TLCServer tlc, ExecutorService es, IBlockSelector aSelector) {
super(COUNT++);
this.executorService = es;
this.tlcServer = tlc;
this.selector = aSelector;
this.uri = aURI;
// Create Timer early to avoid NPE in handleRemoteWorkerLost (it tries to cancel the timer)
keepAliveTimer = new Timer("TLCWorker KeepAlive Timer ["
+ uri.toASCIIString() + "]", true);
// Wrap the TLCWorker with a SmartProxy. A SmartProxy's responsibility
// is to measure the RTT spend to transfer states back and forth.
this.worker = new TLCWorkerSmartProxy(worker);
// Prefix the thread name with a fixed string and a counter.
// This part is used by the external Munin based statistics software to
// gather thread contention stats.
final String i = String.format("%03d", myGetId());
setName(TLCServer.THREAD_NAME_PREFIX + i + "-[" + uri.toASCIIString() + "]");
// schedule a timer to periodically (60s) check server aliveness
task = new TLCTimerTask();
keepAliveTimer.schedule(task, 10000, 60000);
}
/**
* This method gets a state from the queue, generates all the possible next
* states of the state, checks the invariants, and updates the state set and
* state queue.
*/
public void run() {
TLCGlobals.incNumWorkers();
TLCStateVec[] newStates = null;
LongVec[] newFps = null;
final IStateQueue stateQueue = this.tlcServer.stateQueue;
try {
START: while (true) {
// blocks until more states available or all work is done
states = selector.getBlocks(stateQueue, worker);
if (states == null) {
synchronized (this.tlcServer) {
this.tlcServer.setDone();
this.tlcServer.notify();
}
stateQueue.finishAll();
return;
}
// without initial states no need to bother workers
if (states.length == 0) {
continue;
}
// count statistics
sentStates += states.length;
// real work happens here:
// worker computes next states for states
boolean workDone = false;
while (!workDone) {
try {
final NextStateResult res = this.worker.getNextStates(states);
newStates = res.getNextStates();
receivedStates += newStates[0].size();
newFps = res.getNextFingerprints();
workDone = true;
task.setLastInvocation(System.currentTimeMillis());
// Read remote worker cache hits which correspond to
// states skipped
tlcServer.addStatesGeneratedDelta(res.getStatesComputedDelta());
} catch (RemoteException e) {
// If a (remote) {@link TLCWorkerRMI} fails due to the
// amount of new states we have sent it, try to lower
// the amount of states
// and re-send (until we just send a single state)
if (isRecoverable(e) && states.length > 1) {
MP.printMessage(
EC.TLC_DISTRIBUTED_EXCEED_BLOCKSIZE,
Integer.toString(states.length / 2));
// states[] exceeds maximum transferable size
// (add states back to queue and retry)
stateQueue.sEnqueue(states);
// half the maximum size and use it as a limit from
// now on
selector.setMaxTXSize(states.length / 2);
// go back to beginning
continue START;
} else {
// non recoverable errors, exit...
MP.printMessage(
EC.TLC_DISTRIBUTED_WORKER_LOST,
getUri().toString());
handleRemoteWorkerLost(stateQueue);
return;
}
} catch (NullPointerException e) {
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_LOST,
// have the stack trace on a newline
"\n" + throwableToString(e));
handleRemoteWorkerLost(stateQueue);
return;
}
}
// add fingerprints to fingerprint manager (delegates to
// corresponding fingerprint server)
// (Why isn't this done by workers directly?
// -> because if the worker crashes while computing states, the
// fp set would be inconsistent => making it an "atomic"
// operation)
BitVector[] visited = this.tlcServer.fpSetManager
.putBlock(newFps, executorService);
// recreate newly computed states and add them to queue
for (int i = 0; i < visited.length; i++) {
BitVector.Iter iter = new BitVector.Iter(visited[i]);
int index;
while ((index = iter.next()) != -1) {
TLCState state = newStates[i].elementAt(index);
// write state id and state fp to .st file for
// checkpointing
long fp = newFps[i].elementAt(index);
state.uid = this.tlcServer.trace.writeState(state, fp);
// add state to state queue for further processing
stateQueue.sEnqueue(state);
}
}
}
} catch (Throwable e) {
TLCState state1 = null, state2 = null;
if (e instanceof WorkerException) {
state1 = ((WorkerException) e).state1;
state2 = ((WorkerException) e).state2;
}
if (this.tlcServer.setErrState(state1, true)) {
if (state1 != null) {
try {
this.tlcServer.trace.printTrace(state1, state2);
} catch (Exception e1) {
MP.printError(EC.GENERAL, e1);
}
} else {
MP.printError(EC.GENERAL, e);
}
stateQueue.finishAll();
synchronized (this.tlcServer) {
this.tlcServer.notify();
}
}
} finally {
try {
cacheRateHitRatio = worker.getCacheRateRatio();
} catch (RemoteException e) {
// Remote worker might crash after return the last next
// state computation result but before the cache rate hit
// ratio statistic could be read. If this is the case the
// final statistic will be reported as negative indicating
// that it failed to read the statistic.
MP.printWarning(
EC.GENERAL,
"Failed to read remote worker cache statistic (Expect to see a negative chache hit rate. Does not invalidate model checking results)");
}
keepAliveTimer.cancel();
states = new TLCState[0];
// not calling TLCGlobals#decNumWorkers here because at this point
// TLCServer is shutting down anyway
}
}
/**
* A recoverable error/exception is defined to be a case where the
* {@link TLCWorkerRMI} can continue to work if {@link TLCServer} sends less
* new states to process.
*/
private boolean isRecoverable(final Exception e) {
final Throwable cause = e.getCause();
return ((cause instanceof EOFException && cause.getMessage() == null) || (cause instanceof RemoteException && cause
.getCause() instanceof OutOfMemoryError));
}
private String throwableToString(final Exception e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return result.toString();
}
/**
* Handles the case of a disconnected remote worker
*
* @param stateQueue
*/
private void handleRemoteWorkerLost(final IStateQueue stateQueue) {
// Cancel the keepAliveTimer which might still be running if an
// exception in the this run() method has caused handleRemoteWorkerLost
// to be called.
keepAliveTimer.cancel();
// This call has to be idempotent, otherwise we see bugs as in
// Prevent second invocation of worker de-registration which stamps from
// a race condition between the TimerTask (that periodically checks
// server aliveness) and the exception handling that kicks in when the
// run() method catches an RMI exception.
if (cleanupGlobals.compareAndSet(true, false)) {
// De-register TLCServerThread at the main server thread locally
tlcServer.removeTLCServerThread(this);
// Return the undone worklist (if any)
if (stateQueue != null) {
stateQueue.sEnqueue(states != null ? states : new TLCState[0]);
}
// Reset states to empty array to signal to TLCServer that we are not
// processing any new states. Otherwise statistics will incorrectly
// count this TLCServerThread as actively calculating states.
states = new TLCState[0];
// Before decrementing the worker count, notify all waiters on
// stateQueue to re-evaluate the while loop in isAvail(). The demise
// of this worker (who potentially was the lock owner) might causes
// another consumer to leave the while loop (become a consumer).
// This has to happen _prior_ to calling decNumWorkers. Otherwise
// we decrement the total number and the active count by one
// simultaneously, leaving isAvail without effect.
// This is to work around a design bug in
// tlc2.tool.queue.StateQueue's impl. Other IStateQueue impls should
// hopefully not be affected by calling notifyAll on them though.
if (stateQueue != null) {
synchronized (stateQueue) {
stateQueue.notifyAll();
}
}
TLCGlobals.decNumWorkers();
}
}
/**
* @return The current amount of states the corresponding worker is
* computing on
*/
public int getCurrentSize() {
return states.length;
}
/**
* @return the url
*/
public URI getUri() {
return this.uri;
}
/**
* @return the receivedStates
*/
public int getReceivedStates() {
return receivedStates;
}
/**
* @return the sentStates
*/
public int getSentStates() {
return sentStates;
}
/**
* @return The hit ratio of the worker-local fingerprint cache.
*/
public double getCacheRateRatio() {
return cacheRateHitRatio;
}
private class TLCTimerTask extends TimerTask {
/**
* Timestamp of last successful remote invocation
*/
private long lastInvocation = 0L;
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
public void run() {
// Check if the last invocation happened within the last minute. If
// not, check the worker's aliveness and dispose of it if indeed
// lost.
long now = new Date().getTime();
if (lastInvocation == 0 || (now - lastInvocation) > 60000) {
try {
if (!worker.isAlive()) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
} catch (RemoteException e) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
}
}
/**
* @param lastInvocation the lastInvocation to set
*/
public void setLastInvocation(long lastInvocation) {
this.lastInvocation = lastInvocation;
}
}
} |
package net.java.sip.communicator.impl.gui;
import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.lookandfeel.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.account.*;
import net.java.sip.communicator.impl.gui.main.chat.*;
import net.java.sip.communicator.impl.gui.main.chat.conference.*;
import net.java.sip.communicator.impl.gui.main.configforms.*;
import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.impl.gui.main.contactlist.addcontact.*;
import net.java.sip.communicator.impl.gui.main.login.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
/**
* An implementation of the <tt>UIService</tt> that gives access to other
* bundles to this particular swing ui implementation.
*
* @author Yana Stamcheva
*/
public class UIServiceImpl
implements UIService
{
private static final Logger logger = Logger.getLogger(UIServiceImpl.class);
private PopupDialogImpl popupDialog;
private AccountRegWizardContainerImpl wizardContainer;
private Map registeredPlugins = new Hashtable();
private Vector pluginComponentListeners = new Vector();
private static final List supportedContainers = new ArrayList();
static
{
supportedContainers.add(UIService.CONTAINER_MAIN_TOOL_BAR);
supportedContainers.add(UIService.CONTAINER_CONTACT_RIGHT_BUTTON_MENU);
supportedContainers.add(UIService.CONTAINER_GROUP_RIGHT_BUTTON_MENU);
supportedContainers.add(UIService.CONTAINER_TOOLS_MENU);
supportedContainers.add(UIService.CONTAINER_HELP_MENU);
supportedContainers.add(UIService.CONTAINER_CHAT_TOOL_BAR);
supportedContainers.add(UIService.CONTAINER_CALL_HISTORY);
supportedContainers.add(UIService.CONTAINER_MAIN_TABBED_PANE);
supportedContainers.add(UIService.CONTAINER_CHAT_HELP_MENU);
}
private static final Hashtable exportedWindows = new Hashtable();
private MainFrame mainFrame;
private LoginManager loginManager;
private ContactListPanel contactListPanel;
private ConfigurationFrame configurationFrame;
private boolean exitOnClose = true;
/**
* Creates an instance of <tt>UIServiceImpl</tt>.
*/
public UIServiceImpl()
{
}
/**
* Initializes all frames and panels and shows the gui.
*/
public void loadApplicationGui()
{
this.setDefaultThemePack();
this.mainFrame = new MainFrame();
this.loginManager = new LoginManager(mainFrame);
this.contactListPanel = mainFrame.getContactListPanel();
this.popupDialog = new PopupDialogImpl();
this.wizardContainer = new AccountRegWizardContainerImpl(mainFrame);
this.configurationFrame = new ConfigurationFrame(mainFrame);
mainFrame.setContactList(GuiActivator.getMetaContactListService());
if(ConfigurationManager.isApplicationVisible())
SwingUtilities.invokeLater(new RunApplicationGui());
SwingUtilities.invokeLater(new RunLoginGui());
this.initExportedWindows();
}
public void removeComponent(ContainerID containerID, Object component)
throws IllegalArgumentException
{
if (!supportedContainers.contains(containerID))
{
throw new IllegalArgumentException(
"The constraint that you specified is not"
+ " supported by this UIService implementation.");
}
else
{
if (registeredPlugins.containsKey(containerID))
{
((Vector) registeredPlugins.get(containerID)).remove(component);
}
this.firePluginEvent(component, containerID,
PluginComponentEvent.PLUGIN_COMPONENT_REMOVED);
}
}
public void addComponent(ContainerID containerID, Object component)
throws ClassCastException, IllegalArgumentException
{
if (!supportedContainers.contains(containerID))
{
throw new IllegalArgumentException(
"The constraint that you specified is not"
+ " supported by this UIService implementation.");
}
else if (!(component instanceof Component))
{
throw new ClassCastException(
"The specified plugin is not a valid swing or awt component.");
}
else
{
if (registeredPlugins.containsKey(containerID))
{
((Vector) registeredPlugins.get(containerID)).add(component);
}
else
{
Vector plugins = new Vector();
plugins.add(component);
registeredPlugins.put(containerID, plugins);
}
this.firePluginEvent(component, containerID,
PluginComponentEvent.PLUGIN_COMPONENT_ADDED);
}
}
public void addComponent(ContainerID containerID, String constraint,
Object component) throws ClassCastException, IllegalArgumentException
{
this.addComponent(containerID, component);
}
public void addComponent(ContainerID containerID,
ContactAwareComponent component) throws ClassCastException,
IllegalArgumentException
{
if (!(component instanceof Component))
{
throw new ClassCastException(
"The specified plugin is not a valid swing or awt component.");
}
this.addComponent(containerID, (Component) component);
}
public void addComponent(ContainerID containerID, String constraint,
ContactAwareComponent component) throws ClassCastException,
IllegalArgumentException
{
this.addComponent(containerID, constraint, component);
}
/**
* Implements <code>UISercie.getSupportedContainers</code>. Returns the
* list of supported containers by this implementation .
*
* @see UIService#getSupportedContainers()
* @return an Iterator over all supported containers.
*/
public Iterator getSupportedContainers()
{
return Collections.unmodifiableList(supportedContainers).iterator();
}
public Iterator getComponentsForContainer(ContainerID containerID)
throws IllegalArgumentException
{
if (!supportedContainers.contains(containerID))
throw new IllegalArgumentException(
"The container that you specified is not "
+ "supported by this UIService implementation.");
Vector plugins = new Vector();
Object o = registeredPlugins.get(containerID);
if (o != null)
{
plugins = (Vector) o;
}
return plugins.iterator();
}
/**
* Not yet implemented.
*
* @param containerID the ID of the container whose constraints we'll be
* retrieving.
*
* @see UIService#getConstraintsForContainer(ContainerID)
*
* @return Iterator an <tt>Iterator</tt> for all constraintes supported by
* the container corresponding to containerID.
*/
public Iterator getConstraintsForContainer(ContainerID containerID)
{
return null;
}
/**
* Creates the corresponding PluginComponentEvent and notifies all
* <tt>ContainerPluginListener</tt>s that a plugin component is added or
* removed from the container.
*
* @param pluginComponent the plugin component that is added to the
* container.
* @param containerID the containerID that corresponds to the container
* where the component is added.
* @param eventID one of the PLUGIN_COMPONENT_XXX static fields indicating
* the nature of the event.
*/
private void firePluginEvent(Object pluginComponent,
ContainerID containerID, int eventID)
{
PluginComponentEvent evt = new PluginComponentEvent(pluginComponent,
containerID, eventID);
logger.trace("Will dispatch the following plugin component event: "
+ evt);
synchronized (pluginComponentListeners)
{
Iterator listeners = this.pluginComponentListeners.iterator();
while (listeners.hasNext())
{
PluginComponentListener l = (PluginComponentListener) listeners
.next();
switch (evt.getEventID())
{
case PluginComponentEvent.PLUGIN_COMPONENT_ADDED:
l.pluginComponentAdded(evt);
break;
case PluginComponentEvent.PLUGIN_COMPONENT_REMOVED:
l.pluginComponentRemoved(evt);
break;
default:
logger.error("Unknown event type " + evt.getEventID());
}
}
}
}
/**
* Implements <code>isVisible</code> in the UIService interface. Checks if
* the main application window is visible.
*
* @return <code>true</code> if main application window is visible,
* <code>false</code> otherwise
* @see UIService#isVisible()
*/
public boolean isVisible()
{
if (mainFrame.isVisible())
{
if (mainFrame.getExtendedState() == JFrame.ICONIFIED)
return false;
else
return true;
}
else
return false;
}
/**
* Implements <code>setVisible</code> in the UIService interface. Shows or
* hides the main application window depending on the parameter
* <code>visible</code>.
*
* @param isVisible true if we are to show the main application frame and
* false otherwise.
*
* @see UIService#setVisible(boolean)
*/
public void setVisible(boolean isVisible)
{
this.mainFrame.setVisible(isVisible);
if(isVisible)
this.mainFrame.toFront();
}
/**
* Implements <code>minimize</code> in the UIService interface. Minimizes
* the main application window.
*
* @see UIService#minimize()
*/
public void minimize()
{
this.mainFrame.setExtendedState(JFrame.ICONIFIED);
}
/**
* Implements <code>maximize</code> in the UIService interface. Maximizes
* the main application window.
*
* @see UIService#maximize()
*/
public void maximize()
{
this.mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
/**
* Implements <code>restore</code> in the UIService interface. Restores
* the main application window.
*
* @see UIService#restore()
*/
public void restore()
{
if (mainFrame.isVisible())
{
if (mainFrame.getState() == JFrame.ICONIFIED)
mainFrame.setState(JFrame.NORMAL);
mainFrame.toFront();
}
else
mainFrame.setVisible(true);
}
/**
* Implements <code>resize</code> in the UIService interface. Resizes the
* main application window.
*
* @param height the new height of tha main application frame.
* @param width the new width of the main application window.
*
* @see UIService#resize(int, int)
*/
public void resize(int width, int height)
{
this.mainFrame.setSize(width, height);
}
/**
* Implements <code>move</code> in the UIService interface. Moves the main
* application window to the point with coordinates - x, y.
*
* @param x the value of X where the main application frame is to be placed.
* @param y the value of Y where the main application frame is to be placed.
*
* @see UIService#move(int, int)
*/
public void move(int x, int y)
{
this.mainFrame.setLocation(x, y);
}
/**
* Implements the <code>UIService.setExitOnMainWindowClose</code>. Sets a
* boolean property, which indicates whether the application should be
* exited when the main application window is closed.
*
* @param exitOnClose specifies if closing the main application window
* should also be exiting the application.
*/
public void setExitOnMainWindowClose(boolean exitOnClose)
{
this.exitOnClose = exitOnClose;
if (exitOnClose)
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
else
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
/**
* Implements the <code>UIService.getExitOnMainWindowClose</code>.
* Returns the boolean property, which indicates whether the application
* should be exited when the main application window is closed.
*
* @return determines whether the UI impl would exit the application when
* the main application window is closed.
*/
public boolean getExitOnMainWindowClose()
{
return this.exitOnClose;
}
/**
* Adds all <tt>ExportedWindow</tt>s to the list of application windows,
* which could be used from other bundles. Once registered in the
* <tt>UIService</tt> this window could be obtained through the
* <tt>getExportedWindow(WindowID)</tt> method and could be shown,
* hidden, resized, moved, etc.
*/
public void initExportedWindows()
{
AddContactWizard addContactWizard = new AddContactWizard(mainFrame);
exportedWindows.put(configurationFrame.getIdentifier(),
configurationFrame);
exportedWindows.put(addContactWizard.getIdentifier(), addContactWizard);
}
/**
* Registers the given <tt>ExportedWindow</tt> to the list of windows that
* could be accessed from other bundles.
*
* @param window the window to be exported
*/
public void registerExportedWindow(ExportedWindow window)
{
exportedWindows.put(window.getIdentifier(), window);
}
/**
* Sets the contact list service to this UI Service implementation.
* @param contactList the MetaContactList service
*/
public void setContactList(MetaContactListService contactList)
{
this.mainFrame.setContactList(contactList);
}
public void addPluginComponentListener(PluginComponentListener l)
{
synchronized (pluginComponentListeners)
{
pluginComponentListeners.add(l);
}
}
public void removePluginComponentListener(PluginComponentListener l)
{
synchronized (pluginComponentListeners)
{
pluginComponentListeners.remove(l);
}
}
/**
* Implements <code>getSupportedExportedWindows</code> in the UIService
* interface. Returns an iterator over a set of all windows exported by
* this implementation.
*
* @return an Iterator over all windows exported by this implementation of
* the UI service.
*
* @see UIService#getSupportedExportedWindows()
*/
public Iterator getSupportedExportedWindows()
{
return Collections.unmodifiableMap(exportedWindows).keySet().iterator();
}
/**
* Implements the <code>getExportedWindow</code> in the UIService
* interface. Returns the window corresponding to the given
* <tt>WindowID</tt>.
*
* @param windowID the id of the window we'd like to retrieve.
*
* @return a reference to the <tt>ExportedWindow</tt> instance corresponding
* to <tt>windowID</tt>.
* @see UIService#getExportedWindow(WindowID)
*/
public ExportedWindow getExportedWindow(WindowID windowID)
{
if (exportedWindows.containsKey(windowID))
{
return (ExportedWindow) exportedWindows.get(windowID);
}
return null;
}
/**
* Implements the <code>UIService.isExportedWindowSupported</code> method.
* Checks if there's an exported component for the given
* <tt>WindowID</tt>.
*
* @param windowID the id of the window that we're making the query for.
*
* @return true if a window with the corresponding windowID is exported by
* the UI service implementation and false otherwise.
*
* @see UIService#isExportedWindowSupported(WindowID)
*/
public boolean isExportedWindowSupported(WindowID windowID)
{
return exportedWindows.containsKey(windowID);
}
/**
* Implements <code>getPopupDialog</code> in the UIService interface.
* Returns a <tt>PopupDialog</tt> that could be used to show simple
* messages, warnings, errors, etc.
*
* @return a <tt>PopupDialog</tt> that could be used to show simple
* messages, warnings, errors, etc.
*
* @see UIService#getPopupDialog()
*/
public PopupDialog getPopupDialog()
{
return this.popupDialog;
}
/**
* Implements <code>getChat</code> in the UIService interface. If a
* chat for the given contact exists already - returns it, otherwise
* creates a new one.
*
* @param contact the contact that we'd like to retrieve a chat window for.
*
* @return a Chat corresponding to the specified contact.
*
* @see UIService#getChat(Contact)
*/
public Chat getChat(Contact contact)
{
MetaContact metaContact = mainFrame.getContactList()
.findMetaContactByContact(contact);
ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager();
MetaContactChatPanel chatPanel
= chatWindowManager.getContactChat(metaContact);
return chatPanel;
}
/**
* Returns the <tt>Chat</tt> corresponding to the given <tt>ChatRoom</tt>.
*
* @param chatRoom the <tt>ChatRoom</tt> for which the searched chat is
* about.
* @return the <tt>Chat</tt> corresponding to the given <tt>ChatRoom</tt>.
*/
public Chat getChat(ChatRoom chatRoom)
{
ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager();
ConferenceChatPanel chatPanel
= chatWindowManager.getMultiChat(chatRoom);
return chatPanel;
}
/**
* Returns the selected <tt>Chat</tt>.
*
* @return the selected <tt>Chat</tt>.
*/
public Chat getCurrentChat()
{
ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager();
return chatWindowManager.getSelectedChat();
}
/**
* Implements the <code>UIService.isContainerSupported</code> method.
* Checks if the plugable container with the given ContainerID is supported
* by this implementation.
*
* @param containderID the id of the container that we're making the query
* for.
*
* @return true if the container with the specified id is exported by the
* implementation of the UI service and false otherwise.
*
* @see UIService#isContainerSupported(ContainerID)
*/
public boolean isContainerSupported(ContainerID containderID)
{
return supportedContainers.contains(containderID);
}
/**
* Implements the <code>UIService.getAccountRegWizardContainer</code>
* method. Returns the current implementation of the
* <tt>AccountRegistrationWizardContainer</tt>.
*
* @see UIService#getAccountRegWizardContainer()
*
* @return a reference to the currently valid instance of
* <tt>AccountRegistrationWizardContainer</tt>.
*/
public AccountRegistrationWizardContainer getAccountRegWizardContainer()
{
return this.wizardContainer;
}
/**
* Implements the <code>UIService.getConfigurationWindow</code>. Returns
* the current implementation of the <tt>ConfigurationWindow</tt>
* interface.
*
* @see UIService#getConfigurationWindow()
*
* @return a reference to the currently valid instance of
* <tt>ConfigurationWindow</tt>.
*/
public ConfigurationWindow getConfigurationWindow()
{
return this.configurationFrame;
}
public ExportedWindow getAuthenticationWindow(
ProtocolProviderService protocolProvider,
String realm, UserCredentials userCredentials)
{
return new AuthenticationWindow(mainFrame, protocolProvider,
realm, userCredentials);
}
/**
* Returns the LoginManager.
* @return the LoginManager
*/
public LoginManager getLoginManager()
{
return loginManager;
}
/**
* Returns the <tt>MainFrame</tt>. This is the class defining the main
* application window.
*
* @return the <tt>MainFrame</tt>
*/
public MainFrame getMainFrame()
{
return mainFrame;
}
/**
* The <tt>RunLogin</tt> implements the Runnable interface and is used to
* shows the login windows in a seperate thread.
*/
private class RunLoginGui implements Runnable {
public void run() {
loginManager.runLogin(mainFrame);
}
}
/**
* The <tt>RunApplication</tt> implements the Runnable interface and is used to
* shows the main application window in a separate thread.
*/
private class RunApplicationGui implements Runnable {
public void run() {
mainFrame.setVisible(true);
}
}
/**
* Sets the look&feel and the theme.
*/
private void setDefaultThemePack() {
SIPCommLookAndFeel lf = new SIPCommLookAndFeel();
SIPCommLookAndFeel.setCurrentTheme(new SIPCommDefaultTheme());
// we need to set the UIDefaults class loader so that it may access
// resources packed inside OSGI bundles
UIManager.put("ClassLoader", getClass().getClassLoader());
try {
UIManager.setLookAndFeel(lf);
} catch (UnsupportedLookAndFeelException e) {
logger.error("The provided Look & Feel is not supported.", e);
}
}
} |
package com.sun.star.lib.sandbox;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.BorderLayout;
import java.applet.Applet;
import java.applet.AppletStub;
import java.applet.AppletContext;
import java.applet.AudioClip;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.Observable;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public abstract class ExecutionContext extends Observable {
private static final boolean DEBUG = false;
private static int instances;
/* message ids */
protected final static int CMD_LOAD = 1;
protected final static int CMD_INIT = 2;
protected final static int CMD_START = 3;
protected final static int CMD_STOP = 4;
protected final static int CMD_DESTROY = 5;
protected final static int CMD_DISPOSE = 6;
protected final static int LOADED = 1;
protected final static int INITED = 2;
protected final static int STARTED = 3;
protected final static int STOPPED = 4;
protected final static int DESTROYED = 5;
protected final static int DISPOSED = 6;
private int status = DISPOSED;
private Object statusLock= new Object();
private boolean bDispatchException;
protected ClassContext classContext;
private Thread dispatchThread = null;
private SandboxThreadGroup threadGroup = null;
private String name;
protected ResourceBundle resourceBundle;
private Object synObj = new Object();
private Message head;
private Message tail;
private boolean loop = true;
protected ExecutionContext() {
instances ++;
}
public void finalize() {
instances
}
public int getStatus() {
return status;
}
Object getSynObject() {
return synObj;
}
class Message {
Message next;
int id;
Message(int id) {
this.id = id;
}
}
public void init(String name, ClassContext classContext) throws MissingResourceException {
this.name = name;
resourceBundle = ResourceBundle.getBundle("sun.applet.resources.MsgAppletViewer");
this.classContext = classContext;
threadGroup = new SandboxThreadGroup(classContext.getThreadGroup(), name, classContext.getClassLoader());
threadGroup.setDaemon(true);
dispatchThread = new Thread( threadGroup, new Runnable() {
public void run() {
while( loop ) {
if( head != null) {
if (DEBUG) System.err.println("
dispatch( head.id );
if (DEBUG) System.err.println("
synchronized( getSynObject() ) {
head = head.next;
getSynObject().notify();
}
}
synchronized( getSynObject() ) {
if (head == null) {
try {
getSynObject().wait();
}
catch (InterruptedException e ) {
if (DEBUG) System.err.println("
break;
}
}
}
}
if(DEBUG) System.err.println("
}
});
dispatchThread.setDaemon(true);
dispatchThread.start();
}
public void sendEvent(int id) {
sendEvent(id, 0);
}
public void sendEvent(int id, int timeout) {
synchronized( getSynObject() ) {
try {
Message message = new Message(id);
if(tail != null)
tail.next = message;
tail = message;
if(head == null)
head = tail;
getSynObject().notify();
if ( timeout != 0 )
getSynObject().wait( timeout );
}
catch( InterruptedException e ) {
}
}
}
public void dispose() {
//if(DEBUG) System.err.println("
dispose(1000);
}
public void dispose( long timeout ) {
if(DEBUG) System.err.println("
try {
try {
synchronized( getSynObject() ) {
while( head != null )
getSynObject().wait( timeout ); // wait at most one second for each queued command
loop = false;
getSynObject().notifyAll();
}
dispatchThread.join(timeout);
}
catch(InterruptedException ee) {
if(DEBUG) System.err.println("
}
if(DEBUG) threadGroup.list();
if ( !threadGroup.isDestroyed() )
threadGroup.destroy();
}
catch (Exception ie) {
if(DEBUG) System.err.println("
try {
threadGroup.stop();
} catch (Exception se) {
if(DEBUG) System.err.println("
}
}
classContext = null;
dispatchThread = null;
threadGroup.dispose();
threadGroup = null;
name = null;
resourceBundle = null;
synObj = null;
head = null;
tail = null;
}
protected void showStatus(String status) {
if (DEBUG) System.err.println("
setChanged();
notifyObservers(resourceBundle.getString("appletpanel." + status));
}
protected void showStatus(String status, String arg1) {
if(DEBUG) System.err.println("
try {
Object args[] = new Object[1];
args[0] = arg1;
setChanged();
try {
notifyObservers(MessageFormat.format(resourceBundle.getString("appletpanel." + status), args));
}
catch(MissingResourceException me) {}
}
catch(Exception ee) {
if(DEBUG)System.err.println("
}
}
public ThreadGroup getThreadGroup() {
return threadGroup;
}
/**
* Send an event. Queue it for execution by the handler thread.
*/
public void dispatch(int id) {
try {
switch(id) {
case CMD_LOAD:
if (status == DISPOSED) {
xload();
setStatus(LOADED);
showStatus("loaded");
}
else
showStatus("notdisposed");
break;
case CMD_INIT:
if(status == LOADED || status == DESTROYED) {
xinit();
setStatus(INITED);
showStatus("inited");
}
else
showStatus("notloaded");
break;
case CMD_START:
if (status == INITED || status == STOPPED) {
xstart();
setStatus(STARTED);
showStatus("started");
}
else
showStatus("notinited");
break;
case CMD_STOP:
if (status == STARTED) {
xstop();
setStatus(STOPPED);
showStatus("stopped");
}
else
showStatus("notstarted");
break;
case CMD_DESTROY:
if(status == INITED || status == STOPPED) {
xdestroy();
setStatus(DESTROYED);
showStatus("destroyed");
}
else
showStatus("notstopped");
break;
case CMD_DISPOSE:
if (status == LOADED || status == DESTROYED) {
xdispose();
// baseResourceLoader.flush();
showStatus("disposed");
setStatus(DISPOSED);
}
else
showStatus("notdestroyed");
break;
default:
xExtended(id);
}
}
catch (ClassNotFoundException classNotFoundException) {
setDispatchException();
showStatus("notfound", name);
if(DEBUG) classNotFoundException.printStackTrace();
}
catch (InstantiationException instantiationException) {
setDispatchException();
showStatus("nocreate", name);
if(DEBUG) instantiationException.printStackTrace();
}
catch (IllegalAccessException illegalAccessException) {
setDispatchException();
showStatus("noconstruct", name);
if(DEBUG) illegalAccessException.printStackTrace();
}
catch (Exception exception) {
setDispatchException();
showStatus("exception", exception.getMessage());
if(DEBUG) exception.printStackTrace();
}
catch (ThreadDeath threadDeath) {
setDispatchException();
showStatus("death");
if(DEBUG) threadDeath.printStackTrace();
throw threadDeath;
}
catch (Error error) {
setDispatchException();
showStatus("error", error.getMessage());
if(DEBUG) error.printStackTrace();
}
}
protected abstract void xload() throws ClassNotFoundException, InstantiationException, IllegalAccessException;
protected abstract void xinit();
protected abstract void xstart();
protected abstract void xstop();
protected abstract void xdestroy();
protected abstract void xdispose();
protected void xExtended(int id) {
}
public void sendLoad() {
sendEvent(CMD_LOAD);
}
public void sendInit() {
sendEvent(CMD_INIT);
}
public void sendStart() {
sendEvent(CMD_START);
}
public void sendStop() {
sendEvent(CMD_STOP);
}
public void sendDestroy() {
sendEvent(CMD_DESTROY);
}
public void sendDispose() {
sendEvent(CMD_DISPOSE);
}
public void startUp() {
sendLoad();
sendInit();
sendStart();
}
public void shutdown() {
sendStop();
sendDestroy();
sendDispose();
}
public void restart() {
sendStop();
sendDestroy();
sendInit();
sendStart();
}
public void reload() {
sendStop();
sendDestroy();
sendDispose();
sendLoad();
sendInit();
sendStart();
}
/** This function blocks until the status of ExecutionContext is DISPOSED or
* an Exeption occurred during a call to the AppletExecutionContext in dispatch.
* @see #dispatch
* @see #setStatus
* @see #setDispatchException
*/
public void waitForDispose() {
if (status == DISPOSED || bDispatchException)
return;
else
{
// wait until status is disposed
synchronized (statusLock) {
while (status != DISPOSED && !bDispatchException) {
try {
statusLock.wait();
} catch (java.lang.InterruptedException e) {
}
}
}
}
System.err.println("exit");
}
protected void setStatus( int newStatus) {
synchronized (statusLock) {
status= newStatus;
statusLock.notifyAll();
}
}
protected void setDispatchException() {
synchronized (statusLock) {
bDispatchException= true;
statusLock.notifyAll();
}
}
} |
package org.jastadd.tinytemplate.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.jastadd.tinytemplate.SimpleContext;
import org.jastadd.tinytemplate.TemplateParser.SyntaxError;
import org.jastadd.tinytemplate.TinyTemplate;
import org.junit.Test;
public class TestConditionals {
private static final String NL = System.getProperty("line.separator");
/**
* Constructor
*/
public TestConditionals() {
TinyTemplate.printWarnings(false);
TinyTemplate.throwExceptions(false);
}
/**
* Test alternate form of if-then-else with hash sign instead of dollar sign
* @throws SyntaxError
*/
@Test
public void testAlternate_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[#if(cond)boo!#(else)mjau#endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "");
assertEquals("mjau", tc.expand("foo"));
}
/**
* Test an attribute condition
* @throws SyntaxError
*/
@Test
public void testAttributeCondition_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if(#toString)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, "true");
assertEquals("Woof!", tc.expand("dog"));
}
/**
* Test an attribute condition
* @throws SyntaxError
*/
@Test
public void testAttributeCondition_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if(#toString)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, "false");
assertEquals("", tc.expand("dog"));
}
/**
* Test a negated attribute condition
* @throws SyntaxError
*/
@Test
public void testAttributeCondition_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if(!#toString)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, "false");
assertEquals("Woof!", tc.expand("dog"));
}
/**
* Test the if-then conditional
* @throws SyntaxError
*/
@Test
public void testConditional_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$if(cond)boo!$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "true");
assertEquals("boo!", tc.expand("foo"));
}
/**
* Test the if-then conditional
* @throws SyntaxError
*/
@Test
public void testConditional_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$if(cond)boo!$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "not true");
assertEquals("", tc.expand("foo"));
}
/**
* Case sensitive "true"
* @throws SyntaxError
*/
@Test
public void testConditional_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$if(cond)boo!$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "True");
assertEquals("", tc.expand("foo"));
}
/**
* Test the if-then-else conditional
* @throws SyntaxError
*/
@Test
public void testConditional_4() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$if(cond)boo!$(else)mjau$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "");
assertEquals("mjau", tc.expand("foo"));
}
/**
* Test the if-then-else conditional with negated condition
* @throws SyntaxError
*/
@Test
public void testConditional_5() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$if(!cond)boo!$(else)mjau$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("cond", "");
assertEquals("boo!", tc.expand("foo"));
}
/**
* Test whitespace before the condition
* @throws SyntaxError
*/
@Test
public void testConditional_6() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if \t (x)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("x", true);
assertEquals("Woof!", tc.expand("dog"));
}
/**
* Whitespace is trimmed from the condition string
* @throws SyntaxError
*/
@Test
public void testConditional_7() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if(\tx )Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("x", true);
assertEquals("Woof!", tc.expand("dog"));
}
/**
* Whitespace is trimmed from the condition string
* @throws SyntaxError
*/
@Test
public void testConditional_8() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if( ! \tx )Woof!$(else)silence$endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("x", true);
assertEquals("silence", tc.expand("dog"));
}
/**
* Extra exclamation marks in condition
* @throws SyntaxError
*/
@Test
public void testConditional_9() throws SyntaxError {
try {
new TinyTemplate("dog = [[$if(!!x)Woof!$(else)silence$endif]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("illegal characters in variable name '!x'", e.getMessage());
}
}
/**
* A dollar sign is allowed for variable conditions
* @throws SyntaxError
*/
@Test
public void testConditional_10() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if($x)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, this);
tc.bind("x", "true");
assertEquals("Woof!", tc.expand("dog"));
}
/**
* A dollar sign is allowed for variable conditions
* @throws SyntaxError
*/
@Test
public void testConditional_11() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("dog = [[$if(!$x)Woof!$endif]]");
SimpleContext tc = new SimpleContext(tt, this);
tc.bind("x", "true");
assertEquals("", tc.expand("dog"));
}
@Test
public void testConditionError_1() throws SyntaxError {
try {
new TinyTemplate("dog = [[$if(x%)Woof!$(else)silence$endif]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("illegal characters in variable name 'x%'", e.getMessage());
}
}
@Test
public void testConditionError_2() throws SyntaxError {
try {
new TinyTemplate("dog = [[$if(#x.y)Woof!$(else)silence$endif]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("the attribute name 'x.y' is not a valid Java identifier", e.getMessage());
}
}
/**
* Test nested conditional
* @throws SyntaxError
*/
@Test
public void testNested_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"Father = [[" +
"$if(x) x\n" +
"$if(y)Wednesday$endif y" +
"$endif" +
"]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("x", "true");
tc.bind("y", "true");
assertEquals(" x" + NL + "Wednesday y", tc.expand("Father"));
}
/**
* Stray else
* @throws SyntaxError
*/
@Test
public void testSyntaxError_1() throws SyntaxError {
try {
new TinyTemplate("dog = [[$else]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("Syntax error at line 1: stray $else", e.getMessage());
}
}
/**
* Stray endif
* @throws SyntaxError
*/
@Test
public void testSyntaxError_2() throws SyntaxError {
try {
new TinyTemplate("dog = [[$endif]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("Syntax error at line 1: stray $endif", e.getMessage());
}
}
/**
* Missing endif
* @throws SyntaxError
*/
@Test
public void testSyntaxError_3() throws SyntaxError {
try {
new TinyTemplate("dog = [[$if(x)]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("Syntax error at line 1: missing $endif", e.getMessage());
}
}
/**
* Missing endif
* @throws SyntaxError
*/
@Test
public void testSyntaxError_4() throws SyntaxError {
try {
new TinyTemplate("dog = [[$if(x)$else]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("Syntax error at line 1: missing $endif", e.getMessage());
}
}
/**
* Extra else inside if-else
* @throws SyntaxError
*/
@Test
public void testSyntaxError_5() throws SyntaxError {
try {
new TinyTemplate("dog = [[\n" +
"$if(x)\n" +
"$else\n" +
"$else]]");
fail("Expected syntax error!");
} catch (SyntaxError e) {
assertEquals("Syntax error at line 4: too many $else", e.getMessage());
}
}
/**
* Test trimming leading newline in conditional body
* @throws SyntaxError
*/
@Test
public void testTrimming_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[" +
"$if(bark) \t \n" +
"Woof!\n" +
"$endif" +
"]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", "true");
assertEquals("Woof!" + NL, tc.expand("dog"));
}
/**
* If the conditional is surrounded by whitespace then the surrounding
* whitespace up to and including the newline is removed.
* @throws SyntaxError
*/
@Test
public void testTrimming_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[ $if(bark)Woof!$endif \n]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", "true");
assertEquals("Woof!", tc.expand("dog"));
}
/**
* Don't trim whitespace around the conditional if it has non-whitespace
* surrounding it
* @throws SyntaxError
*/
@Test
public void testTrimming_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[ $if(bark)Woof!$endif ;\n]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", "true");
assertEquals(" Woof! ;" + NL, tc.expand("dog"));
}
/**
* Don't trim whitespace around the conditional if there is another
* conditional on the same line
* @throws SyntaxError
*/
@Test
public void testTrimming_4() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[ $if(bark)Woof!$endif $if(bark)Woof!$endif\n]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", "true");
assertEquals(" Woof! Woof!" + NL, tc.expand("dog"));
}
/**
* Trim trailing empty line if there is nothing after the <code>endif</code>
* @throws SyntaxError
*/
@Test
public void testTrimming_5() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[ $if(bark)\n" +
" Woof!\n" +
" $endif]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", "true");
assertEquals(" Woof!" + NL, tc.expand("dog"));
}
/**
* Trim empty trailing line if the <code>else</code> is on it's own line
* @throws SyntaxError
*/
@Test
public void testTrimming_6() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"dog = [[ $if(!bark)\n" +
" Notwoof \n" +
" \t$else \n" +
" Woof!\n" +
" $endif ]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("bark", true);
assertEquals(" Woof!", tc.expand("dog"));
tc.bind("bark", false);
assertEquals(" Notwoof ", tc.expand("dog"));
}
} |
package edu.brandeis.cs.steele.wn;
import edu.brandeis.cs.steele.util.ArrayUtilities;
import java.util.*;
import static edu.brandeis.cs.steele.wn.PointerTypeFlags.*;
/** Instances of this class enumerate the possible WordNet pointer types, and
* are used to label <code>PointerType</code>s.
* Each <code>PointerType</code> carries additional information:
* <ul>
* <li> a human-readable label </li>
* <li> an optional reflexive type that labels links pointing the opposite direction </li>
* <li> an encoding of parts-of-speech that it applies to </li>
* <li> a short string (lemma) that represents it in the dictionary files </li>
* </ul>
*
* @see Pointer
* @see POS
* @author Oliver Steele, steele@cs.brandeis.edu
* @version 1.0
*/
public enum PointerType {
// All parts of speech
ANTONYM("antonym", "!", N | V | ADJ | ADV | LEXICAL),
DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", N | V | ADJ | ADV),
MEMBER_OF_THIS_DOMAIN_TOPIC("Member of this domain - TOPIC", "-c", N | V | ADJ | ADV),
DOMAIN_OF_REGION("Domain of synset - REGION", ";r", N | V | ADJ | ADV),
MEMBER_OF_THIS_DOMAIN_REGION("Member of this domain - REGION", "-r", N | V | ADJ | ADV),
DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", N | V | ADJ | ADV),
MEMBER_OF_THIS_DOMAIN_USAGE("Member of this domain - USAGE", "-u", N | V | ADJ | ADV),
DOMAIN_MEMBER("Domain Member", "-", N | V | ADJ | ADV),
DOMAIN("Domain", ";", N | V | ADJ | ADV),
// Nouns and Verbs
HYPERNYM("hypernym", "@", N | V),
INSTANCE_HYPERNYM("instance hypernym", "@i", N | V),
HYPONYM("hyponym", "~", N | V),
INSTANCE_HYPONYM("instance hyponym", "~i", N | V),
DERIVATIONALLY_RELATED("derivationally related", "+", N | V),
// Nouns and Adjectives
ATTRIBUTE("attribute", "=", N | ADJ),
SEE_ALSO("also see", "^", N | ADJ | LEXICAL),
// Verbs
ENTAILMENT("entailment", "*", V),
CAUSE("cause", ">", V),
VERB_GROUP("verb group", "$", V),
// Nouns
MEMBER_MERONYM("member meronym", "%m", N),
SUBSTANCE_MERONYM("substance meronym", "%s", N),
PART_MERONYM("part meronym", "%p", N),
MEMBER_HOLONYM("member holonym", "#m", N),
SUBSTANCE_HOLONYM("substance holonym", "#s", N),
PART_HOLONYM("part holonym", "#p", N),
MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", N),
MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", N),
MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", N),
// Adjectives
SIMILAR_TO("similar", "&", ADJ),
PARTICIPLE_OF("participle of", "<", ADJ | LEXICAL),
PERTAINYM("pertainym", "\\", ADJ | LEXICAL),
// Adverbs
DERIVED("derived from", "\\", ADV); // from adjective
private static final POS[] CATS = {POS.NOUN, POS.VERB, POS.ADJ, POS.ADV, POS.SAT_ADJ};
private static final int[] POS_MASK = {N, V, ADJ, ADV, SAT_ADJ, LEXICAL};
/** A list of all <code>PointerType</code>s. */
public static final PointerType[] TYPES = {
ANTONYM, HYPERNYM, HYPONYM, ATTRIBUTE, SEE_ALSO,
ENTAILMENT, CAUSE, VERB_GROUP,
MEMBER_MERONYM, SUBSTANCE_MERONYM, PART_MERONYM,
MEMBER_HOLONYM, SUBSTANCE_HOLONYM, PART_HOLONYM,
SIMILAR_TO, PARTICIPLE_OF, PERTAINYM, DERIVED,
DOMAIN_OF_TOPIC, MEMBER_OF_THIS_DOMAIN_TOPIC, DOMAIN_OF_REGION, DOMAIN_OF_USAGE,
MEMBER_OF_THIS_DOMAIN_REGION, MEMBER_OF_THIS_DOMAIN_USAGE,
MEMBER_OF_TOPIC_DOMAIN, MEMBER_OF_REGION_DOMAIN, MEMBER_OF_USAGE_DOMAIN,
DERIVATIONALLY_RELATED,
INSTANCE_HYPERNYM, INSTANCE_HYPONYM
};
static {
// seems to be 30
//assert TYPES.length == 32 : "TYPES.length: "+TYPES.length+" "+Arrays.toString(TYPES);
}
public static final PointerType[] INDEX_ONLY = { DOMAIN_MEMBER, DOMAIN };
static private void setSymmetric(final PointerType a, final PointerType b) {
a.symmetricType = b;
b.symmetricType = a;
}
/**
* Index-only pointer types are used for the sole purpose of parsing index file records.
* They are not used to determine relationships between words.
* @param pType
* @return True if the pType is an index-only pointer type. Otherwise, it is false.
*/
public static boolean isIndexOnly(PointerType pType) {
for (int i=0; i<INDEX_ONLY.length; ++i) {
if (pType.getKey().equals(INDEX_ONLY[i].getKey())) {
return true;
}
}
return false;
}
static {
setSymmetric(ANTONYM, ANTONYM);
setSymmetric(HYPERNYM, HYPONYM);
setSymmetric(INSTANCE_HYPERNYM, INSTANCE_HYPONYM);
setSymmetric(MEMBER_MERONYM, MEMBER_HOLONYM);
setSymmetric(SUBSTANCE_MERONYM, SUBSTANCE_HOLONYM);
setSymmetric(PART_MERONYM, PART_HOLONYM);
setSymmetric(SIMILAR_TO, SIMILAR_TO);
setSymmetric(ATTRIBUTE, ATTRIBUTE);
setSymmetric(DERIVATIONALLY_RELATED, DERIVATIONALLY_RELATED);
setSymmetric(DOMAIN_OF_TOPIC, MEMBER_OF_TOPIC_DOMAIN);
setSymmetric(DOMAIN_OF_REGION, MEMBER_OF_REGION_DOMAIN);
setSymmetric(DOMAIN_OF_USAGE, MEMBER_OF_USAGE_DOMAIN);
setSymmetric(DOMAIN_OF_TOPIC, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_REGION, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_USAGE, DOMAIN_MEMBER);
setSymmetric(VERB_GROUP, VERB_GROUP);
}
/** Return the <code>PointerType</code> whose key matches <var>key</var>.
* @exception NoSuchElementException If <var>key</var> doesn't name any <code>PointerType</code>.
*/
static PointerType parseKey(final CharSequence key) {
for (int i = 0; i < TYPES.length; ++i) {
final PointerType type = TYPES[i];
if (type.key.contentEquals(key)) {
return type;
}
}
for (int i = 0; i < INDEX_ONLY.length; ++i) {
final PointerType type = INDEX_ONLY[i];
if (type.key.contentEquals(key)) {
return type;
}
}
throw new NoSuchElementException("unknown link type " + key);
}
/*
* Instance Interface
*/
private final String label;
private final String key;
private final int flags;
private PointerType symmetricType;
private PointerType(final String label, final String key, final int flags) {
this.label = label;
this.key = key;
this.flags = flags;
}
@Override public String toString() {
return getLabel()+" "+getKey();
}
public String getLabel() {
return label;
}
public String getKey() {
return this.key;
}
public boolean appliesTo(final POS pos) {
return (flags & POS_MASK[ArrayUtilities.indexOf(CATS, pos)]) != 0;
}
public boolean symmetricTo(final PointerType type) {
return symmetricType != null && symmetricType.equals(type);
}
}
/**
* Flags for tagging a pointer type with the POS types it apples to.
* Separate class to allow PointerType enum constructor to reference it.
*/
class PointerTypeFlags {
static final int N = 1;
static final int V = 2;
static final int ADJ = 4;
static final int ADV = 8;
static final int SAT_ADJ = 16;
static final int LEXICAL = 32;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.