answer stringlengths 17 10.2M |
|---|
package org.jetel.data.parser;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.CloverDataRecordSerializer;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.DataRecordSerializer;
import org.jetel.data.Defaults;
import org.jetel.data.formatter.CloverDataFormatter;
import org.jetel.data.formatter.CloverDataFormatter.DataCompressAlgorithm;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.IParserExceptionHandler;
import org.jetel.exception.JetelException;
import org.jetel.exception.PolicyType;
import org.jetel.graph.ContextProvider;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.metadata.DataRecordMetadataXMLReaderWriter;
import org.jetel.util.bytes.ByteBufferUtils;
import org.jetel.util.bytes.CloverBuffer;
import org.jetel.util.file.FileUtils;
import org.jetel.util.primitive.BitArray;
import org.jetel.util.stream.CloverDataStream;
public class CloverDataParser extends AbstractParser implements ICloverDataParser {
public static class FileConfig {
public byte majorVersion;
public byte minorVersion;
public byte revisionVersion;
public int compressionAlgorithm;
public CloverDataFormatter.DataFormatVersion formatVersion;
public DataRecordMetadata metadata;
public boolean raw;
}
private final static Log logger = LogFactory.getLog(CloverDataParser.class);
private DataRecordMetadata metadata;
private ReadableByteChannel recordFile;
private CloverDataStream.Input input;
private CloverBuffer recordBuffer;
private InputStream inStream;
private URL projectURL;
private DataRecordSerializer serializer;
private CloverDataFormatter.DataCompressAlgorithm compress;
/** Clover version which has been used to create the input data file. */
private FileConfig version;
private boolean useParsingFromJobflow_3_4 = false;
/**
* True, if the current transformation is jobflow.
*/
private boolean isJobflow;
private final static int LONG_SIZE_BYTES = 8;
private final static int LEN_SIZE_SPECIFIER = 4;
public CloverDataParser(DataRecordMetadata metadata){
this.metadata = metadata;
this.compress = DataCompressAlgorithm.NONE;
}
public FileConfig getVersion() {
return version;
}
public InputStream getInStream() {
return inStream;
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#getNext()
*/
@Override
public DataRecord getNext() throws JetelException {
DataRecord record = DataRecordFactory.newRecord(metadata);
record.init();
return getNext(record);
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#skip(int)
*/
@Override
public int skip(int nRec) throws JetelException {
if (nRec == 0) {
return 0;
}
if (isDirectReadingSupported()) {
CloverBuffer buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
for (int skipped = 0; skipped < nRec; skipped++) {
if (!getNextDirect(buffer)) {
return skipped;
}
}
} else {
DataRecord record = DataRecordFactory.newRecord(metadata);
record.init();
for (int skipped = 0; skipped < nRec; skipped++) {
if (getNext(record) == null) {
return skipped;
}
}
}
return nRec;
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#init(org.jetel.metadata.DataRecordMetadata)
*/
@Override
public void init() throws ComponentNotReadyException {
if (metadata == null) {
throw new ComponentNotReadyException("Metadata are null");
}
recordBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
recordBuffer.order(CloverDataFormatter.BUFFER_BYTE_ORDER);
serializer=new CloverDataRecordSerializer();
}
private void doReleaseDataSource() throws IOException {
if (inStream != null) {
inStream.close();
inStream = null; // setDataSource() tests inStream for null
}
}
@Override
protected void releaseDataSource() {
try {
doReleaseDataSource();
} catch (IOException ioe) {
logger.warn("Failed to release data source", ioe);
}
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object)
*
* parameter: data fiele name or {data file name, index file name}
*/
@Override
public void setDataSource(Object in) throws ComponentNotReadyException {
String inData=null;
if (releaseDataSource) {
releaseDataSource();
}
if (in instanceof InputStream) {
inStream = (InputStream) in;
}else if (in instanceof ReadableByteChannel){
inStream = Channels.newInputStream((ReadableByteChannel)in);
}else if (in instanceof File){
try {
inStream = new FileInputStream((File)in);
} catch (IOException e) {
throw new ComponentNotReadyException(e);
}
}else if (in instanceof String[]) {
inData = ((String[])in)[0];
}else if (in instanceof String){
inData = (String)in;
}else{
throw new ComponentNotReadyException("Unsupported Data Source type: "+in.getClass().getName());
}
if (inStream==null) { // doReleaseDataSource() should set the previous stream to null
try{
String fileName = new File(FileUtils.getFile(projectURL, inData)).getName();
if (fileName.toLowerCase().endsWith(".zip")) {
fileName = fileName.substring(0,fileName.lastIndexOf('.'));
}
inStream = FileUtils.getInputStream(projectURL, !inData.startsWith("zip:") ? inData :
inData + "#" + CloverDataFormatter.DATA_DIRECTORY + fileName);
} catch (IOException ex) {
throw new ComponentNotReadyException(ex);
}
}
//read and check header of clover binary data format to check out the compatibility issues
version = checkCompatibilityHeader(inStream, metadata);
if(version.formatVersion!=CloverDataFormatter.CURRENT_FORMAT_VERSION){
return;
}
this.compress=DataCompressAlgorithm.getAlgorithm(version.compressionAlgorithm);
//is the current transformation jobflow?
isJobflow = ContextProvider.getRuntimeContext() != null
&& ContextProvider.getRuntimeContext().getJobType().isJobflow();
//special de-serialisation needs to be used, see CLO-1382
if (version.majorVersion == 3
&& (version.minorVersion == 3 || version.minorVersion == 4)
&& isJobflow) {
useParsingFromJobflow_3_4 = true;
}
switch(compress){
case NONE:
this.input= new CloverDataStream.Input(inStream);
break;
case LZ4:
this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorLZ4());
break;
case GZIP:
this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorGZIP());
break;
default:
throw new RuntimeException("Unsupported compression algorithm: "+compress);
}
}
public static FileConfig checkCompatibilityHeader(ReadableByteChannel recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException {
return checkCompatibilityHeader(Channels.newInputStream(recordFile),metadata);
}
public static FileConfig checkCompatibilityHeader(InputStream recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException {
byte[] extraBytes;
CloverBuffer buffer = CloverBuffer.wrap(new byte[CloverDataFormatter.CLOVER_DATA_HEADER_LENGTH]);
try {
int count = recordFile.read(buffer.array());
if (count != buffer.capacity()) {
throw new IOException("Failed to read file header");
}
} catch (IOException e) {
throw new ComponentNotReadyException(e);
}
//read clover binary data header and check backward compatibility
//better header description is at CloverDataFormatter.setDataTarget() method
long cloverHash=buffer.getLong();
if (CloverDataFormatter.CLOVER_DATA_HEADER != cloverHash) {
//clover binary data format is definitely incompatible with current version - header is not present
throw new ComponentNotReadyException("Source clover data file is obsolete. Data cannot be read.");
}
long cloverDataCompatibilityHash = buffer.getLong();
FileConfig version = new FileConfig();
version.majorVersion = buffer.get();
version.minorVersion = buffer.get();
version.revisionVersion = buffer.get();
if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_2_9){
version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_29;
}else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_3_5){
version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_35;
}else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_4_0){
version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_40;
}else{
throw new ComponentNotReadyException("Invallid Clover Data Compatibility Hash: "+cloverDataCompatibilityHash);
}
switch(version.formatVersion){
case VERSION_29:
case VERSION_35:
extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE_3_5];
try {
recordFile.read(extraBytes);
} catch (IOException e) {
throw new ComponentNotReadyException(e);
}
if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) {
throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read.");
}
// what's left is metadata serialized, will let this to "other" parser
break;
case VERSION_40:
extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE];
try {
int count = recordFile.read(extraBytes);
if (count != extraBytes.length) {
throw new IOException("Failed to read file header");
}
} catch (IOException e) {
throw new ComponentNotReadyException(e);
}
if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) {
throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read.");
}
version.compressionAlgorithm=BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_COMPRESSED_DATA);
version.raw = BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_RAW_DATA) == 1;
//check metadata (just read,do not control now)
int metasize;
try {
metasize=ByteBufferUtils.decodeLength(recordFile);
byte[] metadef=new byte[metasize];
if (recordFile.read(metadef)!=metasize){
throw new IOException("Not enough data in file.");
}
version.metadata=DataRecordMetadataXMLReaderWriter.readMetadata(new ByteArrayInputStream(metadef));
} catch (IOException e) {
throw new ComponentNotReadyException("Unable to read metadata definition from CloverData file", e);
}
break;
default:
throw new ComponentNotReadyException("Source clover data file is not supported (version " + version.majorVersion + "." + version.minorVersion + "." + version.revisionVersion + "). Data cannot be read.");
}
return version;
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#close()
*/
@Override
public void close() {
releaseDataSource();
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord)
*/
@Override
public DataRecord getNext(DataRecord record) throws JetelException {
if (!getNextDirect(recordBuffer)) {
return null; //end of file reached
}
if (!useParsingFromJobflow_3_4) {
record.deserializeUnitary(recordBuffer,serializer);
} else {
record.deserialize(recordBuffer,serializer);
}
return record;
}
/**
* Reads the next serialized record into the provided buffer.
* The target buffer is cleared first.
* <p>
* The position of the target buffer will be set to 0
* and the limit will be set to the end of the serialized record.
* </p><p>
* Returns the provided buffer or <code>null</code>
* if there is no record available.
* </p>
*
* @param targetBuffer the target buffer
* @return <code>targetBuffer</code> or <code>null</code> if no data available
* @throws JetelException
*/
@Override
public boolean getNextDirect(CloverBuffer targetBuffer) throws JetelException {
final int size;
try {
size=ByteBufferUtils.decodeLength(input);
if (size<0) return false; //end of file reached
targetBuffer.clear();
targetBuffer.limit(size);
if (input.read(targetBuffer)==-1){
throw new JetelException("Insufficient data in datastream.");
}
targetBuffer.flip();
} catch(IOException ex){
throw new JetelException(ex);
}
return true;
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#setExceptionHandler(org.jetel.exception.IParserExceptionHandler)
*/
@Override
public void setExceptionHandler(IParserExceptionHandler handler) {
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#getExceptionHandler()
*/
@Override
public IParserExceptionHandler getExceptionHandler() {
return null;
}
/* (non-Javadoc)
* @see org.jetel.data.parser.Parser#getPolicyType()
*/
@Override
public PolicyType getPolicyType() {
return null;
}
@Override
public void reset() {
close();
}
@Override
public Object getPosition() {
return null;
}
@Override
public void movePosition(Object position) {
}
public URL getProjectURL() {
return projectURL;
}
public void setProjectURL(URL projectURL) {
this.projectURL = projectURL;
}
@Override
public void preExecute() throws ComponentNotReadyException {
reset();
}
@Override
public void postExecute() throws ComponentNotReadyException {
if (releaseDataSource) {
releaseDataSource();
}
}
@Override
public void free() {
close();
}
@Override
public boolean nextL3Source() {
return false;
}
@Override
public boolean isDirectReadingSupported() {
return getVersion().raw;
}
} |
package org.jetel.util.compile;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Java compiler for dynamic compilation of Java source code.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*
* @see JavaCompiler
*/
public final class DynamicCompiler {
private static final Log logger = LogFactory.getLog(DynamicCompiler.class);
/** The class loader to be used during compilation and class loading. */
private final ClassLoader classLoader;
/** Additional class path URLs to be used during compilation and class loading. */
private final URL[] classPathUrls;
/**
* Constructs a <code>DynamicCompiler</code> instance for a given class loader to be used during compilation.
* Additional class path URLs may be provided if any external Java classes are required.
*
* @param classLoader the class loader to be used, may be <code>null</code>
* @param classPathUrls the array of additional class path URLs, may be <code>null</code>
*/
public DynamicCompiler(ClassLoader classLoader, URL... classPathUrls) {
this.classLoader = classLoader;
this.classPathUrls = classPathUrls; // <- potential encapsulation problem, defensive copying would solve that
}
/**
* Compiles a given piece of Java source code and then loads a desired class. This method may be called repeatedly.
*
* @param sourceCode the Java source code to be compiled, may not be <code>null</code>
* @param className the name of a Java class (present in the source) code to be loaded, may not be <code>null</code>
*
* @return the class instance loaded from the compiled source code
*
* @throws NullPointerException if either the argument is <code>null</code>
* @throws CompilationException if the compilation failed
*/
public Class<?> compile(String sourceCode, String className) throws CompilationException {
if (sourceCode == null) {
throw new NullPointerException("sourceCode");
}
if (className == null) {
throw new NullPointerException("className");
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaClassFileManager fileManager = new JavaClassFileManager(compiler, classLoader, classPathUrls);
logger.debug("Java compile time classpath (-cp) for class '" + className + "': " + fileManager.getClassPath());
StringWriter compilerOutput = new StringWriter();
CompilationTask task = compiler.getTask(compilerOutput, fileManager, null,
Arrays.asList("-cp", fileManager.getClassPath()), null,
Arrays.asList(new JavaSourceFileObject(className, sourceCode)));
if (!task.call()) {
throw new CompilationException("Compilation failed! See compiler output for more details.",
compilerOutput.toString());
}
try {
return fileManager.loadClass(className);
} catch (ClassNotFoundException exception) {
throw new CompilationException("Loading of class " + className + " failed!", exception);
}
}
/**
* Java source code wrapper used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 28th May 2010
* @created 14th May 2010
*/
private static final class JavaSourceFileObject extends SimpleJavaFileObject {
/** The Java source code. */
private final String sourceCode;
public JavaSourceFileObject(String name, String sourceCode) {
super(URI.create(name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return sourceCode;
}
}
/**
* Java class file wrapper used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 28th May 2010
* @created 14th May 2010
*/
private static final class JavaClassFileObject extends SimpleJavaFileObject {
/** The class data in a form of Java byte code. */
private final ByteArrayOutputStream classData = new ByteArrayOutputStream();
public JavaClassFileObject(String name) {
super(URI.create(name.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);
}
@Override
public OutputStream openOutputStream() throws IOException {
return classData;
}
public byte[] getData() {
return classData.toByteArray();
}
}
/**
* Java class file manager used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*/
private static final class JavaClassFileManager extends ForwardingJavaFileManager<JavaFileManager> {
/** The class loader used to load classes directly from Java byte code. */
private final ByteCodeClassLoader classLoader;
public JavaClassFileManager(JavaCompiler compiler, ClassLoader classLoader, URL[] classPathUrls) {
super(compiler.getStandardFileManager(null, null, null));
this.classLoader = new ByteCodeClassLoader(classLoader, classPathUrls);
}
public String getClassPath() {
return ClassLoaderUtils.getClasspath(classLoader.getParent(), classLoader.getURLs());
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling)
throws IOException {
JavaClassFileObject javaClass = new JavaClassFileObject(className);
classLoader.registerClass(className, javaClass);
return javaClass;
}
public Class<?> loadClass(String name) throws ClassNotFoundException {
return classLoader.loadClass(name);
}
}
/**
* Class loader used to load classes directly from Java byte code.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*/
private static final class ByteCodeClassLoader extends URLClassLoader {
/** The map of compiled Java classes that can be loaded by this class loader. */
private final Map<String, JavaClassFileObject> javaClasses = new HashMap<String, JavaClassFileObject>();
public ByteCodeClassLoader(ClassLoader parent, URL[] classPathUrls) {
super((classPathUrls != null) ? classPathUrls : new URL[0], parent);
}
public void registerClass(String name, JavaClassFileObject byteCode) {
javaClasses.put(name, byteCode);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> clazz = findLoadedClass(name);
if (clazz == null) {
JavaClassFileObject javaClass = javaClasses.get(name);
if (javaClass != null) {
try {
byte[] classData = javaClass.getData();
clazz = defineClass(name, classData, 0, classData.length);
} catch(ClassFormatError error) {
throw new ClassNotFoundException(name, error);
}
} else {
clazz = super.loadClass(name, false);
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
}
} |
package sg.ncl.common.authentication;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.inject.Inject;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.security.Key;
/**
* @author Te Ye
*/
@Component
@Slf4j
public class JwtFilter extends GenericFilterBean {
private Key apiKey;
private String get = "GET";
@Inject
JwtFilter(@NotNull Key apiKey) {
this.apiKey = apiKey;
}
@Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
// perform some whitelist
log.info(((HttpServletRequest) req).getRequestURI() + " : " + ((HttpServletRequest) req).getMethod());
// String reqURI = ((HttpServletRequest) req).getRequestURI();
// String method = ((HttpServletRequest) req).getMethod();
// if (reqURI.startsWith("/teams/") && method.equals(get)) {
// String[] param = req.getParameterValues("visibility");
// if ( (param.length != 0) && (param[0].equals("PUBLIC"))) {
// log.info("Teams visibility here");
// chain.doFilter(req, res);
// if (reqURI.startsWith("/users/") && method.equals(get)) {
// log.info("Users get here");
// chain.doFilter(req, res);
// if (reqURI.startsWith("/authentication")) {
// log.info("Authentication here");
// chain.doFilter(req, res);
// if (reqURI.startsWith("/registrations")) {
// log.info("Registrations here");
// chain.doFilter(req, res);
if (!isWhitelistedUrl(req)) {
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
log.warn("Missing or invalid Authorization header: {}", authHeader);
throw new ServletException("Missing or invalid Authorization header.");
}
final String token = authHeader.substring(7); // The part after "Bearer "
log.info("Login with Authorization: {}", authHeader);
try {
final Claims claims = Jwts.parser().setSigningKey(apiKey)
.parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
}
catch (final SignatureException e) {
log.warn("Invalid token: {}", e);
throw new ServletException("Invalid token.");
}
}
chain.doFilter(req, res);
}
private boolean isWhitelistedUrl(ServletRequest req) {
String requestURI = ((HttpServletRequest) req).getRequestURI();
String requestMethod = ((HttpServletRequest) req).getMethod();
if (requestURI.startsWith("/teams/") && requestMethod.equals(get)) {
String[] param = req.getParameterValues("visibility");
if ( (param.length != 0) && (param[0].equals("PUBLIC"))) {
log.info("Teams visibility here");
return true;
}
} else if (requestURI.startsWith("/users/") && requestMethod.equals(get)) {
log.info("Users get here");
return true;
} else if (requestURI.startsWith("/authentication")) {
log.info("Authentication here");
return true;
} else if (requestURI.startsWith("/registrations")) {
log.info("Registrations here");
return true;
}
return false;
}
} |
package com.adaptc.mws.plugins;
import java.util.Map;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* Optional base class for all plugin types and therefore plugin instances which extends
* {@link AbstractPluginInfo}. Contains method definitions to facilitate creating
* new plugin types.
* @author bsaville
*/
public abstract class AbstractPlugin extends AbstractPluginInfo {
// Extra info
/**
* Returns a log that can be used throughout the Plugin.
* @return A logging instance
*/
public Log getLog() {
return null;
}
/**
* Returns an i18n message from any file ending in "-messages.properties" included in the project JAR file.
* @param parameters The parameters used to retrieve the message, such as code, error, default, and args.
* @return The resulting i18n message
*/
public String message(Map parameters) {
return null;
}
// Lifecycle control
/**
* Hook to do any initialization needed before the plugin starts. Can be empty.
*/
public void beforeStart() {}
/**
* Starts the Plugin, including polling if enabled.
* @throws PluginStartException If there is a problem while starting the Plugin
*/
public void start() throws PluginStartException {}
/**
* Hook to do any post-start logic. Can be empty.
*/
public void afterStart() {}
/**
* Hook to start any processes needed to teardown the plugin before it stops. Can be empty.
*/
public void beforeStop() {}
/**
* Stops the Plugin, including polling if started.
* @throws PluginStopException If there is a problem while stopping the Plugin
*/
public void stop() throws PluginStopException {}
/**
* Hook to do any post-stop teardown of the plugin after it stops. Can be empty.
*/
public void afterStop() {}
/**
* Verifies the configuration of the plugin and performs any initial setup needed each time the configuration
* is loaded or changed. This is called when the {@link IPluginControlService#start} method or the
* {@link #start()} method is called, as well as any time the configuration of the Plugin
* is modified.
*
* @throws InvalidPluginConfigurationException Thrown when configuration is invalid. This exception should contain error messages.
*
* @see InvalidPluginConfigurationException#InvalidPluginConfigurationException(String)
* @see InvalidPluginConfigurationException#InvalidPluginConfigurationException(List)
*/
public void configure() throws InvalidPluginConfigurationException {}
// plugin events
/**
* Cancels the specified job(s).
* @param jobs The name(s) of the job(s) to cancel
* @return True if successful, false if an error occurred
*/
public boolean jobCancel(List<String> jobs) {
throw new UnsupportedOperationException();
}
/**
* Modifies the specified job(s) with the properties given.
* @param properties The properties to modify on the job(s)
* @param jobs The name(s) of the job(s) to modify
* @return True if successful, false if an error occurred
*/
public boolean jobModify(List<String> jobs, Map<String, String> properties) {
throw new UnsupportedOperationException();
}
/**
* Requeues the specified job(s).
* @param jobs The name(s) of the job(s) to requeue
* @return True if successful, false if an error occurred
*/
public boolean jobRequeue(List<String> jobs) {
throw new UnsupportedOperationException();
}
/**
* Resumes the specified job(s).
* @param jobs The name(s) of the job(s) to resume
* @return True if successful, false if an error occurred
*/
public boolean jobResume(List<String> jobs) {
throw new UnsupportedOperationException();
}
/**
* Starts the specified job with a list of allocated nodes and username.
* @param jobName The name of the job to start
* @param nodes The nodes allocated to the job (also called the task list)
* @param username The user starting the job
* @return True if successful, false if an error occurred
*/
public boolean jobStart(String jobName, List<String> nodes, String username) {
throw new UnsupportedOperationException();
}
/**
* Submits a new job specified by the properties given. The first plugin to return a valid ID will cause MWS to
* not call any further plugins for the job submission.
* @param job The job as a map, with field names and structure matching the MWS job API (v2 and greater)
* @param submissionFlags Flags from the Moab submission
* @return A job ID if successful, null or empty string if an error occurred
*/
public String jobSubmit(Map<String, Object> job, String submissionFlags) {
throw new UnsupportedOperationException();
}
/**
* Suspends the specified job.
* @param jobs The name(s) of the job(s)
* @return True if successful, false if an error occurred
*/
public boolean jobSuspend(List<String> jobs) {
throw new UnsupportedOperationException();
}
/**
* Modifies the specified node(s) with the properties given.
* @param properties The properties to modify on the node(s)
* @param nodes The name(s) of the node(s) to modify
* @return True if successful, false if an error occurred
*/
public boolean nodeModify(List<String> nodes, Map<String, String> properties) {
throw new UnsupportedOperationException();
}
/**
* Changes the power state of the specified node(s).
* @param state The new requested power state of the node(s)
* @param nodes The name(s) of the node(s) to modify
* @return True if successful, false if an error occurred
*/
public boolean nodePower(List<String> nodes, NodeReportPower state) {
throw new UnsupportedOperationException();
}
/**
* Changes the power state of the specified VM(s).
* @param state The new requested power state of the node(s)
* @param virtualMachines The name(s) of the VM(s) to modify
* @return True if successful, false if an error occurred
*/
public boolean virtualMachinePower(List<String> virtualMachines, NodeReportPower state) {
throw new UnsupportedOperationException();
}
} |
package com.sun.star.sdbcx.comp.hsqldb;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
final class NativeLibraries {
public static void load() {
if (System.getProperty( "os.name" ).startsWith("Windows")) {
loadLibrary("msvcr71");
loadLibrary("uwinapi");
loadLibrary("sal3");
loadLibrary("dbtoolsmi");
}
loadLibrary("hsqldb");
}
private static void loadLibrary(String libname) {
// At least on Mac OS X Tiger, System.loadLibrary("hsqldb2") does not
// find the hsqldb2 library one directory above sdbc_hsqldb.jar, even
// though ".." is on the jar's Class-Path; however, the alternative
// code (needing Java 1.5, which is given for Mac OS X Tiger) works
// there:
try {
System.loadLibrary(libname);
} catch (UnsatisfiedLinkError e) {
ClassLoader cl = NativeLibraries.class.getClassLoader();
if (cl instanceof URLClassLoader) {
URL url = ((URLClassLoader) cl).findResource(
System.mapLibraryName(libname));
if (url != null) {
try {
System.load(
((File) File.class.getConstructor(
new Class[] {
ClassLoader.getSystemClassLoader().
loadClass("java.net.URI") }).
newInstance(
new Object[] {
URL.class.getMethod("toURI", new Class[0]).
invoke(url, (java.lang.Object[])null) })).
getAbsolutePath());
} catch (Throwable t) {
throw new UnsatisfiedLinkError(
e.toString()+ " - " + t.toString());
}
}
}
}
}
private NativeLibraries() {}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaLineArray;
/**
* Class to process the pixel arrays
* @author Michael Deutch
*/
import java.awt.Color;
import java.util.ArrayList;
import java.awt.BasicStroke;
import java.awt.Shape;
//import java.awt.geom.GeneralPath;
import java.awt.geom.Area;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import ArmyC2.C2SD.Utilities.RendererSettings;
import java.awt.geom.Rectangle2D;
/*
* A class to calculate the symbol points for the GeneralPath objects.
* @author Michael Deutch
*/
public final class arraysupport
{
private static double maxLength=100;
private static double minLength=5;
private static double dACP=0;
private static String _className="arraysupport";
protected static void setMinLength(double value)
{
minLength=value;
}
private static void FillPoints(POINT2[] pLinePoints,
int counter,
ArrayList<POINT2>points)
{
points.clear();
for(int j=0;j<counter;j++)
{
points.add(pLinePoints[j]);
}
}
/**
* This is the interface function to CELineArray from clsRenderer2
* for non-channel types
*
* @param lineType the line type
* @param pts the client points
* @param shapes the symbol ShapeInfo objects
* @param clipBounds the rectangular clipping bounds
* @param rev the Mil-Standard-2525 revision
*/
public static ArrayList<POINT2> GetLineArray2(int lineType,
ArrayList<POINT2> pts,
ArrayList<Shape2> shapes,
Rectangle2D clipBounds,
int rev) {
ArrayList<POINT2> points = null;
try {
POINT2 pt = null;
POINT2[] pLinePoints2 = null;
POINT2[] pLinePoints = null;
int vblSaveCounter = pts.size();
//get the count from countsupport
int j = 0;
if (pLinePoints2 == null || pLinePoints2.length == 0)//did not get set above
{
pLinePoints = new POINT2[vblSaveCounter];
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y, pt.style);
}
}
//get the number of points the array will require
int vblCounter = countsupport.GetCountersDouble(lineType, vblSaveCounter, pLinePoints, clipBounds,rev);
//resize pLinePoints and fill the first vblSaveCounter elements with the original points
if(vblCounter>0)
pLinePoints = new POINT2[vblCounter];
else
{
shapes=null;
return null;
}
lineutility.InitializePOINT2Array(pLinePoints);
//safeguards added 2-17-11 after CPOF client was allowed to add points to autoshapes
if(vblSaveCounter>pts.size())
vblSaveCounter=pts.size();
if(vblSaveCounter>pLinePoints.length)
vblSaveCounter=pLinePoints.length;
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y,pt.style);
}
//we have to adjust the autoshapes because they are instantiating with fewer points
points = GetLineArray2Double(lineType, pLinePoints, vblCounter, vblSaveCounter, shapes, clipBounds,rev);
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetLineArray2",
new RendererException("GetLineArray2 " + Integer.toString(lineType), exc));
}
return points;
//the caller can get points
}
/**
* A function to calculate the points for FORTL
* @param pLinePoints OUT - the points arry also used for the return points
* @param lineType
* @param vblSaveCounter the number of client points
* @return
*/
private static int GetFORTLPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, bolVertical = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
//long[] segments=null;
//long numpts2=0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
//numpts2=lineutility.BoundPointsCount(pLinePoints,vblSaveCounter);
//segments=new long[numpts2];
//lineutility.BoundPoints(ref pLinePoints,vblSaveCounter,ref segments);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
switch (lineType) {
default:
dIncrement = 20;
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if (dLengthSegment / 20 < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < dLengthSegment / 20 - 1; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 10, 0);
nCounter++;
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 10);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 3, 10);
nCounter++;
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 2, 10);
nCounter++;
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
if (pLinePoints[j].y < pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 1, 10);
nCounter++;
}
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 0, 10);
nCounter++;
}
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], 10, 0);
nCounter++;
}//end for k
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
return nCounter;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetFORTLPointsDouble",
new RendererException("GetFORTLPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static void CoordFEBADouble(
POINT2[] pLinePoints,
int vblCounter) {
try {
//declarations
int j = 0;
POINT2[] pXLinePoints = new POINT2[4 * vblCounter / 32];
POINT2[] pNewLinePoints = new POINT2[vblCounter / 32];
POINT2[] pShortLinePoints = new POINT2[2 * vblCounter / 32];
POINT2[] pArcLinePoints = new POINT2[26 * vblCounter / 32];
double dPrinter = 1.0;
//end declarations
for (j = vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pLinePoints[0]); //initialize the rest of pLinePoints
pLinePoints[j].style = 0;
}
for (j = 0; j < 4 * vblCounter / 32; j++) {
pXLinePoints[j] = new POINT2(pLinePoints[0]); //initialization only for pXLinePoints
pXLinePoints[j].style = 0;
}
for (j = 0; j < vblCounter / 32; j++) //initialize pNewLinePoints
{
pNewLinePoints[j] = new POINT2(pLinePoints[j]);
pNewLinePoints[j].style = 0;
}
for (j = 0; j < 2 * vblCounter / 32; j++) //initialize pShortLinePoints
{
pShortLinePoints[j] = new POINT2(pLinePoints[0]);
pShortLinePoints[j].style = 0;
}
for (j = 0; j < 26 * vblCounter / 32; j++) //initialize pArcLinePoints
{
pArcLinePoints[j] = new POINT2(pLinePoints[0]);
pArcLinePoints[j].style = 0;
}
//first get the X's
lineutility.GetXFEBADouble(pNewLinePoints, 10 * dPrinter, vblCounter / 32,//was 7
pXLinePoints);
for (j = 0; j < 4 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pXLinePoints[j]);
}
pLinePoints[4 * vblCounter / 32 - 1].style = 5;
for (j = 4 * vblCounter / 32; j < 6 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pShortLinePoints[j - 4 * vblCounter / 32]);
pLinePoints[j].style = 5; //toggle invisible lines between feba's
}
pLinePoints[6 * vblCounter / 32 - 1].style = 5;
//last, get the arcs
lineutility.GetArcFEBADouble(14.0 * dPrinter, pNewLinePoints,
vblCounter / 32,
pArcLinePoints);
for (j = 6 * vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pArcLinePoints[j - 6 * vblCounter / 32]);
}
//clean up
pXLinePoints = null;
pNewLinePoints = null;
pShortLinePoints = null;
pArcLinePoints = null;
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "CoordFEBADouble",
new RendererException("CoordFEBADouble", exc));
}
}
private static int GetATWallPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 0;
int limit = 0;
//POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
pSpikePoints[nCounter++] = new POINT2(pLinePoints[0]);
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
if (limit < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = -1; k < limit; k++)//was k=0 to limit
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = new POINT2(pt0);
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0;j < nCounter;j++){
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble", exc));
}
return nCounter;
}
public static int GetInsideOutsideDouble2(POINT2 pt0,
POINT2 pt1,
POINT2[] pLinePoints,
int vblCounter,
int index,
int lineType) {
int nDirection = 0;
try {
//declarations
ref<double[]> m = new ref();
ref<double[]> m0 = new ref();
double b0 = 0;
double b2 = 0;
double b = 0;
double X0 = 0; //segment midpoint X value
double Y0 = 0; //segment midpoint Y value
double X = 0; //X value of horiz line from left intercept with current segment
double Y = 0; //Y value of vertical line from top intercept with current segment
int nInOutCounter = 0;
int j = 0, bolVertical = 0;
int bolVertical2 = 0;
int nOrientation = 0; //will use 0 for horiz line from left, 1 for vertical line from top
int extendLeft = 0;
int extendRight = 1;
int extendAbove = 2;
int extendBelow = 3;
int oppSegment=vblCounter-index-3; //used by BELT1 only
POINT2 pt2=new POINT2();
//end declarations. will use this to determine the direction
//slope of the segment
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m0);
if(m0.value==null)
return 0;
//get the midpoint of the segment
X0 = (pt0.x + pt1.x) / 2;
Y0 = (pt0.y + pt1.y) / 2;
if(lineType==TacticalLines.BELT1 && oppSegment>=0 && oppSegment<vblCounter-1)
{
//get the midpoint of the opposite segment
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
//must calculate the corresponding point on the current segment
//first get the y axis intercept of the perpendicular line for the opposite (short) segment
//calculate this line at the midpoint of the opposite (short) segment
b0=Y0+1/m0.value[0]*X0;
//the y axis intercept of the index segment
b2=pt0.y-m0.value[0]*pt0.x;
if(m0.value[0]!=0 && bolVertical!=0)
{
//calculate the intercept at the midpoint of the shorter segment
pt2=lineutility.CalcTrueIntersectDouble2(-1/m0.value[0],b0,m0.value[0],b2,1,1,0,0);
X0=pt2.x;
Y0=pt2.y;
}
if(m0.value[0]==0 && bolVertical!=0)
{
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pt0.y+pt1.y )/2;
}
if(bolVertical==0)
{
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
X0= ( pt0.x+pt1.x )/2;
}
}
//slope is not too small or is vertical, use left to right
if (Math.abs(m0.value[0]) >= 1 || bolVertical == 0) {
nOrientation = 0; //left to right orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j) {
//for BELT1 we only want to know if the opposing segment is to the
//left of the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j) //change 2
continue;
if ((pLinePoints[j].y <= Y0 && pLinePoints[j + 1].y >= Y0) ||
(pLinePoints[j].y >= Y0 && pLinePoints[j + 1].y <= Y0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 1 && m.value[0] == 0) //current segment is horizontal, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter
}
//current segment is vertical, it's x value must be to the left
//of the current segment X0 for the horiz line from the left to cross
if (bolVertical2 == 0) {
if (pLinePoints[j].x < X0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the X value of the intersection between the horiz line
//from the left and the current segment
//b=Y0;
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
X = (Y0 - b) / m.value[0];
if (X < X0) //the horizontal line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
} //end if
else //use top to bottom to get orientation
{
nOrientation = 1; //top down orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j)
{
//for BELT1 we only want to know if the opposing segment is
//above the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j)
continue;
if ((pLinePoints[j].x <= X0 && pLinePoints[j + 1].x >= X0) ||
(pLinePoints[j].x >= X0 && pLinePoints[j + 1].x <= X0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 0) //current segment is vertical, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter
}
//current segment is horizontal, it's y value must be above
//the current segment Y0 for the horiz line from the left to cross
if (bolVertical2 == 1 && m.value[0] == 0) {
if (pLinePoints[j].y < Y0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the Y value of the intersection between the vertical line
//from the top and the current segment
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
Y = m.value[0] * X0 + b;
if (Y < Y0) //the vertical line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
}
switch (nInOutCounter % 2) {
case 0:
if (nOrientation == 0) {
nDirection = extendLeft;
} else {
nDirection = extendAbove;
}
break;
case 1:
if (nOrientation == 0) {
nDirection = extendRight;
} else {
nDirection = extendBelow;
}
break;
default:
break;
}
//reverse direction for ICING
switch(lineType)
{
case TacticalLines.ICING:
if(nDirection==extendLeft)
nDirection=extendRight;
else if(nDirection==extendRight)
nDirection=extendLeft;
else if(nDirection==extendAbove)
nDirection=extendBelow;
else if(nDirection==extendBelow)
nDirection=extendAbove;
break;
default:
break;
}
} catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetInsideOutsideDouble2",
new RendererException("GetInsideOutsideDouble2", exc));
}
return nDirection;
}
/**
* BELT1 line and others
* @param pLinePoints
* @param lineType
* @param vblSaveCounter
* @return
*/
protected static int GetZONEPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, n = 0;
int lCount = 0;
double dLengthSegment = 0;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = null, pt2 = null, pt3 = null;
POINT2[] pSpikePoints = null;
int nDirection = 0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
double remainder=0;
//for(j=0;j<numpts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++) {
pt1 = new POINT2(pLinePoints[j]);
pt2 = new POINT2(pLinePoints[j + 1]);
//get the direction for the spikes
nDirection = GetInsideOutsideDouble2(pt1, pt2, pLinePoints, vblSaveCounter, (int) j, lineType);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
//reverse the direction for those lines with inward spikes
if (!(lineType == TacticalLines.BELT) && !(lineType == TacticalLines.BELT1) )
{
if (dLengthSegment < 20) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
switch (nDirection) {
case 0: //extend left
nDirection = 1; //extend right
break;
case 1: //extend right
nDirection = 0; //extend left
break;
case 2: //extend above
nDirection = 3; //extend below
break;
case 3: //extgend below
nDirection = 2; //extend above
break;
default:
break;
}
break;
default:
break;
}
n = (int) (dLengthSegment / 20);
remainder=dLengthSegment-n*20;
for (k = 0; k < n; k++)
{
if(k>0)
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20-remainder/2, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10-remainder/2, 0);//was -10
}
else
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10, 0);//was -10
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 5);
break;
case TacticalLines.STRONG:
case TacticalLines.FORT:
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
break;
default:
break;
}
pSpikePoints[nCounter++] = lineutility.ExtendDirectedLine(pt1, pt2, pt0, nDirection, 10);
//nCounter++;
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
break;
case TacticalLines.STRONG:
pSpikePoints[nCounter] = new POINT2(pSpikePoints[nCounter - 2]);
break;
case TacticalLines.FORT:
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pt1, pt2, pt3, nDirection, 10);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pt3);
break;
default:
break;
}
nCounter++;
//diagnostic
if(lineType==TacticalLines.ENCIRCLE)
pSpikePoints[nCounter++] = new POINT2(pSpikePoints[nCounter-4]);
}//end for k
pSpikePoints[nCounter++] = new POINT2(pLinePoints[j + 1]);
//nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[j].style = 11;
}
}
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[nCounter - 1].style = 12;
} else {
if(nCounter>0)
pSpikePoints[nCounter - 1].style = 5;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
if (j == nCounter - 1) {
if (lineType != (long) TacticalLines.OBSAREA) {
pLinePoints[j].style = 5;
}
}
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetZONEPointsDouble2",
new RendererException("GetZONEPointsDouble2", exc));
}
return nCounter;
}
private static boolean IsTurnArcReversed(POINT2[] pPoints) {
try {
if (pPoints.length < 3) {
return false;
}
POINT2[] ptsSeize = new POINT2[2];
ptsSeize[0] = new POINT2(pPoints[0]);
ptsSeize[1] = new POINT2(pPoints[1]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double d = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize[0] = new POINT2(pPoints[1]);
ptsSeize[1] = new POINT2(pPoints[0]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double dArcReversed = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize = null;
if (dArcReversed > d) {
return true;
} else {
return false;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "IsTurnArcReversed",
new RendererException("IsTurnArcReversed", exc));
}
return false;
}
private static void GetIsolatePointsDouble(POINT2[] pLinePoints,
int lineType) {
try {
//declarations
boolean reverseTurn=false;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = new POINT2(pLinePoints[1]), pt2 = new POINT2(pLinePoints[0]);
if(pt0.x==pt1.x && pt0.y==pt1.y)
pt1.x+=1;
POINT2 C = new POINT2(), E = new POINT2(), midPt = new POINT2();
int j = 0, k = 0, l = 0;
POINT2[] ptsArc = new POINT2[26];
POINT2[] midPts = new POINT2[7];
POINT2[] trianglePts = new POINT2[21];
POINT2[] pArrowPoints = new POINT2[3], reversepArrowPoints = new POINT2[3];
double dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
double dLength = Math.abs(dRadius - 20);
if(dRadius<40)
{
dLength=dRadius/1.5;
}
double d = lineutility.MBRDistance(pLinePoints, 2);
POINT2[] ptsSeize = new POINT2[2];
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(pLinePoints[j]);
}
if (pLinePoints.length >= 3) {
savepoints[2] = new POINT2(pLinePoints[2]);
}
lineutility.InitializePOINT2Array(ptsArc);
lineutility.InitializePOINT2Array(midPts);
lineutility.InitializePOINT2Array(trianglePts);
lineutility.InitializePOINT2Array(pArrowPoints);
lineutility.InitializePOINT2Array(reversepArrowPoints);
lineutility.InitializePOINT2Array(ptsSeize);
if (d / 7 > maxLength) {
d = 7 * maxLength;
}
if (d / 7 < minLength) { //was minLength
d = 7 * minLength; //was minLength
}
//change due to outsized arrow in 6.0, 11-3-10
if(d>140)
d=140;
//calculation points for the SEIZE arrowhead
//for SEIZE calculations
POINT2[] ptsArc2 = new POINT2[26];
lineutility.InitializePOINT2Array(ptsArc2);
//end declarations
E.x = 2 * pt1.x - pt0.x;
E.y = 2 * pt1.y - pt0.y;
ptsArc[0] = new POINT2(pLinePoints[1]);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if(lineType != TacticalLines.OCCUPY)
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) d / 7, pArrowPoints, 0);
else
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) (1.75*d) / 7, pArrowPoints, 0);
pLinePoints[25].style = 5;
switch (lineType) {
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.ISOLATE:
for (j = 1; j <= 23; j++) {
if (j % 3 == 0) {
midPts[k].x = pt0.x - (long) ((dLength / dRadius) * (pt0.x - ptsArc[j].x));
midPts[k].y = pt0.y - (long) ((dLength / dRadius) * (pt0.y - ptsArc[j].y));
midPts[k].style = 0;
trianglePts[l] = new POINT2(ptsArc[j - 1]);
l++;
trianglePts[l] = new POINT2(midPts[k]);
l++;
trianglePts[l] = new POINT2(ptsArc[j + 1]);
trianglePts[l].style = 5;
l++;
k++;
}
}
for (j = 26; j < 47; j++) {
pLinePoints[j] = new POINT2(trianglePts[j - 26]);
}
pLinePoints[46].style = 5;
for (j = 47; j < 50; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 47]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.OCCUPY:
midPt.x = (pt1.x + ptsArc[25].x) / 2;
midPt.y = (pt1.y + ptsArc[25].y) / 2;
//lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) d / 7, reversepArrowPoints, 0);
lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) (1.75*d) / 7, reversepArrowPoints, 0);
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
}
for (j = 29; j < 32; j++) {
pLinePoints[j] = new POINT2(reversepArrowPoints[j - 29]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.SECURE:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
break;
case TacticalLines.TURN:
boolean changeArc = IsTurnArcReversed(savepoints); //change 1
if (reverseTurn == true || changeArc == true) //swap the points
{
pt0.x = pt1.x;
pt0.y = pt1.y;
pt1.x = pt2.x;
pt1.y = pt2.y;
}
ptsSeize[0] = new POINT2(pt0);
ptsSeize[1] = new POINT2(pt1);
dRadius = lineutility.CalcClockwiseCenterDouble(ptsSeize);
C = new POINT2(ptsSeize[0]);
E = new POINT2(ptsSeize[1]);
ptsArc[0] = new POINT2(pt0);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if (changeArc == true)//if(changeArc==false) //change 1
{
lineutility.GetArrowHead4Double(ptsArc[1], pt0, (int) d / 7, (int) d / 7, pArrowPoints, 5);
} else {
lineutility.GetArrowHead4Double(ptsArc[24], pt1, (int) d / 7, (int) d / 7, pArrowPoints, 5);
}
pLinePoints[25].style = 5;
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 9;
}
pLinePoints[28].style = 10;
break;
case TacticalLines.RETAIN:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
//get the extended points for retain
k = 29;
for (j = 1; j < 24; j++) {
pLinePoints[k] = new POINT2(ptsArc[j]);
pLinePoints[k].style = 0;
k++;
pLinePoints[k] = lineutility.ExtendLineDouble(pt0, ptsArc[j], (long) d / 7);
pLinePoints[k].style = 5;
k++;
}
break;
default:
break;
}
//clean up
savepoints = null;
ptsArc = null;
midPts = null;
trianglePts = null;
pArrowPoints = null;
reversepArrowPoints = null;
ptsSeize = null;
ptsArc2 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIsolatePointsDouble",
new RendererException("GetIsolatePointsDouble " + Integer.toString(lineType), exc));
}
return;
}
/**
* @deprecated
* returns the location for the Dummy Hat
* @param pLinePoints
* @return
*/
private static POINT2 getDummyHat(POINT2[]pLinePoints)
{
POINT2 pt=null;
try
{
int j=0;
double minY=Double.MAX_VALUE;
double minX=Double.MAX_VALUE,maxX=-Double.MAX_VALUE;
int index=-1;
//get the highest point
for(j=0;j<pLinePoints.length-3;j++)
{
if(pLinePoints[j].y<minY)
{
minY=pLinePoints[j].y;
index=j;
}
if(pLinePoints[j].x<minX)
minX=pLinePoints[j].x;
if(pLinePoints[j].x>maxX)
maxX=pLinePoints[j].x;
}
pt=new POINT2(pLinePoints[index]);
double deltaMaxX=0;
double deltaMinX=0;
if(pt.x+25>maxX)
{
deltaMaxX=pt.x+25-maxX;
pt.x-=deltaMaxX;
}
if(pt.x-25<minX)
{
deltaMinX=minX-(pt.x-25);
pt.x+=deltaMinX;
}
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "getDummyHat",
new RendererException("getDummyHat", exc));
}
return pt;
}
private static void AreaWithCenterFeatureDouble(POINT2[] pLinePoints,
int vblCounter,
int lineType )
{
try
{
//declarations
int k=0;
POINT2 ptCenter = new POINT2();
int fLength=4;
if(lineType==TacticalLines.AIRFIELD)
fLength=5;
double d = lineutility.MBRDistance(pLinePoints, vblCounter-fLength);
//11-18-2010
if(d>350)
d=350;
//end declarations
for (k = 0; k < vblCounter; k++) {
pLinePoints[k].style = 0;
}
switch (lineType) {
case TacticalLines.DUMMY:
if(d<20)
d=20;
if(d>60)
d=60;
POINT2 ul=new POINT2();
POINT2 lr=new POINT2();
lineutility.CalcMBRPoints(pLinePoints, vblCounter-4, ul, lr);
//ul=getDummyHat(pLinePoints);
//ul.x-=25;
POINT2 ur=new POINT2(lr);
ur.y=ul.y;
pLinePoints[vblCounter-3]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-3].x-=d/2;
pLinePoints[vblCounter-3].y-=d/5;
pLinePoints[vblCounter-2]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-2].y-=d*0.7;
pLinePoints[vblCounter-1]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-1].x+=d/2;
pLinePoints[vblCounter-1].y-=d/5;
pLinePoints[vblCounter-4].style=5;
break;
case TacticalLines.AIRFIELD:
if(d<100)
d=100;
pLinePoints[vblCounter - 5] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 5].style = 5;
pLinePoints[vblCounter - 4] = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 6);
pLinePoints[vblCounter - 4].x -= d / 10; //was 20
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 3].x = pLinePoints[vblCounter - 4].x + d / 5;//was 10
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 2].y += d / 20;//was 40
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 3]);
pLinePoints[vblCounter - 1].y -= d / 20;//was 40
pLinePoints[vblCounter - 1].style = 0;
break;
case TacticalLines.DMA:
if(d<50)
d=50;
if (lineType == (long) TacticalLines.DMA) {
for (k = 0; k < vblCounter - 4; k++) {
pLinePoints[k].style = 14;
}
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 4].style = 5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
break;
case TacticalLines.DMAF:
if(d<50)
d=50;
pLinePoints[vblCounter-4].style=5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
pLinePoints[vblCounter - 1].style = 5;
break;
default:
break;
}
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AreaWithCenterFeatureDouble",
new RendererException("AreaWithCenterFeatureDouble " + Integer.toString(lineType), exc));
}
}
private static int GetATWallPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dRemainder = 0, dSpikeSize = 0;
int limit = 0;
POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
switch (lineType) {
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter] = pLinePoints[0];
pSpikePoints[nCounter].style = 0;
nCounter++;
break;
default:
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
switch (lineType) {
case TacticalLines.UCF:
case TacticalLines.CF:
case TacticalLines.CFG:
case TacticalLines.CFY:
dIncrement = 60;
dSpikeSize = 20;
dRemainder = dLengthSegment / dIncrement - (double) ((int) (dLengthSegment / dIncrement));
if (dRemainder < 0.75) {
limit = (int) (dLengthSegment / dIncrement);
} else {
limit = (int) (dLengthSegment / dIncrement) + 1;
}
break;
default:
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
break;
}
if (limit < 1) {
pSpikePoints[nCounter] = pLinePoints[j];
nCounter++;
pSpikePoints[nCounter] = pLinePoints[j + 1];
nCounter++;
continue;
}
for (k = 0; k < limit; k++) {
switch (lineType) {
case TacticalLines.CFG: //linebreak for dot
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 4, 5);
nCounter++;
//dot
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 1, 20);
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 7, 0);
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
case TacticalLines.CFY: //linebreak for crossed line
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 10, 5);
nCounter++;
//dot
//pSpikePoints[nCounter]=lineutility.ExtendLine2Double(pLinePoints[j+1],pLinePoints[j],-k*dIncrement-1,20);
//nCounter++;
//replace the dot with crossed line segment
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 5, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 10, 5);
nCounter++;
crossPt1 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 1], 2, 5, 0);
crossPt2 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 2], 3, 5, 5);
pSpikePoints[nCounter] = crossPt1;
nCounter++;
pSpikePoints[nCounter] = crossPt2;
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 13, 0);
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
default:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
break;
}
if (lineType == TacticalLines.CF) {
pSpikePoints[nCounter].style = 0;
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - dSpikeSize, 0);
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter].style = 9;
}
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = pt0;
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter - 1].style = 9;
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
//need an extra point for these
switch (lineType) {
case TacticalLines.CF:
pSpikePoints[nCounter].style = 10;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter].style = 10;
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], dSpikeSize, 0);
break;
default:
break;
}
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = pLinePoints[j + 1];
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = pSpikePoints[j];
}
pLinePoints[nCounter-1].style=5;
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static int GetRidgePointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 20;
int limit = 0;
double d = 0;
int bolVertical = 0;
//end delcarations
m.value = new double[1];
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
//for(j=0;j<numPts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++)
{
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
limit = (int) (dLengthSegment / dIncrement);
if (limit < 1)
{
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < limit; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
d = lineutility.CalcDistanceDouble(pLinePoints[j], pSpikePoints[nCounter - 1]);
pt0 = lineutility.ExtendLineDouble(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize / 2);
//the spikes
if (bolVertical != 0) //segment is not vertical
{
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, dSpikeSize);
}
else //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, dSpikeSize);
}
}
else //segment is vertical
{
if (pLinePoints[j + 1].y < pLinePoints[j].y) //extend left of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, dSpikeSize);
}
else //extend right of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, dSpikeSize);
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize, 0);
nCounter++;
}
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
for (j = nCounter; j < lCount; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[nCounter - 1]);
}
//clean up
//segments=null;
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRidgePointsDouble",
new RendererException("GetRidgePointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
protected static int GetSquallDouble(POINT2[] pLinePoints,
int amplitude,
int quantity,
int length,
int numPoints)
{
int counter = 0;
try {
int j = 0, k = 0;
POINT2 StartSegPt, EndSegPt;
POINT2 savePoint1 = new POINT2(pLinePoints[0]);
POINT2 savePoint2 = new POINT2(pLinePoints[numPoints - 1]);
ref<int[]> sign = new ref();
int segQty = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints);
POINT2[] pSquallPts = new POINT2[totalQty];
POINT2[] pSquallSegPts = null;
//end declarations
lineutility.InitializePOINT2Array(pSquallPts);
sign.value = new int[1];
sign.value[0] = -1;
if (totalQty == 0) {
return 0;
}
for (j = 0; j < numPoints - 1; j++) {
//if(segments[j]!=0)
StartSegPt = new POINT2(pLinePoints[j]);
EndSegPt = new POINT2(pLinePoints[j + 1]);
segQty = countsupport.GetSquallSegQty(StartSegPt, EndSegPt, quantity, length);
if (segQty > 0)
{
pSquallSegPts = new POINT2[segQty];
lineutility.InitializePOINT2Array(pSquallSegPts);
}
else
{
continue;
}
sign.value[0]=-1;
lineutility.GetSquallSegment(StartSegPt, EndSegPt, pSquallSegPts, sign, amplitude, quantity, length);
for (k = 0; k < segQty; k++)
{
pSquallPts[counter].x = pSquallSegPts[k].x;
pSquallPts[counter].y = pSquallSegPts[k].y;
if (k == 0)
{
pSquallPts[counter] = new POINT2(pLinePoints[j]);
}
if (k == segQty - 1)
{
pSquallPts[counter] = new POINT2(pLinePoints[j + 1]);
}
pSquallPts[counter].style = 0;
counter++;
}
}
//load the squall points into the linepoints array
for (j = 0; j < counter; j++) {
if (j < totalQty)
{
pLinePoints[j].x = pSquallPts[j].x;
pLinePoints[j].y = pSquallPts[j].y;
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
}
if (j == counter - 1)
{
pLinePoints[j] = new POINT2(savePoint2);
}
pLinePoints[j].style = pSquallPts[j].style;
}
}
if (counter == 0)
{
for (j = 0; j < pLinePoints.length; j++)
{
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
} else
{
pLinePoints[j] = new POINT2(savePoint2);
}
}
counter = pLinePoints.length;
}
//clean up
pSquallPts = null;
pSquallSegPts = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSquallDouble",
new RendererException("GetSquallDouble", exc));
}
return counter;
}
protected static int GetSevereSquall(POINT2[] pLinePoints,
int numPoints) {
int l = 0;
try
{
int quantity = 5, length = 30, j = 0, k = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints) + 2 * numPoints;
POINT2[] squallPts = new POINT2[totalQty];
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), pt2 = new POINT2(),
pt3 = new POINT2(), pt4 = new POINT2(), pt5 = new POINT2(), pt6 = new POINT2(),
pt7 = new POINT2(),pt8 = new POINT2();
int segQty = 0;
double dist = 0;
//end declarations
lineutility.InitializePOINT2Array(squallPts);
for (j = 0; j < numPoints - 1; j++)
{
dist = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
segQty = (int) (dist / 30);
for (k = 0; k < segQty; k++) {
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30);
pt1 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 20);
//pt0.style = 5;
pt5 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 25);
pt6 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 30);
//pt6.style=5;
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 5, 0); //extend above line
pt3 = lineutility.ExtendDirectedLine(pt0, pt5, pt5, 3, 5, 0); //extend below line
pt4 = lineutility.ExtendDirectedLine(pt0, pt6, pt6, 2, 5, 5); //extend above line
pt4.style=5;
squallPts[l++] = new POINT2(pt2);
squallPts[l++] = new POINT2(pt3);
squallPts[l++] = new POINT2(pt4);
pt7 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 5);
pt8 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 10);
pt8.style=5;
squallPts[l++] = new POINT2(pt7);
squallPts[l++] = new POINT2(pt8);
}
//segment remainder
squallPts[l++] = new POINT2(pLinePoints[j + 1]);
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j+1], pLinePoints[j], 5);
pt0.style=5;
squallPts[l++]=new POINT2(pt0);
}
if(l>pLinePoints.length)
l=pLinePoints.length;
for (j = 0; j < l; j++)
{
if (j < totalQty)
{
pLinePoints[j] = new POINT2(squallPts[j]);
}
else
break;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSevereSquall",
new RendererException("GetSevereSquall", exc));
}
return l;
}
private static int GetConvergancePointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = vblCounter;
try {
int j = 0, k = 0;
//int counter=vblCounter;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
pLinePoints[vblCounter - 1].style = 5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 10);
//we don't want too small a remainder
if (d - numJags * 10 < 5)
{
numJags -= 1;
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
//the first spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 10 + 5, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 2, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
//the 2nd spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, (k + 1) * 10, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 3, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetConvergancePointsDouble",
new RendererException("GetConvergancePointsDouble", exc));
}
return counter;
}
private static int GetITDPointsDouble(POINT2[] pLinePoints, int vblCounter)
{
int counter = 0;
try {
int j = 0, k = 0;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0, lineStyle = 19;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
//pLinePoints[vblCounter-1].style=5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 15);
//we don't want too small a remainder
if (d - numJags * 10 < 5) {
numJags -= 1;
}
if(numJags==0)
{
pt0.style=19;
pLinePoints[counter++] = new POINT2(pt0);
pt1.style=5;
pLinePoints[counter++] = new POINT2(pt1);
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 15 + 5, lineStyle);
pLinePoints[counter++] = new POINT2(tempPt);
if (k < numJags - 1) {
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 10, 5);
} else {
tempPt = new POINT2(tempPts[j + 1]);
tempPt.style = 5;
}
pLinePoints[counter++] = new POINT2(tempPt);
if (lineStyle == 19) {
lineStyle = 25;
} else {
lineStyle = 19;
}
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetITDPointsDouble",
new RendererException("GetITDPointsDouble", exc));
}
return counter;
}
private static int GetXPoints(int linetype, POINT2[] pOriginalLinePoints, POINT2[] XPoints, int vblCounter)
{
int xCounter=0;
try
{
int j=0,k=0;
double d=0;
POINT2 pt0,pt1,pt2,pt3=new POINT2(),pt4=new POINT2(),pt5=new POINT2(),pt6=new POINT2();
int numThisSegment=0;
double distInterval=0;
for(j=0;j<vblCounter-1;j++)
{
d=lineutility.CalcDistanceDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1]);
numThisSegment=(int)( (d-20d)/20d);
if(linetype==TacticalLines.LRO)
numThisSegment=(int)( (d-30d)/30d);
//added 4-19-12
distInterval=d/numThisSegment;
for(k=0;k<numThisSegment;k++)
{
//pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1], 10+20*k);
pt0=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j],pOriginalLinePoints[j+1], distInterval/2+distInterval*k);
pt1=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], 5);
pt2=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], -5);
pt3=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 2, 5);
pt4=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 3, 5);
pt4.style=5;
pt5=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 2, 5);
pt6=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 3, 5);
pt6.style=5;
XPoints[xCounter++]=new POINT2(pt3);
XPoints[xCounter++]=new POINT2(pt6);
XPoints[xCounter++]=new POINT2(pt5);
XPoints[xCounter++]=new POINT2(pt4);
}
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return xCounter;
}
/**
* returns a 37 point ellipse
* @param ptCenter
* @param ptWidth
* @param ptHeight
* @return
*/
private static POINT2[] getEllipsePoints(POINT2 ptCenter, POINT2 ptWidth, POINT2 ptHeight)
{
POINT2[]pEllipsePoints=null;
try
{
pEllipsePoints=new POINT2[37];
int l=0;
double dFactor=0;
double a=lineutility.CalcDistanceDouble(ptCenter, ptWidth);
double b=lineutility.CalcDistanceDouble(ptCenter, ptHeight);
lineutility.InitializePOINT2Array(pEllipsePoints);
for (l = 1; l < 37; l++)
{
//dFactor = (20.0 * l) * Math.PI / 180.0;
dFactor = (10.0 * l) * Math.PI / 180.0;
pEllipsePoints[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints[l - 1].style = 0;
}
pEllipsePoints[36]=new POINT2(pEllipsePoints[0]);
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetEllipsePoints",
new RendererException("GetEllipsePoints", exc));
}
return pEllipsePoints;
}
private static int GetLVOPoints(int linetype, POINT2[] pOriginalLinePoints, POINT2[] pLinePoints, int vblCounter)
{
int lEllipseCounter = 0;
try {
//double dAngle = 0, d = 0, a = 13, b = 6, dFactor = 0;
double dAngle = 0, d = 0, a = 4, b = 8, dFactor = 0;
int lHowManyThisSegment = 0, j = 0, k = 0, l = 0, t = 0;
POINT2 ptCenter = new POINT2();
POINT2[] pEllipsePoints2 = new POINT2[37];
double distInterval=0;
//end declarations
for (j = 0; j < vblCounter - 1; j++)
{
lineutility.InitializePOINT2Array(pEllipsePoints2);
d = lineutility.CalcDistanceDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
//lHowManyThisSegment = (int) ((d - 10) / 10);
lHowManyThisSegment = (int) ((d - 20) / 20);
if(linetype==TacticalLines.LRO)
lHowManyThisSegment = (int) ((d - 30) / 30);
//added 4-19-12
distInterval=d/lHowManyThisSegment;
dAngle = lineutility.CalcSegmentAngleDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
dAngle = dAngle + Math.PI / 2;
for (k = 0; k < lHowManyThisSegment; k++)
{
//t = k;
//ptCenter=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*20+20);
ptCenter=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*distInterval);
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}//end k loop
//extra ellipse on the final segment at the end of the line
if(j==vblCounter-2)
{
ptCenter=pOriginalLinePoints[j+1];
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetLVOPointsDouble",
new RendererException("GetLVOPointsDouble", exc));
}
return lEllipseCounter;
}
private static int GetIcingPointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = 0;
try {
int j = 0;
POINT2[] origPoints = new POINT2[vblCounter];
int nDirection = -1;
int k = 0, numSegments = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), midPt = new POINT2(), pt2 = new POINT2();
//save the original points
for (j = 0; j < vblCounter; j++) {
origPoints[j] = new POINT2(pLinePoints[j]);
}
double distInterval=0;
for (j = 0; j < vblCounter - 1; j++) {
//how many segments for this line segment?
numSegments = (int) lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1]);
numSegments /= 15; //segments are 15 pixels long
//4-19-12
distInterval=lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1])/numSegments;
//get the direction and the quadrant
nDirection = GetInsideOutsideDouble2(origPoints[j], origPoints[j + 1], origPoints, vblCounter, j, TacticalLines.ICING);
for (k = 0; k < numSegments; k++) {
//get the parallel segment
if (k == 0) {
pt0 = new POINT2(origPoints[j]);
} else {
//pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15, 0);
pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval, 0);
}
//pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 10, 5);
pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 10, 5);
//midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 5, 0);
midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 5, 0);
//get the perpendicular segment
pt2 = lineutility.ExtendDirectedLine(origPoints[j], origPoints[j + 1], midPt, nDirection, 5, 5);
pLinePoints[counter] = new POINT2(pt0);
pLinePoints[counter + 1] = new POINT2(pt1);
pLinePoints[counter + 2] = new POINT2(midPt);
pLinePoints[counter + 3] = new POINT2(pt2);
counter += 4;
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIcingPointsDouble",
new RendererException("GetIcingPointsDouble", exc));
}
return counter;
}
protected static int GetAnchorageDouble(POINT2[] vbPoints2, int numPts)
{
int lFlotCounter = 0;
try
{
//declarations
int j = 0, k = 0, l = 0;
int x1 = 0, y1 = 0;
int numSegPts = -1;
int lFlotCount = 0;
int lNumSegs = 0;
double dDistance = 0;
int[] vbPoints = null;
int[] points = null;
int[] points2 = null;
POINT2 pt = new POINT2();
POINT2 pt1 = new POINT2(), pt2 = new POINT2();
//end declarations
lFlotCount = flot.GetAnchorageCountDouble(vbPoints2, numPts);
vbPoints = new int[2 * numPts];
for (j = 0; j < numPts; j++)
{
vbPoints[k] = (int) vbPoints2[j].x;
k++;
vbPoints[k] = (int) vbPoints2[j].y;
k++;
}
k = 0;
ref<int[]> bFlip = new ref();
bFlip.value = new int[1];
ref<int[]> lDirection = new ref();
lDirection.value = new int[1];
ref<int[]> lLastDirection = new ref();
lLastDirection.value = new int[1];
for (l = 0; l < numPts - 1; l++)
{
//pt1=new POINT2();
//pt2=new POINT2();
pt1.x = vbPoints[2 * l];
pt1.y = vbPoints[2 * l + 1];
pt2.x = vbPoints[2 * l + 2];
pt2.y = vbPoints[2 * l + 3];
//for all segments after the first segment we shorten
//the line by 20 so the flots will not abut
if (l > 0)
{
pt1 = lineutility.ExtendAlongLineDouble(pt1, pt2, 20);
}
dDistance = lineutility.CalcDistanceDouble(pt1, pt2);
lNumSegs = (int) (dDistance / 20);
//ref<int[]> bFlip = new ref();
//bFlip.value = new int[1];
//ref<int[]> lDirection = new ref();
//lDirection.value = new int[1];
//ref<int[]> lLastDirection = new ref();
//lLastDirection.value = new int[1];
if (lNumSegs > 0) {
points2 = new int[lNumSegs * 32];
numSegPts = flot.GetAnchorageFlotSegment(vbPoints, (int) pt1.x, (int) pt1.y, (int) pt2.x, (int) pt2.y, l, points2, bFlip, lDirection, lLastDirection);
points = new int[numSegPts];
for (j = 0; j < numSegPts; j++)
{
points[j] = points2[j];
}
for (j = 0; j < numSegPts / 3; j++) //only using half the flots
{
x1 = points[k];
y1 = points[k + 1];
//z = points[k + 2];
k += 3;
if (j % 10 == 0) {
pt.x = x1;
pt.y = y1;
pt.style = 5;
}
else if ((j + 1) % 10 == 0)
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter++].y = y1;
vbPoints2[lFlotCounter++] = new POINT2(pt);
continue;
}
else
{
break;
}
}
if (lFlotCounter < lFlotCount) {
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter].y = y1;
lFlotCounter++;
} else {
break;
}
}
k = 0;
points = null;
} else
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = vbPoints[2 * l];
vbPoints2[lFlotCounter].y = vbPoints[2 * l + 1];
lFlotCounter++;
}
}
}
for (j = lFlotCounter - 1; j < lFlotCount; j++)
{
vbPoints2[j].style = 5;
}
//clean up
vbPoints = null;
points = null;
points2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetAnchorageDouble",
new RendererException("GetAnchorageDouble", exc));
}
return lFlotCounter;
}
private static int GetPipePoints(POINT2[] pLinePoints,
int vblCounter)
{
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2[] xPoints = new POINT2[pLinePoints.length];
int xCounter = 0;
int j=0,k=0;
for (j = 0; j < vblCounter; j++)
{
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0;
double d = 0;
lineutility.InitializePOINT2Array(xPoints);
for (j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 20);
for (k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt1.style = 5;
pt2 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt2.style = 20; //for filled circle
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
xPoints[xCounter++] = new POINT2(pt2);
}
if (numSegs == 0)
{
pLinePoints[counter] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++].style=0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style=5;
}
else
{
pLinePoints[counter] = new POINT2(pLinePoints[counter - 1]);
pLinePoints[counter++].style = 0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style = 5;
}
}
//load the circle points
for (k = 0; k < xCounter; k++)
{
pLinePoints[counter++] = new POINT2(xPoints[k]);
}
//add one more circle
pLinePoints[counter++] = new POINT2(pLinePoints[counter]);
pOriginalPoints = null;
xPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetPipePoints",
new RendererException("GetPipePoints", exc));
}
return counter;
}
private static int GetReefPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
POINT2 pt4 = new POINT2();
//POINT2 pt5=new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0,direction=0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++) {
if(pOriginalPoints[j].x<pOriginalPoints[j+1].x)
direction=2;
else
direction=3;
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 40);
for (int k = 0; k < numSegs; k++) {
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * k);
pt1 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 10);
pt1 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt1, direction, 15);//was 2
pt2 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 20);
pt2 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 5);//was 2
pt3 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 30);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt3, direction, 20);//was 2
pt4 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * (k + 1));
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt4);
}
if (numSegs == 0) {
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetReefPoints",
new RendererException("GetReefPoints", exc));
}
return counter;
}
private static int GetRestrictedAreaPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int direction=0;
int numSegs = 0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 15);
if(pOriginalPoints[j].x < pOriginalPoints[j+1].x)
direction=3;
else
direction=2;
for (int k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k + 10);
pt1.style = 5;
pt2 = lineutility.MidPointDouble(pt0, pt1, 0);
//pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 10);
pt3.style = 5;
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
}
if (numSegs == 0)
{
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter - 1].style = 0;
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRestrictedAreaPoints",
new RendererException("GetRestrictedAreaPoints", exc));
}
return counter;
}
//there should be two linetypes depending on scale
private static int getOverheadWire(POINT2[]pLinePoints, int vblCounter)
{
int counter=0;
try
{
int j=0;
POINT2 pt=null,pt2=null;
double x=0,y=0;
ArrayList<POINT2>pts=new ArrayList();
for(j=0;j<vblCounter;j++)
{
pt=new POINT2(pLinePoints[j]);
x=pt.x;
y=pt.y;
//tower
pt2=new POINT2(pt);
pt2.y -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=5;
pt2.style=5;
pts.add(pt2);
//low cross piece
pt2=new POINT2(pt);
pt2.x -=2;
pt2.y-=10;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=2;
pt2.y-=10;
pt2.style=5;
pts.add(pt2);
//high cross piece
pt2=new POINT2(pt);
pt2.x -=7;
pt2.y-=17;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=7;
pt2.y-=17;
pt2.style=5;
pts.add(pt2);
//angle piece
pt2=new POINT2(pt);
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x+=8;
pt2.y-=12;
pt2.style=5;
pts.add(pt2);
}
//connect the towers
for(j=0;j<vblCounter-1;j++)
{
pt=new POINT2(pLinePoints[j]);
pt2=new POINT2(pLinePoints[j+1]);
if(pt.x<pt2.x)
{
pt.x+=5;
pt.y -=10;
pt2.x-=5;
pt2.y-=10;
pt2.style=5;
}
else
{
pt.x-=5;
pt.y -=10;
pt2.x+=5;
pt2.y-=10;
pt2.style=5;
}
pts.add(pt);
pts.add(pt2);
}
for(j=0;j<pts.size();j++)
{
pLinePoints[j]=pts.get(j);
counter++;
}
for(j=counter;j<pLinePoints.length;j++)
pLinePoints[j]=new POINT2(pLinePoints[counter-1]);
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetOverheadWire",
new RendererException("GetOverheadWire", exc));
}
return counter;
}
//private static int linetype=-1; //use for BLOCK, CONTIAN
/**
* Calculates the points for the non-channel symbols.
* The points will be stored in the original POINT2 array in pixels, pLinePoints.
* The client points occupy the first vblSaveCounter positions in pLinePoints
* and will be overwritten by the symbol points.
*
* @param lineType the line type
* @param pLinePoints - OUT - an array of POINT2
* @param vblCounter the number of points allocated
* @param vblSaveCounter the number of client points
*
* @return the symbol point count
*/
private static ArrayList<POINT2> GetLineArray2Double(int lineType,
POINT2[] pLinePoints,
int vblCounter,
int vblSaveCounter,
ArrayList<Shape2>shapes,
Rectangle2D clipBounds,
int rev)
{
ArrayList<POINT2> points=new ArrayList();
try
{
String client=CELineArray.getClient();
if(pLinePoints==null || pLinePoints.length<2)
return null;
//declarations
int[] segments=null;
double dMRR=0;
int n=0,bolVertical=0;
double dExtendLength=0;
double dWidth=0;
int nQuadrant=0;
int lLinestyle=0,pointCounter=0;
ref<double[]> offsetX=new ref(),offsetY=new ref();
double b=0,b1=0,dRadius=0,d1=0,d=0,d2=0;
ref<double[]>m=new ref();
int direction=0;
int nCounter=0;
int j=0,k=0,middleSegment=-1;
double dMBR=lineutility.MBRDistance(pLinePoints,vblSaveCounter);
POINT2 pt0=new POINT2(pLinePoints[0]), //calculation points for autoshapes
pt1=new POINT2(pLinePoints[1]),
pt2=new POINT2(pLinePoints[1]),
pt3=new POINT2(pLinePoints[0]),
pt4=new POINT2(pLinePoints[0]),
pt5=new POINT2(pLinePoints[0]),
pt6=new POINT2(pLinePoints[0]),
pt7=new POINT2(pLinePoints[0]),
pt8=new POINT2(pLinePoints[0]),
ptYIntercept=new POINT2(pLinePoints[0]),
ptYIntercept1=new POINT2(pLinePoints[0]),
ptCenter=new POINT2(pLinePoints[0]);
POINT2[] pArrowPoints=new POINT2[3],
arcPts=new POINT2[26],
circlePoints=new POINT2[100],
pts=null,pts2=null;
POINT2 midpt=new POINT2(pLinePoints[0]),midpt1=new POINT2(pLinePoints[0]);
POINT2[]pOriginalLinePoints=null;
POINT2[] pUpperLinePoints = null;
POINT2[] pLowerLinePoints = null;
POINT2[] pUpperLowerLinePoints = null;
POINT2 calcPoint0=new POINT2(),
calcPoint1=new POINT2(),
calcPoint2=new POINT2(),
calcPoint3=new POINT2(),
calcPoint4=new POINT2();
POINT2 ptTemp=new POINT2(pLinePoints[0]);
int acCounter=0;
POINT2[] acPoints=new POINT2[6];
int lFlotCount=0;
//end declarations
//Bearing line and others only have 2 points
if(vblCounter>2)
pt2=new POINT2(pLinePoints[2]);
//strcpy(CurrentFunction,"GetLineArray2");
pt0.style=0;
pt1.style=0;
pt2.style=0;
//set jaggylength in clsDISMSupport before the points get bounded
//clsDISMSupport.JaggyLength = Math.Sqrt ( (pLinePoints[1].x-pLinePoints[0].x) * (pLinePoints[1].x-pLinePoints[0].x) +
// (pLinePoints[1].y-pLinePoints[0].y) * (pLinePoints[1].y-pLinePoints[0].y) );
//double saveMaxPixels=CELineArrayGlobals.MaxPixels2;
//double saveMaxPixels=2000;
ArrayList xPoints=null;
pOriginalLinePoints = new POINT2[vblSaveCounter];
for(j = 0;j<vblSaveCounter;j++)
{
pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
}
//resize the array and get the line array
//for the specified non-channel line type
switch(lineType)
{
case TacticalLines.BBS_AREA:
lineutility.getExteriorPoints(pLinePoints, vblSaveCounter, lineType, false);
acCounter=vblSaveCounter;
break;
case TacticalLines.BS_CROSS:
pt0=new POINT2(pLinePoints[0]);
pLinePoints[0]=new POINT2(pt0);
pLinePoints[0].x-=10;
pLinePoints[1]=new POINT2(pt0);
pLinePoints[1].x+=10;
pLinePoints[1].style=10;
pLinePoints[2]=new POINT2(pt0);
pLinePoints[2].y+=10;
pLinePoints[3]=new POINT2(pt0);
pLinePoints[3].y-=10;
acCounter=4;
break;
case TacticalLines.BS_RECTANGLE:
lineutility.CalcMBRPoints(pLinePoints, pLinePoints.length, pt0, pt2); //pt0=ul, pt1=lr
//pt0=new POINT2(pLinePoints[0]);
//pt2=new POINT2(pLinePoints[1]);
//pt1=new POINT2(pt0);
//pt1.y=pt2.y;
pt1=new POINT2(pt0);
pt1.x=pt2.x;
pt3=new POINT2(pt0);
pt3.y=pt2.y;
pLinePoints=new POINT2[5];
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BBS_RECTANGLE:
//double xmax=pLinePoints[0].x,xmin=pLinePoints[1].x,ymax=pLinePoints[0].y,ymin=pLinePoints[1].y;
//double xmax=pLinePoints[2].x,xmin=pLinePoints[0].x,ymax=pLinePoints[2].y,ymin=pLinePoints[0].y;
double buffer=pLinePoints[0].style;
pOriginalLinePoints=new POINT2[5];
pOriginalLinePoints[0]=new POINT2(pLinePoints[0]);
pOriginalLinePoints[1]=new POINT2(pLinePoints[1]);
pOriginalLinePoints[2]=new POINT2(pLinePoints[2]);
pOriginalLinePoints[3]=new POINT2(pLinePoints[3]);
pOriginalLinePoints[4]=new POINT2(pLinePoints[0]);
//clockwise orientation
pt0=pLinePoints[0];
pt0.x-=buffer;
pt0.y-=buffer;
pt1=pLinePoints[1];
pt1.x+=buffer;
pt1.y-=buffer;
pt2=pLinePoints[2];
pt2.x+=buffer;
pt2.y+=buffer;
pt3=pLinePoints[3];
pt3.x-=buffer;
pt3.y+=buffer;
pLinePoints=new POINT2[5];
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
vblSaveCounter=5;
acCounter=5;
break;
case TacticalLines.BS_ELLIPSE:
pt0=pLinePoints[0];//the center of the ellipse
pt1=pLinePoints[1];//the width of the ellipse
pt2=pLinePoints[2];//the height of the ellipse
pLinePoints=getEllipsePoints(pt0,pt1,pt2);
acCounter=37;
break;
case TacticalLines.OVERHEAD_WIRE:
acCounter=getOverheadWire(pLinePoints,vblSaveCounter);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for(j=0;j<vblSaveCounter;j++)
{
//pLinePoints[j]=new POINT2(pOriginalLinePoints[j]);
pLinePoints[j].style=1;
}
//pLinePoints[vblSaveCounter-1].style=5;
for(j=vblSaveCounter;j<2*vblSaveCounter;j++)
{
pLinePoints[j]=new POINT2(pOriginalLinePoints[j-vblSaveCounter]);
pLinePoints[j].style=20;
}
//pLinePoints[2*vblSaveCounter-1].style=5;
acCounter=pLinePoints.length;
break;
case TacticalLines.BOUNDARY:
acCounter=pLinePoints.length;
break;
case TacticalLines.REEF:
vblCounter = GetReefPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ICE_DRIFT:
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-5], pLinePoints[vblCounter - 4], 10, 10,pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RESTRICTED_AREA:
vblCounter=GetRestrictedAreaPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TRAINING_AREA:
//diagnostic
dMBR=lineutility.MBRDistance(pLinePoints, vblSaveCounter);
d=20;
if(dMBR<60)
d=dMBR/4;
if(d<5)
d=5;
//end section
for (j = 0; j < vblSaveCounter; j++)
{
pLinePoints[j].style = 1;
}
pLinePoints[vblSaveCounter - 1].style = 5;
pt0 = lineutility.CalcCenterPointDouble(pLinePoints, vblSaveCounter - 1);
//lineutility.CalcCircleDouble(pt0, 20, 26, arcPts, 0);
lineutility.CalcCircleDouble(pt0, d, 26, arcPts, 0);
for (j = vblSaveCounter; j < vblSaveCounter + 26; j++)
{
pLinePoints[j] = new POINT2(arcPts[j - vblSaveCounter]);
}
pLinePoints[j-1].style = 5;
//! inside the circle
//diagnostic
if(dMBR<50)
{
//d was used as the circle radius
d*=0.6;
}
else
d=12;
//end section
pt1 = new POINT2(pt0);
pt1.y -= d;
pt1.style = 0;
pt2 = new POINT2(pt1);
pt2.y += d;
pt2.style = 5;
pt3 = new POINT2(pt2);
pt3.y += d/4;
pt3.style = 0;
pt4 = new POINT2(pt3);
pt4.y += d/4;
pLinePoints[j++] = new POINT2(pt1);
pLinePoints[j++] = new POINT2(pt2);
pLinePoints[j++] = new POINT2(pt3);
pt4.style = 5;
pLinePoints[j++] = new POINT2(pt4);
vblCounter = j;
acCounter=vblCounter;
break;
case TacticalLines.PIPE:
vblCounter=GetPipePoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ANCHORAGE_AREA:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 1: //extend left
case 2: //extend below
break;
case 0: //extend right
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 1: //extend left
case 3: //extend above
break;
case 0: //extend right
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 1: //extend left
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 3: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 1: //extend left
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 2: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = GetAnchorageDouble(pLinePoints, vblSaveCounter);
acCounter = lFlotCount;
break;
case TacticalLines.ANCHORAGE_LINE:
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
acCounter=GetAnchorageDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.LRO:
int xCount=countsupport.GetXPointsCount(lineType, pOriginalLinePoints, vblSaveCounter);
POINT2 []xPoints2=new POINT2[xCount];
int lvoCount=countsupport.GetLVOCount(lineType, pOriginalLinePoints, vblSaveCounter);
POINT2 []lvoPoints=new POINT2[lvoCount];
xCount=GetXPoints(lineType, pOriginalLinePoints,xPoints2,vblSaveCounter);
lvoCount=GetLVOPoints(lineType, pOriginalLinePoints,lvoPoints,vblSaveCounter);
for(k=0;k<xCount;k++)
{
pLinePoints[k]=new POINT2(xPoints2[k]);
}
if(xCount>0)
pLinePoints[xCount-1].style=5;
for(k=0;k<lvoCount;k++)
{
pLinePoints[xCount+k]=new POINT2(lvoPoints[k]);
}
acCounter=xCount+lvoCount;
break;
case TacticalLines.UNDERCAST:
if(pLinePoints[0].x<pLinePoints[1].x)
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
lFlotCount=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.LVO:
acCounter=GetLVOPoints(lineType, pOriginalLinePoints,pLinePoints,vblSaveCounter);
break;
case TacticalLines.ICING:
vblCounter=GetIcingPointsDouble(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.MVFR:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 0: //extend left
case 3: //extend below
break;
case 1: //extend right
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 0: //extend left
case 2: //extend above
break;
case 1: //extend right
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 0: //extend left
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 2: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 0: //extend left
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 3: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = flot.GetFlotDouble(pLinePoints, vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.ITD:
acCounter=GetITDPointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.CONVERGANCE:
acCounter=GetConvergancePointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.RIDGE:
vblCounter=GetRidgePointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TROUGH:
case TacticalLines.INSTABILITY:
case TacticalLines.SHEAR:
//case TacticalLines.SQUALL:
//CELineArrayGlobals.MaxPixels2=saveMaxPixels+100;
vblCounter=GetSquallDouble(pLinePoints,10,6,30,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.SQUALL:
//vblCounter = GetSquallDouble(pLinePoints, 10, 6, 30, vblSaveCounter);
vblCounter=GetSevereSquall(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.USF:
case TacticalLines.SFG:
case TacticalLines.SFY:
vblCounter=flot.GetSFPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.SF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.OFY:
vblCounter=flot.GetOFYPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.OCCLUDED:
case TacticalLines.UOF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.WF:
case TacticalLines.UWF:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter-vblSaveCounter+j]=pOriginalLinePoints[j];
acCounter=lFlotCount+vblSaveCounter;
break;
case TacticalLines.WFG:
case TacticalLines.WFY:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
acCounter=lFlotCount;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.CF:
case TacticalLines.UCF:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
pLinePoints[vblCounter-1].style=5;
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
pLinePoints[vblCounter-1].style=5;
acCounter=vblCounter;
break;
case TacticalLines.IL:
case TacticalLines.PLANNED:
case TacticalLines.ESR1:
case TacticalLines.ESR2:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
d=lineutility.CalcDistanceDouble(pLinePoints[0], pt0);
pt4 = lineutility.ExtendLineDouble(pt0, pLinePoints[0], d);
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt4, pt2, pt3);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
pLinePoints[2] = new POINT2(pt3);
pLinePoints[3] = new POINT2(pt2);
switch (lineType) {
case TacticalLines.IL:
case TacticalLines.ESR2:
pLinePoints[0].style = 0;
pLinePoints[1].style = 5;
pLinePoints[2].style = 0;
break;
case TacticalLines.PLANNED:
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2].style = 1;
break;
case TacticalLines.ESR1:
pLinePoints[1].style = 5;
if (pt0.x <= pt1.x) {
if (pLinePoints[1].y <= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
} else {
if (pLinePoints[1].y >= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
}
break;
default:
break;
}
acCounter=4;
break;
case TacticalLines.FORDSITE:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2] = new POINT2(pt0);
pLinePoints[2].style = 1;
pLinePoints[3] = new POINT2(pt1);
pLinePoints[3].style = 5;
acCounter=4;
break;
case TacticalLines.ROADBLK:
pts = new POINT2[4];
for (j = 0; j < 4; j++) {
pts[j] = new POINT2(pLinePoints[j]);
}
dRadius = lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
d = lineutility.CalcDistanceToLineDouble(pLinePoints[0], pLinePoints[1], pLinePoints[2]);
//first two lines
pLinePoints[0] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], d, 0);
pLinePoints[1] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], d, 5);
pLinePoints[2] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], -d, 0);
pLinePoints[3] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], -d, 5);
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[0], midpt, d);
//the next line
pLinePoints[4] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[5] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[5].style = 5;
//recompute the original midpt because it was moved
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[1], midpt, d);
//the last line
pLinePoints[6] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[7] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[7].style = 5;
acCounter=8;
break;
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.PNO:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DMAF:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
pLinePoints[vblCounter-1].style=5;
FillPoints(pLinePoints,vblCounter,points);
xPoints=lineutility.LineOfXPoints(pOriginalLinePoints);
for(j=0;j<xPoints.size();j++)
{
points.add((POINT2)xPoints.get(j));
}
acCounter=points.size();
break;
case TacticalLines.FOXHOLE:
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical==0) //line is vertical
{
if (pt0.y > pt1.y) {
direction = 0;
} else {
direction = 1;
}
}
if (bolVertical != 0 && m.value[0] <= 1) {
if (pt0.x < pt1.x) {
direction = 3;
} else {
direction = 2;
}
}
if (bolVertical != 0 && m.value[0] > 1) {
if (pt0.x < pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x < pt1.x && pt0.y < pt1.y) {
direction = 0;
}
if (pt0.x > pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x > pt1.x && pt0.y < pt1.y) {
direction = 0;
}
}
//M. Deutch 8-19-04
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<250)
dMBR=250;
if(dMBR>500)
dMBR=500;
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, direction, dMBR / 20);
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, direction, dMBR / 20);
acCounter=4;
break;
case TacticalLines.ISOLATE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
break;
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.OCCUPY:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=32;
break;
case TacticalLines.RETAIN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=75;
break;
case TacticalLines.SECURE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.TURN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.ENCIRCLE:
//pOriginalLinePoints=null;
//pOriginalLinePoints = new POINT2[vblSaveCounter+2];
//for(j = 0;j<vblSaveCounter;j++)
// pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
//pOriginalLinePoints[vblSaveCounter] = new POINT2(pLinePoints[0]);
//pOriginalLinePoints[vblSaveCounter+1] = new POINT2(pLinePoints[1]);
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
//for(j=0;j<vblSaveCounter+2;j++)
// pLinePoints[pointCounter+j]=new POINT2(pOriginalLinePoints[j]);
//pointCounter += vblSaveCounter+1;
//acCounter=pointCounter;
break;
case TacticalLines.BELT1:
pUpperLinePoints=new POINT2[vblSaveCounter];
pLowerLinePoints=new POINT2[vblSaveCounter];
pUpperLowerLinePoints=new POINT2[2*vblCounter];
for(j=0;j<vblSaveCounter;j++)
pLowerLinePoints[j]=new POINT2(pLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLinePoints[j]=new POINT2(pLinePoints[j]);
pUpperLinePoints = Channels.CoordIL2Double(1,pUpperLinePoints,1,vblSaveCounter,lineType,30);
pLowerLinePoints = Channels.CoordIL2Double(1,pLowerLinePoints,0,vblSaveCounter,lineType,30);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j]=new POINT2(pUpperLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j+vblSaveCounter]=new POINT2(pLowerLinePoints[vblSaveCounter-j-1]);
pUpperLowerLinePoints[2*vblSaveCounter]=new POINT2(pUpperLowerLinePoints[0]);
vblCounter=GetZONEPointsDouble2(pUpperLowerLinePoints,lineType,2*vblSaveCounter+1);
for(j=0;j<vblCounter;j++)
pLinePoints[j]=new POINT2(pUpperLowerLinePoints[j]);
//pLinePoints[j]=pLinePoints[0];
//vblCounter++;
acCounter=vblCounter;
break;
case TacticalLines.BELT: //change 2
case TacticalLines.ZONE:
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.STRONG:
case TacticalLines.FORT:
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.ATWALL:
case TacticalLines.LINE: //7-9-07
acCounter = GetATWallPointsDouble2(pLinePoints, lineType, vblSaveCounter);
break;
// case TacticalLines.ATWALL3D:
// acCounter = GetATWallPointsDouble3D(pLinePoints, lineType, vblSaveCounter);
// break;
case TacticalLines.PLD:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.FEBA:
CoordFEBADouble(pLinePoints,vblCounter);
acCounter=pLinePoints.length;
break;
case TacticalLines.UAV:
case TacticalLines.MRR:
if(rev==RendererSettings.Symbology_2525Bch2_USAS_13_14)
{
dMRR=pOriginalLinePoints[0].style;
if (dMRR <= 0) {
dMRR = 1;//was 14
}
lineutility.GetSAAFRSegment(pLinePoints, lineType, dMRR,rev);
acCounter=6;
}
if(rev==RendererSettings.Symbology_2525C)
{
return GetLineArray2Double(TacticalLines.SAAFR,pLinePoints,vblCounter,vblSaveCounter,shapes,clipBounds,rev);
}
break;
case TacticalLines.MRR_USAS:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR: //added 5-4-07
case TacticalLines.SAAFR: //these have multiple segments
case TacticalLines.AC:
dMRR = dACP;
// if (dMRR <= 0) {
// dMRR = 14;
lineutility.InitializePOINT2Array(acPoints);
lineutility.InitializePOINT2Array(arcPts);
acCounter = 0;
for (j = 0; j < vblSaveCounter;j++)
if(pOriginalLinePoints[j].style<=0)
pOriginalLinePoints[j].style=1; //was 14
//get the SAAFR segments
for (j = 0; j < vblSaveCounter - 1; j++) {
//diagnostic: use style member for dMBR
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRSegment(acPoints, lineType, dMBR,rev);//was dMRR
for (k = 0; k < 6; k++)
{
pLinePoints[acCounter] = new POINT2(acPoints[k]);
acCounter++;
}
}
//get the circles
int nextCircleSize=0,currentCircleSize=0;
for (j = 0; j < vblSaveCounter-1; j++)
{
currentCircleSize=pOriginalLinePoints[j].style;
nextCircleSize=pOriginalLinePoints[j+1].style;
//draw the circle at the segment front end
arcPts[0] = new POINT2(pOriginalLinePoints[j]);
//diagnostic: use style member for dMBR
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
//draw the circle at the segment back end
arcPts[0] = new POINT2(pOriginalLinePoints[j+1]);
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
}
//acPoints = null;
break;
case TacticalLines.MINED:
case TacticalLines.UXO:
acCounter=vblCounter;
break;
case TacticalLines.BEARING:
case TacticalLines.ACOUSTIC:
case TacticalLines.ELECTRO:
case TacticalLines.TORPEDO:
case TacticalLines.OPTICAL:
acCounter=vblCounter;
break;
case TacticalLines.MSDZ:
lineutility.InitializePOINT2Array(circlePoints);
pt3 = new POINT2(pLinePoints[3]);
dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[j] = new POINT2(circlePoints[j]);
}
pLinePoints[99].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt2);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[100 + j] = new POINT2(circlePoints[j]);
}
pLinePoints[199].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt3);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[200 + j] = new POINT2(circlePoints[j]);
}
//acCounter=300;
acCounter=vblCounter;
//FillPoints(pLinePoints,vblCounter,points);
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CONVOY:
d=lineutility.CalcDistanceDouble(pt0, pt1);
if(d<=30)
{
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
pt0 = lineutility.ExtendLine2Double(pt1, pt0, -30, 0);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 30);
lineutility.GetArrowHead4Double(pt0, pt2, 30, 30, pArrowPoints, 0);
d = lineutility.CalcDistanceDouble(pLinePoints[0], pArrowPoints[0]);
d1 = lineutility.CalcDistanceDouble(pLinePoints[3], pArrowPoints[0]);
pLinePoints[3].style = 5;
if (d < d1) {
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[4].style = 0;
pLinePoints[5] = new POINT2(pArrowPoints[0]);
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pArrowPoints[1]);
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pArrowPoints[2]);
pLinePoints[7].style = 0;
pLinePoints[8] = new POINT2(pLinePoints[3]);
} else {
pLinePoints[4] = pLinePoints[3];
pLinePoints[4].style = 0;
pLinePoints[5] = pArrowPoints[0];
pLinePoints[5].style = 0;
pLinePoints[6] = pArrowPoints[1];
pLinePoints[6].style = 0;
pLinePoints[7] = pArrowPoints[2];
pLinePoints[7].style = 0;
pLinePoints[8] = pLinePoints[0];
}
acCounter=9;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.HCONVOY:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
pt2.x = (pt0.x + pt1.x) / 2;
pt2.y = (pt0.y + pt1.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[5] = new POINT2(pt0);
pLinePoints[5].style = 0;
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 50);
lineutility.GetArrowHead4Double(pt2, pt0, 20, 20, pArrowPoints, 0);
// for (j = 0; j < 3; j++)
// pLinePoints[j + 6] = new POINT2(pArrowPoints[j]);
// pLinePoints[8].style = 0;
// pLinePoints[9] = new POINT2(pArrowPoints[0]);
pLinePoints[6]=new POINT2(pArrowPoints[1]);
pLinePoints[7]=new POINT2(pArrowPoints[0]);
pLinePoints[8]=new POINT2(pArrowPoints[2]);
pLinePoints[8].style = 0;
pLinePoints[9] = new POINT2(pArrowPoints[1]);
acCounter=10;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.ONEWAY:
case TacticalLines.ALT:
case TacticalLines.TWOWAY:
nCounter = (int) vblSaveCounter;
pLinePoints[vblSaveCounter - 1].style = 5;
for (j = 0; j < vblSaveCounter - 1; j++) {
d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if(d<20) //too short
continue;
pt0 = new POINT2(pLinePoints[j]);
pt1 = new POINT2(pLinePoints[j + 1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1],m);
d=lineutility.CalcDistanceDouble(pLinePoints[j],pLinePoints[j+1]);
pt2 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -3 * d / 4, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -1 * d / 4, 5);
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
d = 10;
if (dMBR / 20 < minLength) {
d = 5;
}
lineutility.GetArrowHead4Double(pt2, pt3, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
if (lineType == (long) TacticalLines.ALT) {
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
if (lineType == (long) TacticalLines.TWOWAY) {
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
}
acCounter=nCounter;
break;
case TacticalLines.CFL:
for(j=0;j<vblCounter;j++) //dashed lines
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKFNT: //extra three for arrow plus extra three for feint
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<20)//was 10
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], 21);//was 11
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], 20); //was 10
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
d = dMBR;
pt0=lineutility.ExtendLineDouble(pLinePoints[vblCounter-8], pLinePoints[vblCounter - 7], 20); //was 10
pt1 = new POINT2(pLinePoints[vblCounter - 8]);
pt2 = new POINT2(pLinePoints[vblCounter - 7]);
if (d / 10 > maxLength) {
d = 10 * maxLength;
}
if (d / 10 < minLength) {
d = 10 * minLength;
}
if(d<250)
d=250;
if(d>500)
d=250;
lineutility.GetArrowHead4Double(pt1, pt2, (int) d / 10, (int) d / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = pArrowPoints[k];
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) d / 10, (int) d / 10,
pArrowPoints,18);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = pArrowPoints[k];
}
acCounter=vblCounter;
break;
case TacticalLines.FORDIF:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2], pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
for (j = 0; j < vblCounter; j++) {
pLinePoints[j].style = 1;
}
//CommandSight section
//comment 2 lines for CS
pt0 = lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
pt1 = lineutility.MidPointDouble(pLinePoints[2], pLinePoints[3], 0);
//uncomment 3 line for CS
//pt0=new POINT2(pt2);
//d=lineutility.CalcDistanceDouble(pt4, pt2);
//pt1=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], d);
//end section
// pts = new POINT2[2];
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// pointCounter = lineutility.BoundPointsCount(pts, 2);
// segments = new int[pointCounter];
// pts = new POINT2[pointCounter];
// lineutility.InitializePOINT2Array(pts);
// pts[0] = new POINT2(pt0);
// pts[1] = new POINT2(pt1);
// lineutility.BoundPoints(pts, 2, segments);
// for (j = 0; j < pointCounter - 1; j++) {
// if (segments[j] == 1) {
// pt0 = new POINT2(pts[j]);
// pt1 = new POINT2(pts[j + 1]);
// break;
// for (j = 3; j < vblCounter; j++) {
// pLinePoints[j] = new POINT2(pLinePoints[3]);
// pLinePoints[j].style = 5;
// pLinePoints[1].style = 5;
//added section 10-27-20
POINT2[]savepoints=null;
Boolean drawJaggies=true;
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints=lineutility.BoundOneSegment(pt0, pt1, ul, lr);
if(savepoints != null && savepoints.length>1)
{
pt0=savepoints[0];
pt1=savepoints[1];
}
midpt=lineutility.MidPointDouble(pt0, pt1, 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
}
else
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
}
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
//end section
}
else
{
midpt=lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
else
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
}
//end section
//calculate start, end points for upper and lower lines
//across the middle
pt2 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, -10, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, -10, 0);
pt4 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, 10, 0);
pt5 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, 10, 0);
dWidth = lineutility.CalcDistanceDouble(pt0, pt1);
pointCounter = 4;
n = 1;
pLinePoints[pointCounter] = new POINT2(pt0);
pLinePoints[pointCounter].style = 0;
pointCounter++;
//while (dExtendLength < dWidth - 20)
if(drawJaggies)
while (dExtendLength < dWidth - 10)
{
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt2, pt3, dExtendLength - dWidth, 0);
pointCounter++;
n++;
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt4, pt5, dExtendLength - dWidth, 0);
pointCounter++;
n++;
}
pLinePoints[pointCounter] = new POINT2(pt1);
pLinePoints[pointCounter].style = 5;
pointCounter++;
acCounter=pointCounter;
break;
case TacticalLines.ATDITCH:
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
break;
case (int)TacticalLines.ATDITCHC: //extra Points were calculated by a function
pLinePoints[0].style=9;
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style=10;
break;
case TacticalLines.ATDITCHM:
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pLinePoints[0].style = 9;
acCounter = lineutility.GetDitchSpikeDouble(
pLinePoints,
vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style = 20;
break;
case TacticalLines.DIRATKGND:
//reverse the points
//lineutility.ReversePointsDouble2(
//pLinePoints,
//vblSaveCounter);
//was 20
if (dMBR / 30 > maxLength) {
dMBR = 30 * maxLength;
}
if (dMBR / 30 < minLength) {
dMBR = 30 * minLength;
}
//if(dMBR<250)
// dMBR = 250;
if(dMBR<500)
dMBR = 500;
if(dMBR>750)
dMBR = 500;
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<dMBR/40)
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], dMBR/40+1);
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1],dMBR/40);
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pt0 = new POINT2(pLinePoints[vblCounter - 12]);
pt1 = new POINT2(pLinePoints[vblCounter - 11]);
pt2 = lineutility.ExtendLineDouble(pt0, pt1, dMBR / 40);
lineutility.GetArrowHead4Double(pt0, pt1, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 10 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pt0, pt2, (int) (dMBR / 13.33), (int) (dMBR / 13.33),
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 7 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[vblCounter - 10]);
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 7]);
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 5]);
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.MFLANE:
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.RAFT: //extra eight Points for hash marks either end
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>200)
dMBR=200;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKAIR:
//added section for click-drag mode
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
for(k=vblSaveCounter-1;k>0;k
{
d += lineutility.CalcDistanceDouble(pLinePoints[k],pLinePoints[k-1]);
if(d>60)
break;
}
if(d>60)
{
middleSegment=k;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
else
{
if(vblSaveCounter<=3)
middleSegment=1;
else
middleSegment=2;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
pt0 = new POINT2(pLinePoints[0]);
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<150)
dMBR=150;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pLinePoints[vblCounter - 10], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 9 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 6].x = (pLinePoints[vblCounter - 11].x + pLinePoints[vblCounter - 10].x) / 2;
pLinePoints[vblCounter - 6].y = (pLinePoints[vblCounter - 11].y + pLinePoints[vblCounter - 10].y) / 2;
pt0 = new POINT2(pLinePoints[vblCounter - 6]);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt3, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 6 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 10], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt2, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
//this section was added to remove fill from the bow tie feature
ArrayList<POINT2> airPts=new ArrayList();
pLinePoints[middleSegment-1].style=5;
//pLinePoints[middleSegment].style=14;
if(vblSaveCounter==2)
pLinePoints[1].style=5;
for(j=0;j<vblCounter;j++)
airPts.add(new POINT2(pLinePoints[j]));
midpt=lineutility.MidPointDouble(pLinePoints[middleSegment-1], pLinePoints[middleSegment], 0);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment]);
pt1.style=5;
airPts.add(pt1);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment-1], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment-1]);
pt1.style=5;
airPts.add(pt1);
//re-dimension pLinePoints so that it can hold the
//the additional points required by the shortened middle segment
//which has the bow tie feature
vblCounter=airPts.size();
pLinePoints=new POINT2[airPts.size()];
for(j=0;j<airPts.size();j++)
pLinePoints[j]=new POINT2(airPts.get(j));
//end section
acCounter=vblCounter;
//FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PDF:
//reverse pt0 and pt1 8-1-08
pt0 = new POINT2(pLinePoints[1]);
pt1 = new POINT2(pLinePoints[0]);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
//end section
pts2 = new POINT2[3];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts2[2] = new POINT2(pt2);
lineutility.GetPixelsMin(pts2, 3,
offsetX,
offsetY);
if(offsetX.value[0]<0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
pLinePoints[2].style = 5;
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR < minLength) {
dMBR = 20 * minLength;
}
if(dMBR>250)
dMBR=250;
pt2 = lineutility.ExtendLineDouble(pt0, pt1, -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[3] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
pLinePoints[3].style = 0;
pLinePoints[4] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[4].style = 0;
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].y = pt2.y - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].y = pt2.y + 2;
pLinePoints[4].style = 0;
}
if (bolVertical == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].x = pt2.x - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].x = pt2.x + 2;
pLinePoints[4].style = 0;
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, -dMBR / 10);
if (bolVertical != 0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
//get the Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[5] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[5].style = 0;
pLinePoints[6] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].y = pt2.y + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].y = pt2.y - 2;
}
if (bolVertical == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].x = pt2.x + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].x = pt2.x - 2;
}
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pLinePoints[3]);
pLinePoints[7].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[8 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[2], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[11 + j] = new POINT2(pArrowPoints[j]);
pLinePoints[11 + j].style = 0;
}
acCounter=14;
break;
case TacticalLines.DIRATKSPT:
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if(dMBR/20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(client.startsWith("cpof"))
{
if(dMBR<250)
dMBR=250;
}
else
{
if(dMBR<150)
dMBR=150;
}
if(dMBR>500)
dMBR=500;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 5], pLinePoints[vblCounter - 4], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - k - 1] = new POINT2(pArrowPoints[k]);
}
acCounter=vblCounter;
break;
case TacticalLines.ABATIS:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
lineutility.GetPixelsMin(pts2, 2,
offsetX,
offsetY);
if(offsetX.value[0]<=0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
if(dMBR>300)
dMBR=300;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
midpt.x=(pt0.x+pLinePoints[0].x) / 2;
midpt.y = (pt0.y + pLinePoints[0].y) / 2;
pLinePoints[vblCounter - 3] = new POINT2(pt0);
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 3].style = 0;
if (bolVertical != 0 && m.value[0] != 0) {
b = midpt.y + (1 / m.value[0]) * midpt.x; //the line equation
//get Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, dMBR / 20);
if (pLinePoints[vblCounter - 2].y >= midpt.y) {
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dMBR / 20);
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].y = midpt.y - dMBR / 20;
}
if (bolVertical == 0) {
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].x = midpt.x - dMBR / 20;
}
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[0]);
//put the abatis feature on the front
// ArrayList<POINT2>abatisPts=new ArrayList();
// for(j=3;j<vblCounter;j++)
// abatisPts.add(new POINT2(pLinePoints[j-3]));
// abatisPts.add(0,new POINT2(pLinePoints[vblCounter-3]));
// abatisPts.add(1,new POINT2(pLinePoints[vblCounter-2]));
// abatisPts.add(2,new POINT2(pLinePoints[vblCounter-1]));
// for(j=0;j<abatisPts.size();j++)
// pLinePoints[j]=new POINT2(abatisPts.get(j));
//end section
//FillPoints(pLinePoints,vblCounter,points);
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CLUSTER:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
//for some reason occulus puts the points on top of one another
if(Math.abs(pt0.y-pt1.y)<1)
{
pt1.y = pt0.y +1;
}
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts = new POINT2[26];
dRadius = lineutility.CalcDistanceDouble(pt0, pt1) / 2;
midpt.x = (pt1.x + pt0.x) / 2;
midpt.y = (pt1.y + pt0.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical!=0 && m.value[0] != 0) //not vertical or horizontal
{
b = midpt.y + (1 / m.value[0]) * midpt.x; //normal y intercept at x=0
//we want to get the y intercept at x=offsetX
//b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
//ptYIntercept.x = offsetX.value[0];
ptYIntercept.x=0;
//ptYIntercept.y = b1;
ptYIntercept.y = b;
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, dRadius);
if (pLinePoints[0].x <= pLinePoints[1].x) {
if (pt2.y >= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
} else {
if (pt2.y <= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pt2 = midpt;
if (pLinePoints[0].x <= pLinePoints[1].x) {
pt2.y = midpt.y - dRadius;
} else {
pt2.y = midpt.y + dRadius;
}
}
if (bolVertical == 0) //vertical line
{
pt2 = midpt;
if (pLinePoints[0].y <= pLinePoints[1].y) {
pt2.x = midpt.x + dRadius;
} else {
pt2.x = midpt.x - dRadius;
}
}
pt1 = lineutility.ExtendLineDouble(midpt, pt2, 100);
pts[0] = new POINT2(pt2);
pts[1] = new POINT2(pt1);
lineutility.ArcArrayDouble(
pts,
0,dRadius,
lineType);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
for (j = 0; j < 26; j++) {
pLinePoints[2 + j] = new POINT2(pts[j]);
pLinePoints[2 + j].style = 1;
}
acCounter=28;
break;
case TacticalLines.TRIP:
dRadius = lineutility.CalcDistanceToLineDouble(pt0, pt1, pt2);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt1.y + 1 / m.value[0] * pt1.x;
b1 = pt2.y - m.value[0] * pt2.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
b = calcPoint1.y + 1 / m.value[0] * calcPoint1.x;
calcPoint3 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
b = calcPoint2.y + 1 / m.value[0] * calcPoint2.x;
calcPoint4 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
b = pt1.y + 1 / m.value[0] * pt1.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical != 0 && m.value[0] == 0) {
calcPoint0.x = pt1.x;
calcPoint0.y = pt2.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.x = calcPoint0.x + dRadius / 2;
calcPoint3.y = calcPoint0.y;
calcPoint4.x = pt1.x + dRadius;
calcPoint4.y = pt2.y;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical == 0) {
calcPoint0.x = pt2.x;
calcPoint0.y = pt1.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.y = calcPoint0.y + dRadius / 2;
calcPoint3.x = calcPoint0.x;
calcPoint4.y = pt1.y + dRadius;
calcPoint4.x = pt2.x;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
arcPts[0] = new POINT2(calcPoint1);
arcPts[1] = new POINT2(calcPoint3);
lineutility.ArcArrayDouble(
arcPts,
0,dRadius,
lineType);
pLinePoints[0].style = 5;
pLinePoints[1].style = 5;
for (k = 0; k < 26; k++) {
pLinePoints[k] = new POINT2(arcPts[k]);
}
for (k = 25; k < vblCounter; k++) {
pLinePoints[k].style = 5;
}
pLinePoints[26] = new POINT2(pt1);
dRadius = lineutility.CalcDistanceDouble(pt1, pt0);
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 - 7, 0);
pLinePoints[27] = new POINT2(midpt);
pLinePoints[27].style = 0;
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 + 7, 0);
pLinePoints[28] = new POINT2(midpt);
pLinePoints[29] = new POINT2(pt0);
pLinePoints[29].style = 5;
lineutility.GetArrowHead4Double(pt1, pt0, 15, 15, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[30 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 0; k < 3; k++) {
pLinePoints[30 + k].style = 5;
}
midpt = lineutility.MidPointDouble(pt0, pt1, 0);
d = lineutility.CalcDistanceDouble(pt1, calcPoint0);
//diagnostic for CS
//pLinePoints[33] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, d, 0);
//pLinePoints[34] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, -d, 5);
pLinePoints[33]=pt2;
pt3=lineutility.PointRelativeToLine(pt0, pt1, pt0, pt2);
d=lineutility.CalcDistanceDouble(pt3, pt2);
pt4=lineutility.ExtendAlongLineDouble(pt0, pt1, d);
d=lineutility.CalcDistanceDouble(pt2, pt4);
pLinePoints[34]=lineutility.ExtendLineDouble(pt2, pt4, d);
//end section
acCounter=35;
break;
case TacticalLines.FOLLA:
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(client.startsWith("cpof"))
d2=20;
else
d2=30;
if(d<d2)
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>150)
dMBR=150;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -2 * dMBR / 10);
for (k = 0; k < vblCounter - 14; k++) {
pLinePoints[k].style = 18;
}
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], 5 * dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
pLinePoints[vblCounter - 12].style = 0;
pLinePoints[vblCounter - 11] = new POINT2(pArrowPoints[2]);
pLinePoints[vblCounter - 11].style = 0;
pLinePoints[vblCounter - 10] = new POINT2(pArrowPoints[0]);
pLinePoints[vblCounter - 10].style = 0;
pLinePoints[vblCounter - 9] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 9].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 8 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 6].style = 0;
//diagnostic to make first point tip of arrowhead 6-14-12
//pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], 0.75 * dMBR / 10);
pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], -0.75 * dMBR / 10);
pLinePoints[1]=pt3;
pLinePoints[1].style=5;
//lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (1.25 * dMBR / 10), (int) (1.25 * dMBR / 10), pArrowPoints, 0);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (dMBR / 10), (int) (dMBR / 10), pArrowPoints, 0);
//end section
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 5 + k] = new POINT2(pArrowPoints[2 - k]);
}
pLinePoints[vblCounter - 5].style = 0;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 5;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 7]);
acCounter=16;
break;
case TacticalLines.FOLSP:
if(client.startsWith("cpof"))
d2=25;
else
d2=25;
double folspDist=0;
folspDist=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(folspDist<d2) //was 10
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(lineType, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
// else if(folspDist<d2)//was 25
// lineType=TacticalLines.FOLLA;
// GetLineArray2Double(lineType, pLinePoints,16,2,shapes,clipBounds,rev);
// for(k=0;k<pLinePoints.length;k++)
// if(pLinePoints[k].style==18)
// pLinePoints[k].style=0;
// //lineType=TacticalLines.FOLSP;
// //acCounter=16;
// break;
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
if(client.startsWith("cpof"))
{
if(folspDist<25)
dMBR=125;
if(folspDist<75)
dMBR=150;
if(folspDist<100)
dMBR=175;
if(folspDist<125)
dMBR=200;
}
else
{
dMBR*=1.5;
}
//make tail larger 6-10-11 m. Deutch
//pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 8.75);
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 4);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(k=0; k < 3; k++)
{
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 12].style = 0;
//make tail larger 6-10-11 m. Deutch
//pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 20);
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 15);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 11 + k] = new POINT2(pArrowPoints[2 - k]);
pLinePoints[vblCounter - 11 + k].style = 0;
}
pLinePoints[vblCounter - 8] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 8].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 20, (int) dMBR / 20,pArrowPoints,9);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 7 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 4; k > 0; k
{
pLinePoints[vblCounter - k].style = 5;
}
acCounter=12;
break;
case TacticalLines.FERRY:
lLinestyle=9;
if(dMBR/10>maxLength)
dMBR=10*maxLength;
if(dMBR/10<minLength)
dMBR=10*minLength;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-8],pLinePoints[vblCounter-7],(int)dMBR/10,(int)dMBR/10,pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-6+k]=new POINT2(pArrowPoints[k]);
lineutility.GetArrowHead4Double(pLinePoints[1],pLinePoints[0],(int)dMBR/10,(int)dMBR/10, pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-3+k]=new POINT2(pArrowPoints[k]);
acCounter=8;
break;
case TacticalLines.NAVIGATION:
pt3 = lineutility.ExtendLine2Double(pt1, pt0, -10, 0);
pt4 = lineutility.ExtendLine2Double(pt0, pt1, -10, 0);
pt5 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, 10, 0);
pt6 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, -10, 0);
pt7 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, 10, 0);
pt8 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, -10, 0);
if (pt5.y < pt6.y) {
pLinePoints[0] = new POINT2(pt5);
} else {
pLinePoints[0] = new POINT2(pt6);
}
if (pt7.y > pt8.y) {
pLinePoints[3] = new POINT2(pt7);
} else {
pLinePoints[3] = new POINT2(pt8);
}
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
acCounter=4;
break;
case TacticalLines.FORTL:
acCounter=GetFORTLPointsDouble(pLinePoints,lineType,vblSaveCounter);
break;
// case TacticalLines.HOLD:
// case TacticalLines.BRDGHD:
// lineutility.ReorderPoints(pLinePoints);
// acCounter=pLinePoints.length;
// FillPoints(pLinePoints,acCounter,points);
// break;
case TacticalLines.CANALIZE:
acCounter = DISMSupport.GetDISMCanalizeDouble(pLinePoints,lineType);
break;
case TacticalLines.BREACH:
acCounter=DISMSupport.GetDISMBreachDouble( pLinePoints,lineType);
break;
case TacticalLines.SCREEN:
case TacticalLines.GUARD:
case TacticalLines.COVER:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SCREEN_REVC: //works for 3 or 4 points
case TacticalLines.GUARD_REVC:
case TacticalLines.COVER_REVC:
acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SARA:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//reorder pLinePoints
POINT2[]saraPts=new POINT2[16];
for(j=0;j<4;j++)
saraPts[j]=pLinePoints[j];
for(j=4;j<8;j++)
saraPts[j]=pLinePoints[j+4]; //8-11
for(j=8;j<12;j++)
saraPts[j]=pLinePoints[j-4];
for(j=12;j<16;j++)
saraPts[j]=pLinePoints[j]; //12-15
pLinePoints=saraPts;
//acCounter=14;
break;
case TacticalLines.DISRUPT:
acCounter=DISMSupport.GetDISMDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.CONTAIN:
acCounter=DISMSupport.GetDISMContainDouble(pLinePoints,lineType);
break;
case TacticalLines.PENETRATE:
DISMSupport.GetDISMPenetrateDouble(pLinePoints,lineType);
acCounter=7;
break;
case TacticalLines.MNFLDBLK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.BLOCK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.LINTGT:
case TacticalLines.LINTGTS:
case TacticalLines.FPF:
acCounter=DISMSupport.GetDISMLinearTargetDouble(pLinePoints, lineType, vblCounter);
break;
case TacticalLines.GAP:
case TacticalLines.ASLTXING:
case TacticalLines.BRIDGE: //change 1
DISMSupport.GetDISMGapDouble(
pLinePoints,
lineType);
acCounter=12;
break;
case TacticalLines.MNFLDDIS:
acCounter=DISMSupport.GetDISMMinefieldDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.SPTBYFIRE:
acCounter=DISMSupport.GetDISMSupportByFireDouble(pLinePoints,lineType);
break;
case TacticalLines.ATKBYFIRE:
acCounter=DISMSupport.GetDISMATKBYFIREDouble(pLinePoints,lineType);
break;
case TacticalLines.BYIMP:
acCounter=DISMSupport.GetDISMByImpDouble(pLinePoints,lineType);
break;
case TacticalLines.CLEAR:
acCounter=DISMSupport.GetDISMClearDouble(pLinePoints,lineType);
break;
case TacticalLines.BYDIF:
acCounter=DISMSupport.GetDISMByDifDouble(pLinePoints,lineType,clipBounds);
break;
case TacticalLines.SEIZE:
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,0);
break;
case TacticalLines.SEIZE_REVC: //works for 3 or 4 points
double radius=0;
if(rev==RendererSettings.Symbology_2525C)
{
radius=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
pLinePoints[1]=new POINT2(pLinePoints[3]);
pLinePoints[2]=new POINT2(pLinePoints[2]);
}
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,radius);
break;
case TacticalLines.FIX:
case TacticalLines.MNFLDFIX:
acCounter = DISMSupport.GetDISMFixDouble(pLinePoints, lineType,clipBounds);
break;
case TacticalLines.RIP:
acCounter = DISMSupport.GetDISMRIPDouble(pLinePoints,lineType);
break;
case TacticalLines.DELAY:
case TacticalLines.WITHDRAW:
case TacticalLines.WDRAWUP:
case TacticalLines.RETIRE:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
acCounter=DISMSupport.GetDelayGraphicEtcDouble(pLinePoints);
break;
case TacticalLines.EASY:
acCounter=DISMSupport.GetDISMEasyDouble(pLinePoints,lineType);
break;
case TacticalLines.DECEIVE:
DISMSupport.GetDISMDeceiveDouble(pLinePoints);
acCounter=4;
break;
case TacticalLines. BYPASS:
acCounter=DISMSupport.GetDISMBypassDouble(pLinePoints,lineType);
break;
case TacticalLines.PAA_RECTANGULAR:
DISMSupport.GetDISMPAADouble(pLinePoints,lineType);
acCounter=5;
break;
case TacticalLines.AMBUSH:
acCounter=DISMSupport.AmbushPointsDouble(pLinePoints);
break;
case TacticalLines.FLOT:
acCounter=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
break;
default:
acCounter=vblSaveCounter;
break;
}
//diagnostic
//lineutility.WriteFile(Double.toString(pLinePoints[0].x)+" to "+Double.toString(pLinePoints[1].x));
//end diagnostic
//Fill points
//and/or return points if shapes is null
switch(lineType)
{
case TacticalLines.BOUNDARY:
FillPoints(pLinePoints,acCounter,points);
return points;
case TacticalLines.CONTAIN:
case TacticalLines.BLOCK:
//case TacticalLines.DMAF: //points are already filled for DMAF
case TacticalLines.COVER:
case TacticalLines.SCREEN: //note: screen, cover, guard are getting their modifiers before the call to getlinearray
case TacticalLines.GUARD:
case TacticalLines.COVER_REVC:
case TacticalLines.SCREEN_REVC:
case TacticalLines.GUARD_REVC:
//case TacticalLines.DUMMY: //commented 5-3-10
case TacticalLines.PAA_RECTANGULAR:
case TacticalLines.FOLSP:
case TacticalLines.FOLLA:
//add these for rev c 3-12-12
case TacticalLines.BREACH:
case TacticalLines.BYPASS:
case TacticalLines.CANALIZE:
case TacticalLines.CLEAR:
case TacticalLines.DISRUPT:
case TacticalLines.FIX:
case TacticalLines.ISOLATE:
case TacticalLines.OCCUPY:
case TacticalLines.PENETRATE:
case TacticalLines.RETAIN:
case TacticalLines.SECURE:
case TacticalLines.SEIZE:
case TacticalLines.SEIZE_REVC:
case TacticalLines.BS_RECTANGLE:
case TacticalLines.BBS_RECTANGLE:
//add these
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.MSDZ:
case TacticalLines.CONVOY:
case TacticalLines.HCONVOY:
case TacticalLines.MFLANE:
case TacticalLines.DIRATKAIR:
case TacticalLines.ABATIS:
FillPoints(pLinePoints,acCounter,points);
break;
default:
//if shapes is null then it is a non-CPOF client, dependent upon pixels
//instead of shapes
if(shapes==null)
{
FillPoints(pLinePoints,acCounter,points);
return points;
}
break;
}
//the shapes require pLinePoints
//if the shapes are null then it is a non-CPOF client,
if(shapes==null)
return points;
Shape2 shape=null;
Shape gp=null;
Shape2 redShape=null,blueShape=null,paleBlueShape=null,whiteShape=null;
Shape2 redFillShape=null,blueFillShape=null,blackShape=null;
BasicStroke blueStroke,paleBlueStroke;
Area blueArea=null;
Area paleBlueArea=null;
Area whiteArea=null;
boolean beginLine=true;
Polygon poly=null;
//a loop for the outline shapes
switch(lineType)
{
case TacticalLines.BBS_AREA:
case TacticalLines.BBS_RECTANGLE:
// for(j=0;j<vblSaveCounter-1;j++)
// shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
// shape.moveTo(pOriginalLinePoints[j]);
// shape.lineTo(pLinePoints[j]);
// shape.lineTo(pLinePoints[j+1]);
// shape.lineTo(pOriginalLinePoints[j+1]);
// shape.lineTo(pOriginalLinePoints[j]);
// shapes.add(shape);
// //shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pLinePoints[0]);
for(j=0;j<vblSaveCounter;j++)
shape.lineTo(pLinePoints[j]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pOriginalLinePoints[0]);
for(j=1;j<vblSaveCounter;j++)
shape.lineTo(pOriginalLinePoints[j]);
shapes.add(shape);
break;
case TacticalLines.DIRATKGND:
//create two shapes. the first shape is for the line
//the second shape is for the arrow
//renderer will know to use a skinny stroke for the arrow shape
//the line shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
shape.moveTo(pLinePoints[0]);
for(j=0;j<acCounter-10;j++)
{
//shape.lineTo(pLinePoints[j].x,pLinePoints[j].y);
shape.lineTo(pLinePoints[j]);
}
shapes.add(shape);
//the arrow shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[acCounter-10].x,pLinePoints[acCounter-10].y);
shape.moveTo(pLinePoints[acCounter-10]);
for(j=9;j>0;j
{
if(pLinePoints[acCounter-j-1].style == 5)
{
//shape.moveTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.moveTo(pLinePoints[acCounter-j]);
}
else
{
//shape.lineTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.lineTo(pLinePoints[acCounter-j]);
}
}
//shape.lineTo(pLinePoints[acCounter-1].x,pLinePoints[acCounter-1].y);
shapes.add(shape);
break;
// case TacticalLines.BBS_LINE:
// Shape2 outerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//line color
// Shape2 innerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//fill color
// BasicStroke wideStroke=new BasicStroke(pLinePoints[0].style);
// BasicStroke thinStroke=new BasicStroke(pLinePoints[0].style-1);
// for(k=0;k<vblSaveCounter;k++)
// if(k==0)
// outerShape.moveTo(pLinePoints[k]);
// innerShape.moveTo(pLinePoints[k]);
// else
// outerShape.lineTo(pLinePoints[k]);
// innerShape.lineTo(pLinePoints[k]);
// outerShape.setStroke(wideStroke);
// innerShape.setStroke(thinStroke);
// shapes.add(outerShape);
// shapes.add(innerShape);
// break;
case TacticalLines.DEPTH_AREA:
paleBlueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
paleBlueShape.setFillColor(new Color(153,204,255));
paleBlueStroke=new BasicStroke(28);
blueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
blueShape.setFillColor(new Color(30,144,255));
blueStroke=new BasicStroke(14);
whiteShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
whiteShape.setFillColor(Color.WHITE);
poly=new Polygon();
for(k=0;k<vblSaveCounter;k++)
{
poly.addPoint((int)pLinePoints[k].x, (int)pLinePoints[k].y);
if(k==0)
whiteShape.moveTo(pLinePoints[k]);
else
whiteShape.lineTo(pLinePoints[k]);
}
whiteArea=new Area(poly);
blueArea=new Area(blueStroke.createStrokedShape(poly));
blueArea.intersect(whiteArea);
blueShape.setShape(lineutility.createStrokedShape(blueArea));
paleBlueArea=new Area(paleBlueStroke.createStrokedShape(poly));
paleBlueArea.intersect(whiteArea);
paleBlueShape.setShape(lineutility.createStrokedShape(paleBlueArea));
shapes.add(whiteShape);
shapes.add(paleBlueShape);
shapes.add(blueShape);
break;
case TacticalLines.TRAINING_AREA:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for outline
redShape.set_Style(1);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for symbol
blueShape.set_Style(0);
redShape.moveTo(pLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
redShape.lineTo(pLinePoints[k]);
//blueShape.moveTo(pLinePoints[vblSaveCounter]);
beginLine=true;
for(k=vblSaveCounter;k<acCounter;k++)
{
if(pLinePoints[k].style==0)
{
if(beginLine)
{
blueShape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
blueShape.lineTo(pLinePoints[k]);
}
if(pLinePoints[k].style==5)
{
blueShape.lineTo(pLinePoints[k]);
beginLine=true;
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.ITD:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.GREEN);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFY:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//flots and spikes (triangles)
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
//blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
//blackShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//red and blue short segments (between the flots)
for(k=0;k<vblCounter-1;k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFG:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes red outline
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==22)
{
POINT2[] CirclePoints=new POINT2[8];
redShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
redShape.setFillColor(Color.RED);
if(redShape !=null && redShape.getShape() != null)
shapes.add(redShape);
}
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
blueShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
blueShape.setFillColor(Color.BLUE);
if(blueShape !=null && blueShape.getShape() != null)
shapes.add(blueShape);
}
}
break;
case TacticalLines.USF:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
beginLine=true;
//int color=0;//red
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==19)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==25)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SF:
blackShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blackShape.setLineColor(Color.BLACK);
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23)
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//12-30-11
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
blackShape.lineTo(pLinePoints[l]);
}
redFillShape.lineTo(pLinePoints[k-9]); //12-30-11
shapes.add(redFillShape); //12-30-11
}
if(pLinePoints[k].style==24)
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
blueFillShape.lineTo(pLinePoints[k-2]);
shapes.add(blueFillShape); //12-30-11
blackShape.moveTo(pLinePoints[k-2]);
blackShape.lineTo(pLinePoints[k-1]);
blackShape.lineTo(pLinePoints[k]);
}
}
//the corners
blackShape.moveTo(pOriginalLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
blackShape.lineTo(pOriginalLinePoints[k]);
//shapes.add(redFillShape); //12-30-11
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
shapes.add(blackShape);
break;
case TacticalLines.WFG:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.FOLLA:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1); //dashed line
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(0); //dashed line
//shape.moveTo(pLinePoints[2]);
for(j=2;j<vblCounter;j++)
{
if(pLinePoints[j-1].style != 5)
shape.lineTo(pLinePoints[j]);
else
shape.moveTo(pLinePoints[j]);
}
shapes.add(shape);
break;
case TacticalLines.CFG:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==9)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
d=lineutility.CalcDistanceDouble(pLinePoints[k], pLinePoints[k+1]);
pt0=lineutility.ExtendAlongLineDouble(pLinePoints[k], pLinePoints[k+1], d-5);
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pt0.x,pt0.y);
shape.lineTo(pt0);
}
if(pLinePoints[k].style==0 && k==acCounter-2)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.PIPE:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==1)
{
if(k==0)
{
shape.moveTo(pLinePoints[k]);
}
else
shape.lineTo(pLinePoints[k]);
}
}
shapes.add(shape);
break;
case TacticalLines.ATDITCHM:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 4, 8, CirclePoints, 9);//was 3
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
if(k<acCounter-2)
{
if(pLinePoints[k].style!=0 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==10)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
//use shapes instead of pixels
// if(shape==null)
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// if(beginLine)
// if(k==0)
// shape.set_Style(pLinePoints[k].style);
// shape.moveTo(pLinePoints[k]);
// beginLine=false;
// else
// //diagnostic 1-8-13
// if(k<acCounter-1)
// if(pLinePoints[k].style==5)
// shape.moveTo(pLinePoints[k]);
// continue;
// //end section
// shape.lineTo(pLinePoints[k]);
// //diagnostic 1-8-13
// //if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
// if(pLinePoints[k].style==10)
// beginLine=true;
// if(pLinePoints[k+1].style==20)
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
if(k<acCounter-2)
{
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
}//end for
break;
case TacticalLines.DIRATKFNT:
//the solid lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18)
continue;
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k>0) //doubled points with linestyle=5
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
continue;//shape.lineTo(pLinePoints[k]);
if(k==0)
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==vblCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
//the dashed lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18 && pLinePoints[k-1].style == 5)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.set_Style(pLinePoints[k].style);
shape.set_Style(1);
shape.moveTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==18 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
}
else
continue;
}
break;
case TacticalLines.ESR1:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[2].style);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
break;
case TacticalLines.DUMMY: //commented 5-3-10
//first shape is the original points
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.set_Style(1);
// shape.moveTo(pLinePoints[acCounter-1]);
// shape.lineTo(pLinePoints[acCounter-2]);
// shape.lineTo(pLinePoints[acCounter-3]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for (k = 0; k < acCounter-3; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k==0)
shape.set_Style(pLinePoints[k].style);
//if(k>0) //doubled points with linestyle=5
// if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
// shape.lineTo(pLinePoints[k]);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-4) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1);
shape.moveTo(pLinePoints[acCounter-1]);
shape.lineTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-3]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMA:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[vblCounter-3]);
shape.set_Style(1);
shape.lineTo(pLinePoints[vblCounter-2]);
shape.lineTo(pLinePoints[vblCounter-1]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.FORDIF:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[4].style);
shape.moveTo(pLinePoints[4]);
for(k=5;k<acCounter;k++)
{
if(pLinePoints[k-1].style != 5)
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMAF:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(points.get(0).style);
shape.moveTo(points.get(0));
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(points.get(k));
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(points.get(vblCounter-3));
shape.set_Style(1);
shape.lineTo(points.get(vblCounter-2));
shape.lineTo(points.get(vblCounter-1));
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for(k=vblCounter;k<points.size();k++)
{
if(beginLine)
{
if(k==0)
shape.set_Style(points.get(k).style);
if(k>0) //doubled points with linestyle=5
if(points.get(k).style==5 && points.get(k-1).style==5)
shape.lineTo(points.get(k));
shape.moveTo(points.get(k));
beginLine=false;
}
else
{
shape.lineTo(points.get(k));
if(points.get(k).style==5 || points.get(k).style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==points.size()-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.AIRFIELD:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for (k = 1; k < acCounter-5; k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[acCounter-4]);
shape.lineTo(pLinePoints[acCounter-3]);
shape.moveTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-1]);
shapes.add(shape);
//we need an extra shape to outline the center feature
//in case there is opaque fill that obliterates it
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.MIN_POINTS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for(k=1;k<pLinePoints.length;k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
break;
default:
for (k = 0; k < acCounter; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
//if(pLinePoints[k].style==5)
// continue;
if(k==0)
shape.set_Style(pLinePoints[k].style);
if(k>0) //doubled points with linestyle=5
{
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5 && k< acCounter-1)
continue;
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==10)
continue;
}
if(k==0 && pLinePoints.length>1)
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==5)
continue;
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
break;
}//end switch
//a loop for arrowheads with fill
//these require a separate shape for fill
switch(lineType)
{
case TacticalLines.AC:
case TacticalLines.SAAFR:
case TacticalLines.MRR:
case TacticalLines.MRR_USAS:
case TacticalLines.UAV:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR:
for (j = 0; j < vblSaveCounter - 1; j++) {
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRFillSegment(acPoints, dMBR);//was dMRR
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(acPoints[0]);
shape.lineTo(acPoints[1]);
shape.lineTo(acPoints[2]);
shape.lineTo(acPoints[3]);
shapes.add(0,shape);
}
break;
case TacticalLines.BELT1://requires non-decorated fill shape
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pUpperLinePoints[0]);
for(j=1;j<pUpperLinePoints.length;j++)
{
shape.lineTo(pUpperLinePoints[j]);
//lineutility.SegmentLineShape(pUpperLinePoints[j], pUpperLinePoints[j+1], shape);
}
shape.lineTo(pLowerLinePoints[pLowerLinePoints.length-1]);
for(j=pLowerLinePoints.length-1;j>=0;j
{
shape.lineTo(pLowerLinePoints[j]);
//lineutility.SegmentLineShape(pLowerLinePoints[j], pLowerLinePoints[j-1], shape);
}
shape.lineTo(pUpperLinePoints[0]);
shapes.add(0,shape);
break;
case TacticalLines.DIRATKAIR:
//added this section to not fill the bow tie and instead
//add a shape to close what had been the bow tie fill areas with
//a line segment for each one
int outLineCounter=0;
POINT2[]ptOutline=new POINT2[4];
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==10)
{
//shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[k-2]);
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(1,shape);
//collect these four points
ptOutline[outLineCounter++]=pLinePoints[k-2];
ptOutline[outLineCounter++]=pLinePoints[k];
}
}//end for
//build a shape from the to use as outline for the feature
//if fill alpha is high
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.moveTo(ptOutline[0]);
// shape.lineTo(ptOutline[1]);
// shape.lineTo(ptOutline[3]);
// shape.lineTo(ptOutline[2]);
// shape.lineTo(ptOutline[0]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(0,shape);
break;
case TacticalLines.OFY:
case TacticalLines.OCCLUDED:
case TacticalLines.WF:
case TacticalLines.WFG:
case TacticalLines.WFY:
case TacticalLines.CF:
case TacticalLines.CFY:
case TacticalLines.CFG:
//case TacticalLines.SF:
//case TacticalLines.SFY:
//case TacticalLines.SFG:
case TacticalLines.SARA:
case TacticalLines.FERRY:
case TacticalLines.EASY:
case TacticalLines.BYDIF:
case TacticalLines.BYIMP:
case TacticalLines.FOLSP:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
case TacticalLines.MNFLDFIX:
case TacticalLines.TURN:
case TacticalLines.MNFLDDIS:
//POINT2 initialFillPt=null;
for (k = 0; k < acCounter; k++)
{
if(k==0)
{
if(pLinePoints[k].style==9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
}
else
{
if(pLinePoints[k].style==9 && pLinePoints[k-1].style != 9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
if(pLinePoints[k].style==9 && pLinePoints[k-1].style==9) //9,9,...,9,10
{
shape.lineTo(pLinePoints[k]);
}
}
if(pLinePoints[k].style==10)
{
shape.lineTo(pLinePoints[k]);
//if(lineType==TacticalLines.SARA)
//shape.lineTo(pLinePoints[k-2]);
if(shape !=null && shape.getShape() != null)
{
//must line to the initial fill point to close the shape
//this is a requirement for the java linear ring (map3D java client)
//if(initialFillPt != null)
//shape.lineTo(initialFillPt);
shapes.add(0,shape);
//initialFillPt=null;
}
}
}//end for
break;
default:
break;
}
//CELineArray.add_Shapes(shapes);
//clean up
pArrowPoints=null;
arcPts=null;
circlePoints=null;
pOriginalLinePoints=null;
pts2=null;
pts=null;
segments=null;
pUpperLinePoints=null;
pLowerLinePoints=null;
pUpperLowerLinePoints=null;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetLineArray2Double",
new RendererException("GetLineArray2Dboule " + Integer.toString(lineType), exc));
}
return points;
}
} |
package rsv.process.control;
import org.apache.log4j.Logger;
import rsv.process.lib.SendMail;
import rsv.process.model.GratiaDatabase;
import rsv.process.model.OIMDatabase;
import rsv.process.model.RSVDatabase;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import java.nio.channels.*;
import rsv.process.Configuration;
public class RSVMain {
public static final int exitcode_invalid_arg = -1;
public static final int exitcode_ok = 0;
public static final int exitcode_warning = 1;
public static final int exitcode_error = 2;
private static final Logger logger = Logger.getLogger(RSVMain.class);
public static Configuration conf = null;
public static final String version = "1.11";
public static boolean debug = false;
public static void main(String[] args) {
int ret = exitcode_ok;
try {
logger.info("Initializing RSV Process " + version);
conf = new Configuration();
conf.load(new FileInputStream("rsvprocess.conf"));
RSVMain app = new RSVMain();
if(RSVMain.conf.getProperty(Configuration.debug).equals("true")) {
debug = true;
}
if(args.length == 0) {
showUsage();
} else {
String command = args[0];
//get file lock to make sure I am the only one running this process
String lock_filename = conf.getProperty(Configuration.common_filelock_prefix) + "." + command;
FileOutputStream fos= new FileOutputStream(lock_filename);
FileLock fl = fos.getChannel().tryLock();
if(fl != null) {
//ok. run specified process
try {
ret = app.dispatch(command, args);
} catch (Exception e) {
logger.error("Unhandled exception" , e);
//TODO - send email to GOC?
ret = exitcode_warning;
}
fl.release();
} else {
System.out.println("Failed to obtain filelock on " + lock_filename);
}
fos.close();
}
} catch (FileNotFoundException e) {
logger.error("rsvprocess.conf not found in currernt directory.", e);
SendMail.sendErrorEmail(e.getMessage());
ret = exitcode_error;
} catch (IOException e) {
logger.error("Failed to read rsvprocess.conf", e);
SendMail.sendErrorEmail(e.getMessage());
ret = exitcode_error;
} catch (Exception e) {
logger.error(e);
SendMail.sendErrorEmail(e.getMessage());
ret = exitcode_error;
}
exit(ret);
}
public static void exit(int ret)
{
printErrorCode(ret);
RSVDatabase.closeDB();
GratiaDatabase.closeDB();
OIMDatabase.closeDB();
System.exit(ret);
}
public int dispatch(String command, String args[]) {
//determine which process to run
RSVProcess process = null;
if(command.compareToIgnoreCase("preprocess") == 0) {
process = new RSVPreprocess();
} else if(command.compareToIgnoreCase("overallstatus") == 0) {
process = new RSVOverallStatus();
} else if(command.compareToIgnoreCase("availability") == 0) {
process = new RSVAvailability();
} else if(command.compareToIgnoreCase("vomatrix") == 0) {
process = new RSVVOMatrix();
} else if(command.compareToIgnoreCase("cache") == 0) {
process = new RSVCurrentStatusCache();
}
//then run it
if(process == null) {
logger.error("Unknown command specified: " + command);
showUsage();
return RSVMain.exitcode_invalid_arg;
} else {
int ret = process.run(args);
logger.info("Process Ended with return code " + ret);
return ret;
}
}
public static int showUsage()
{
System.out.println("RSVProcess Usage");
System.out.println("> java rsvprocess.jar [command]");
System.out.println("\t[command]");
System.out.println("\tpreprocess - Run Preprocess");
System.out.println("\toverallstatus - Overall Status Calculation Process");
System.out.println("\t\t optional arguments: [resource_id] [start_time] [end_time]
"Causes status recalculation on specific resource and specific time period. " +
"This will not update the processlog.");
System.out.println("\tavailability - Calculate Availability, Reliability Number for all resources / services and create xml cache");
System.out.println("\t\t[start_time] [end_time]");
System.out.println("\tvomatrix - VO Matrix Processing");
return exitcode_ok;
}
public static void printErrorCode(int code) {
switch(code) {
case RSVMain.exitcode_invalid_arg:
System.out.println("Invalid Argument");
break;
case RSVMain.exitcode_ok:
System.out.println("Process ended OK");
break;
case RSVMain.exitcode_warning:
System.out.println("Process ended with Warning");
break;
case RSVMain.exitcode_error:
System.out.println("Process ended with Error");
break;
}
}
} |
package imagej.script;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
/**
* Abstract superclass for {@link ScriptLanguage} implementations which adapt an
* existing {@link ScriptEngineFactory}.
* <p>
* This is useful for situations where a JSR-223-compliant script engine has
* been provided, but whose behavior we need to extend or tweak.
* </p>
*
* @author Curtis Rueden
*/
public class AdaptedScriptLanguage extends AbstractScriptLanguage {
/** The {@link ScriptEngineFactory} which this one adapts. */
private final ScriptEngineFactory base;
/**
* Creates a new {@link AdaptedScriptLanguage} wrapping the given
* {@link ScriptEngineFactory}.
*/
public AdaptedScriptLanguage(final ScriptEngineFactory base) {
this.base = base;
}
/**
* Creates a new {@link AdaptedScriptLanguage} wrapping the
* {@link ScriptEngineFactory} with the given name.
*/
public AdaptedScriptLanguage(final String factoryName) {
this(findFactory(factoryName));
}
// -- ScriptEngineFactory methods --
@Override
public String getEngineName() {
return base.getEngineName();
}
@Override
public String getEngineVersion() {
return base.getEngineVersion();
}
@Override
public List<String> getExtensions() {
return base.getExtensions();
}
@Override
public List<String> getMimeTypes() {
return base.getMimeTypes();
}
@Override
public List<String> getNames() {
return base.getNames();
}
@Override
public String getLanguageName() {
return base.getLanguageName();
}
@Override
public String getLanguageVersion() {
return base.getLanguageVersion();
}
@Override
public Object getParameter(final String key) {
return base.getParameter(key);
}
@Override
public String getMethodCallSyntax(final String obj, final String m,
final String... args)
{
return base.getMethodCallSyntax(obj, m, args);
}
@Override
public String getOutputStatement(final String toDisplay) {
return base.getOutputStatement(toDisplay);
}
@Override
public String getProgram(final String... statements) {
return base.getProgram(statements);
}
@Override
public ScriptEngine getScriptEngine() {
return base.getScriptEngine();
}
// -- Helper methods --
private static ScriptEngineFactory findFactory(final String factoryName) {
final ScriptEngineManager manager = new javax.script.ScriptEngineManager();
for (final ScriptEngineFactory factory : manager.getEngineFactories()) {
for (final String name : factory.getNames()) {
if (factoryName.equals(name)) return factory;
}
}
return null;
}
} |
// LegacyPlugin.java
package imagej.legacy.plugin;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Roi;
import imagej.data.Dataset;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.ext.module.ItemIO;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Parameter;
import imagej.legacy.LegacyImageMap;
import imagej.legacy.LegacyOutputTracker;
import imagej.legacy.LegacyService;
import imagej.legacy.translate.DefaultImageTranslator;
import imagej.legacy.translate.Harmonizer;
import imagej.legacy.translate.ImageTranslator;
import imagej.legacy.translate.LegacyUtils;
import imagej.ui.DialogPrompt;
import imagej.ui.IUserInterface;
import imagej.ui.UIService;
import imagej.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Executes an IJ1 plugin.
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyPlugin implements ImageJPlugin {
@Parameter
private String className;
@Parameter
private String arg;
@Parameter(type = ItemIO.OUTPUT)
private List<ImageDisplay> outputs;
@Parameter(required = true, persist = false)
private ImageDisplayService imageDisplayService;
@Parameter(required = true, persist = false)
private LegacyService legacyService;
@Parameter(required = true, persist = false)
private UIService uiService;
// -- LegacyPlugin methods --
/** Gets the list of output {@link ImageDisplay}s. */
public List<ImageDisplay> getOutputs() {
return Collections.unmodifiableList(outputs);
}
// -- Runnable methods --
@Override
public void run() {
final ImageDisplay activeDisplay =
imageDisplayService.getActiveImageDisplay();
if (!isLegacyCompatible(activeDisplay)) {
final String err =
"The active dataset is too large to be represented inside IJ1.";
Log.error(err);
notifyUser(err);
outputs = new ArrayList<ImageDisplay>();
return;
}
final LegacyImageMap map = legacyService.getImageMap();
// sync legacy images to match existing modern displays
final ImageTranslator imageTranslator = new DefaultImageTranslator();
final Harmonizer harmonizer = new Harmonizer(imageTranslator);
final Set<ImagePlus> outputSet = LegacyOutputTracker.getOutputImps();
final Set<ImagePlus> closedSet = LegacyOutputTracker.getClosedImps();
harmonizer.resetTypeTracking();
updateImagePlusesFromDisplays(map, harmonizer);
// must happen after updateImagePlusesFromDisplays()
outputSet.clear();
closedSet.clear();
// set ImageJ1's active image
legacyService.syncActiveImage();
try {
Set<Thread> originalThreads = getCurrentThreads();
// execute the legacy plugin
IJ.runPlugIn(className, arg);
// we always sleep at least once to make sure plugin has time to hatch
// it's first thread if its going to create any.
try { Thread.sleep(50); } catch (InterruptedException e) {}
// wait for any threads hatched by plugin to terminate
waitForPluginThreads(originalThreads);
// sync modern displays to match existing legacy images
outputs = updateDisplaysFromImagePluses(map, harmonizer);
}
catch (final Exception e) {
final String msg = "ImageJ 1.x plugin threw exception";
Log.error(msg, e);
notifyUser(msg);
// make sure our ImagePluses are in sync with original Datasets
updateImagePlusesFromDisplays(map, harmonizer);
// return no outputs
outputs = new ArrayList<ImageDisplay>();
}
// close any displays that IJ1 wants closed
for (final ImagePlus imp : closedSet) {
final ImageDisplay disp = map.lookupDisplay(imp);
if (disp != null) {
// REMOVED next line to fix #803. May leave extra windows open.
// outputs.remove(display);
// Now only close displays that have not been changed
if (!outputs.contains(disp))
disp.close();
}
}
// clean up
harmonizer.resetTypeTracking();
outputSet.clear();
closedSet.clear();
// reflect any changes to globals in IJ2 options/prefs
legacyService.updateIJ2Settings();
}
// -- Helper methods --
private Set<Thread> getCurrentThreads() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
Thread[] threads;
int numThreads;
int size = 25;
do {
threads = new Thread[size];
numThreads = group.enumerate(threads);
size *= 2;
} while (numThreads > threads.length);
Set<Thread> threadSet = new HashSet<Thread>();
for (int i = 0; i < numThreads; i++)
threadSet.add(threads[i]);
return threadSet;
}
private void waitForPluginThreads(Set<Thread> threadsToIgnore) {
Set<Thread> currentThreads = getCurrentThreads();
for (Thread thread : currentThreads) {
if ((thread != Thread.currentThread()) &&
(!threadsToIgnore.contains(thread)))
try { thread.join(); } catch (InterruptedException e) {}
}
}
private void updateImagePlusesFromDisplays(final LegacyImageMap map,
final Harmonizer harmonizer)
{
// TODO - track events and keep a dirty bit, then only harmonize those
// displays that have changed. See ticket #546.
final List<ImageDisplay> imageDisplays =
imageDisplayService.getImageDisplays();
for (final ImageDisplay display : imageDisplays) {
ImagePlus imp = map.lookupImagePlus(display);
if (imp == null) {
if (isLegacyCompatible(display)) {
imp = map.registerDisplay(display);
harmonizer.registerType(imp);
}
}
else { // imp already exists : update it
harmonizer.updateLegacyImage(display, imp);
harmonizer.registerType(imp);
}
}
}
private List<ImageDisplay> updateDisplaysFromImagePluses(
final LegacyImageMap map, final Harmonizer harmonizer)
{
// TODO - check the changes flag for each ImagePlus that already has a
// ImageDisplay and only harmonize those that have changed. Maybe changes
// flag does not track everything (such as metadata changes?) and thus
// we might still have to do some minor harmonization. Investigate.
final Set<ImagePlus> imps = LegacyOutputTracker.getOutputImps();
final ImagePlus currImp = WindowManager.getCurrentImage();
// see method below
finishInProgressPastes(currImp, imps);
// the IJ1 plugin may not have any outputs but just changes current
// ImagePlus make sure we catch any changes via harmonization
final List<ImageDisplay> displays = new ArrayList<ImageDisplay>();
if (currImp != null) {
ImageDisplay display = map.lookupDisplay(currImp);
if (display != null) {
harmonizer.updateDisplay(display, currImp);
}
else {
display = map.registerLegacyImage(currImp);
displays.add(display);
}
}
// also harmonize any outputs
for (final ImagePlus imp : imps) {
if (imp.getStack().getSize() == 0) { // totally emptied by plugin
// TODO - do we need to delete display or is it already done?
}
else { // image plus is not totally empty
ImageDisplay display = map.lookupDisplay(imp);
if (display == null) {
if (imp.getWindow() != null) {
display = map.registerLegacyImage(imp);
}
else {
continue;
}
}
else {
if (imp == currImp) {
// we harmonized this earlier
}
else harmonizer.updateDisplay(display, imp);
}
displays.add(display);
}
}
return displays;
}
private boolean isLegacyCompatible(final ImageDisplay display) {
if (display == null) return true;
final Dataset ds = imageDisplayService.getActiveDataset(display);
return LegacyUtils.dimensionsIJ1Compatible(ds);
}
private void notifyUser(String message) {
final IUserInterface ui = uiService.getUI();
final DialogPrompt dialog =
ui.dialogPrompt(message, "Error",
DialogPrompt.MessageType.INFORMATION_MESSAGE,
DialogPrompt.OptionType.DEFAULT_OPTION);
dialog.prompt();
}
// Finishes any in progress paste() operations. Done before harmonization.
// In IJ1 the paste operations are usually handled by ImageCanvas::paint().
// In IJ2 that method is never called. It would be nice to hook something
// that calls paint() via the legacy injector but that may raise additional
// problems. This is a simple fix.
private void finishInProgressPastes(
ImagePlus currImp, Set<ImagePlus> outputList)
{
endPaste(currImp);
for (final ImagePlus imp : outputList) { // potentially empty list
if (imp == currImp) continue;
endPaste(imp);
}
}
private void endPaste(ImagePlus imp) {
if (imp == null) return;
Roi roi = imp.getRoi();
if (roi == null) return;
if (roi.getPasteMode() == Roi.NOT_PASTING) return;
roi.endPaste();
}
} |
package com.infunity.isometricgame.core.view;
import com.badlogic.gdx.graphics.g2d.ParticleEffectPool;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.infunity.isometricgame.shared.intefaces.EffectsInterface;
public class EffectManager implements EffectsInterface {
private ParticleManager particleManager;
public EffectManager(ParticleManager particleManager) {
this.particleManager = particleManager;
}
@Override
public void createEffect(int x, int y, Effect effectType) {
if(effectType == Effect.COIN_EFFECT) {
ParticleEffectPool.PooledEffect prt = particleManager.obtainEffect(ParticleManager.COIN_EFFECT);
prt.setPosition(x, y);
particleManager.addEffect(prt);
} else {
throw new IllegalArgumentException("Unknown effectType");
}
}
public void update(float delta) {
particleManager.update(delta);
}
public void draw(SpriteBatch batch) {
particleManager.draw(batch);
}
} |
package com.leonemsolis.screens.fight_screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.leonemsolis.main.MainGameClass;
import com.leonemsolis.screens.blueprints.Object;
import com.leonemsolis.screens.blueprints.Renderer;
import com.leonemsolis.screens.fight_screen.objects.Enemy;
import com.leonemsolis.screens.fight_screen.objects.Hero;
import java.util.List;
public class FightRenderer extends Renderer {
private OrthographicCamera camera;
private BitmapFont blackFont;
private final Rectangle heroLabel, enemyLabel;
private Rectangle roundCounterLabel, enemyPoolLabel, heroPoolLabel;
private int roundCounter = 1;
private String heroTag, enemyTag;
private Hero hero;
private Enemy enemy;
// For text's size measure
private GlyphLayout layout;
public FightRenderer(List<Object> renderingObject) {
this.renderingObjects = renderingObject;
camera = new OrthographicCamera();
camera.setToOrtho(true, MainGameClass.GAME_WIDTH, MainGameClass.GAME_HEIGHT);
camera.update();
shape = new ShapeRenderer();
shape.setProjectionMatrix(camera.combined);
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.combined);
blackFont = new BitmapFont(true);
blackFont.setColor(Color.BLACK);
// Make font height about 20
blackFont.getData().setScale(1.272727f);
hero = ((Hero)renderingObject.get(0));
heroTag = hero.getTag();
enemy = ((Enemy)renderingObject.get(1));
enemyTag = enemy.getTag();
layout = new GlyphLayout();
layout.setText(blackFont, heroTag);
heroLabel = new Rectangle(10, 3, layout.width, layout.height);
layout.setText(blackFont, enemyTag);
enemyLabel = new Rectangle(MainGameClass.GAME_WIDTH - 10 - layout.width, 3, layout.width, layout.height);
layout.setText(blackFont, roundCounter+"");
roundCounterLabel = new Rectangle(MainGameClass.GAME_WIDTH / 2 - layout.width / 2, 3, layout.width, layout.height);
layout.setText(blackFont, "Pool: "+hero.getPool());
heroPoolLabel = new Rectangle(10, 49, layout.width, layout.height);
layout.setText(blackFont, "Pool: "+enemy.getPool());
enemyPoolLabel = new Rectangle(MainGameClass.GAME_WIDTH - 10 - layout.width, 49, layout.width, layout.height);
}
@Override
public void render(float delta) {
Gdx.gl20.glClearColor(0, 0, 0, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shape.begin(ShapeRenderer.ShapeType.Filled);
// Upper cover(beyond upper bound)
shape.setColor(Color.WHITE);
shape.rect(0, MainGameClass.MID_POINT - 400, MainGameClass.GAME_WIDTH, 480);
shape.setColor(Color.RED);
// Bottom cover
shape.rect(0, MainGameClass.MID_POINT + 80, MainGameClass.GAME_WIDTH, 200);
// Hero's HP bar (filler)
shape.rect(0, 23, (hero.getHP() * MainGameClass.GAME_WIDTH / 2) / 100, 23);
// Enemy's HP bar (filler)
shape.rect(MainGameClass.GAME_WIDTH / 2 + (MainGameClass.GAME_WIDTH / 2 - (enemy.getHP() * MainGameClass.GAME_WIDTH / 2) / 100), 23, MainGameClass.GAME_WIDTH, 23);
shape.end();
shape.begin(ShapeRenderer.ShapeType.Line);
shape.setColor(Color.BLACK);
// Hero's HP bar outline
shape.rect(0, 23, (hero.getHP() * MainGameClass.GAME_WIDTH / 2) / 100, 23);
// Enemy's HP bar outline
shape.rect(MainGameClass.GAME_WIDTH / 2 + (MainGameClass.GAME_WIDTH / 2 - (enemy.getHP() * MainGameClass.GAME_WIDTH / 2) / 100), 23, MainGameClass.GAME_WIDTH, 23);
shape.rect(MainGameClass.GAME_WIDTH / 2 - 20, 0, 40, 23);
shape.line(0, 23, MainGameClass.GAME_WIDTH, 23);
shape.line(0, 46, MainGameClass.GAME_WIDTH, 46);
shape.rect(MainGameClass.GAME_WIDTH / 2 - 1, 46, 2, 23);
shape.line(0, 69, MainGameClass.GAME_WIDTH, 69);
shape.end();
batch.begin();
blackFont.draw(batch, heroTag, heroLabel.x, heroLabel.y);
blackFont.draw(batch, enemyTag, enemyLabel.x, enemyLabel.y);
blackFont.draw(batch, roundCounter+"", roundCounterLabel.x, roundCounterLabel.y);
blackFont.draw(batch, "Pool: "+hero.getPool(), heroPoolLabel.x, heroPoolLabel.y);
blackFont.draw(batch, "Pool: "+enemy.getPool(), enemyPoolLabel.x, enemyPoolLabel.y);
batch.end();
}
public void nextRound() {
roundCounter++;
layout.setText(blackFont, roundCounter+"");
roundCounterLabel = new Rectangle(MainGameClass.GAME_WIDTH / 2 - layout.width / 2, 3, layout.width, layout.height);
}
} |
package com.leonemsolis.screens.fight_screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.leonemsolis.main.MainGameClass;
import com.leonemsolis.screens.blueprints.Renderer;
public class FightRenderer extends Renderer {
private OrthographicCamera camera;
private BitmapFont redFont;
private final Rectangle heroLabel, enemyLabel;
public FightRenderer() {
camera = new OrthographicCamera();
camera.setToOrtho(true, MainGameClass.GAME_WIDTH, MainGameClass.GAME_HEIGHT);
camera.update();
shape = new ShapeRenderer();
shape.setProjectionMatrix(camera.combined);
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.combined);
redFont = new BitmapFont(true);
redFont.setColor(Color.RED);
// Make font height about 20
redFont.getData().setScale(1.272727f);
GlyphLayout layout = new GlyphLayout();
layout.setText(redFont, "Hero");
heroLabel = new Rectangle(140 / 2 - layout.width / 2, 3, layout.width, layout.height);
layout.setText(redFont, "Enemy");
enemyLabel = new Rectangle(180 + 140 / 2 - layout.width / 2, 3, layout.width, layout.height);
Gdx.app.log("height", layout.height+"");
}
@Override
public void render(float delta) {
Gdx.gl20.glClearColor(0, 0, 0, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shape.begin(ShapeRenderer.ShapeType.Filled);
// With cover
shape.setColor(Color.WHITE);
shape.rect(0, MainGameClass.MID_POINT - 400, MainGameClass.GAME_WIDTH, 480);
shape.setColor(Color.RED);
shape.rect(0, MainGameClass.MID_POINT + 80, MainGameClass.GAME_WIDTH, 200);
shape.end();
batch.begin();
redFont.draw(batch, "Hero", heroLabel.x, heroLabel.y);
redFont.draw(batch, "Enemy", enemyLabel.x, enemyLabel.y);
batch.end();
}
} |
package io.zerodi.windbag.app;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Environment;
import io.zerodi.windbag.api.representations.ServerDetail;
import io.zerodi.windbag.api.resources.ServerConfigurationResource;
import io.zerodi.windbag.api.resources.ServerControlResource;
import io.zerodi.windbag.app.client.registery.ChannelRegistryImpl;
import io.zerodi.windbag.app.healthcheck.ServerDefinitionHealthCheck;
import java.util.List;
/**
* Main class, spinning the core application.
*
* @author zerodi
*/
public class ApplicationService extends Service<ApplicationConfiguration> {
public static void main(String[] args) throws Exception {
new ApplicationService().run(args);
}
@Override
public void initialize(Bootstrap<ApplicationConfiguration> bootstrap) {
bootstrap.setName("windbag");
bootstrap.getObjectMapperFactory().enable(SerializationFeature.WRAP_ROOT_VALUE);
}
@Override
public void run(ApplicationConfiguration configuration, Environment environment) throws Exception {
List<ServerDetail> defaultServers = configuration.getServers();
environment.addResource(ServerConfigurationResource.getInstance(defaultServers));
environment.addResource(ServerControlResource.getInstance());
ChannelRegistryImpl channelRegistryImpl = ChannelRegistryImpl.getInstance();
environment.manage(channelRegistryImpl);
environment.addHealthCheck(ServerDefinitionHealthCheck.getInstance(defaultServers));
}
} |
package org.javarosa.core.model.test;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.data.DateData;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.instance.test.DummyInstanceInitializationFactory;
import org.javarosa.core.model.utils.test.PersistableSandbox;
import org.javarosa.core.test.FormParseInit;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.test_utils.ExprEvalUtils;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import org.javarosa.xform.parse.XFormParser;
import static org.junit.Assert.*;
/**
* @author Phillip Mates (pmates@dimagi.com)
*/
public class FormDefTest {
/**
* Make sure that 'current()' expands correctly when used in conditionals
* such as in 'relevant' tags. The test answers a question and expects the
* correct elements to be re-evaluated and set to not relevant.
*/
@Test
public void testCurrentFuncInTriggers() {
FormParseInit fpi = new FormParseInit("/trigger_and_current_tests.xml");
FormEntryController fec = initFormEntry(fpi);
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null) {
continue;
}
// get the reference of question
TreeReference qRef = q.getBind().getReference();
// are we changing the value of /data/show?
if (qRef.toString().equals("/data/show")) {
int response = fec.answerQuestion(new StringData("no"));
if (response != FormEntryController.ANSWER_OK) {
fail("Bad response from fec.answerQuestion()");
}
} else if (q.getID() == 2) {
// check (sketchily) if the second question is shown, which
// shouldn't happen after answering "no" to the first, unless
// triggers aren't working properly.
fail("shouldn't be relevant after answering no before");
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
}
/**
* Make sure that relative references in <bind> elements are correctly
* contextualized.
*/
@Test
public void testRelativeRefInTriggers() {
FormParseInit fpi = new FormParseInit("/test_nested_preds_with_rel_refs.xml");
FormEntryController fec = fpi.getFormEntryController();
fec.jumpToIndex(FormIndex.createBeginningOfFormIndex());
FormDef fd = fpi.getFormDef();
// run initialization to ensure xforms-ready event and binds are
// triggered.
fd.initialize(true, new DummyInstanceInitializationFactory());
FormInstance instance = fd.getMainInstance();
String errorMsg;
errorMsg = ExprEvalUtils.expectedEval("/data/query-one", instance, null, "0", null);
assertTrue(errorMsg, "".equals(errorMsg));
boolean[] shouldBePresent = {true, true};
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null) {
continue;
}
if (q.getID() <= shouldBePresent.length && !shouldBePresent[q.getID() - 1]) {
fail("question with id " + q.getID() + " shouldn't be relevant");
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
}
@Test
public void testAnswerConstraint() {
FormParseInit fpi = new FormParseInit("/ImageSelectTester.xhtml");
FormEntryController fec = initFormEntry(fpi);
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null || q.getTextID() == null || "".equals(q.getTextID())) {
continue;
}
if (q.getTextID().equals("constraint-test")) {
int response = fec.answerQuestion(new IntegerData(13));
if (response == FormEntryController.ANSWER_CONSTRAINT_VIOLATED) {
fail("Answer Constraint test failed.");
} else if (response == FormEntryController.ANSWER_OK) {
break;
} else {
fail("Bad response from fec.answerQuestion()");
}
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
}
@Test
public void testAnswerConstraintOldText() {
IntegerData ans = new IntegerData(7);
FormParseInit fpi = new FormParseInit("/ImageSelectTester.xhtml");
FormEntryController fec = initFormEntry(fpi);
fec.setLanguage("English");
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null || q.getTextID() == null || "".equals(q.getTextID())) {
continue;
}
if (q.getTextID().equals("constraint-test")) {
int response = fec.answerQuestion(ans);
if (response == FormEntryController.ANSWER_CONSTRAINT_VIOLATED) {
if (!"Old Constraint".equals(fec.getModel().getQuestionPrompt().getConstraintText())) {
fail("Old constraint message not found, instead got: "
+ fec.getModel().getQuestionPrompt().getConstraintText());
}
} else if (response == FormEntryController.ANSWER_OK) {
fail("Should have constrained");
break;
}
}
if (q.getTextID().equals("constraint-test-2")) {
int response3 = fec.answerQuestion(new IntegerData(13));
if (response3 == FormEntryController.ANSWER_CONSTRAINT_VIOLATED) {
if (!"New Alert".equals(fec.getModel().getQuestionPrompt().getConstraintText())) {
fail("New constraint message not found, instead got: "
+ fec.getModel().getQuestionPrompt().getConstraintText());
}
} else if (response3 == FormEntryController.ANSWER_OK) {
fail("Should have constrained (2)");
break;
}
}
if (q.getTextID().equals("constraint-test-3")) {
int response4 = fec.answerQuestion(new IntegerData(13));
if (response4 == FormEntryController.ANSWER_CONSTRAINT_VIOLATED) {
if (!"The best QB of all time: Tom Brady".equals(fec.getModel().getQuestionPrompt().getConstraintText())) {
fail("New constraint message not found, instead got: "
+ fec.getModel().getQuestionPrompt().getConstraintText());
}
} else if (response4 == FormEntryController.ANSWER_OK) {
fail("Should have constrained (2)");
break;
}
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
}
/**
* Test setvalue expressions which have predicate references
*/
@Test
public void testSetValuePredicate() {
FormParseInit fpi = new FormParseInit("/test_setvalue_predicate.xml");
FormEntryController fec = initFormEntry(fpi);
boolean testPassed = false;
do {
if (fec.getModel().getEvent() != FormEntryController.EVENT_QUESTION) {
continue;
}
String text = fec.getModel().getQuestionPrompt().getQuestionText();
//check for our test
if (text.contains("Test") && text.contains("pass")) {
testPassed = true;
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
if (!testPassed) {
fail("Setvalue Predicate Target Test");
}
}
/**
* Test nested form repeat triggers and actions
*/
@Test
public void testNestedRepeatActions() throws Exception {
FormParseInit fpi = new FormParseInit("/xform_tests/test_looped_model_iteration.xml");
FormEntryController fec = initFormEntry(fpi);
stepThroughEntireForm(fec);
ExprEvalUtils.assertEqualsXpathEval("Nested repeats did not evaluate to the proper outcome",
30.0,
"/data/sum",
fpi.getFormDef().getEvaluationContext());
}
/**
* Test triggers fired from inserting a new repeat entry. Triggers fired
* during insert action don't need to be fired again when all triggers
* rooted by that repeat entry are fired.
*/
@Test
public void testRepeatInsertTriggering() throws Exception {
FormParseInit fpi =
new FormParseInit("/xform_tests/test_repeat_insert_duplicate_triggering.xml");
FormEntryController fec = initFormEntry(fpi);
stepThroughEntireForm(fec);
EvaluationContext evalCtx = fpi.getFormDef().getEvaluationContext();
// make sure the language isn't the default language, 'esperanto',
// which it is initially set to
ExprEvalUtils.assertEqualsXpathEval("Check language set correctly",
"en", "/data/iter/country[1]/language", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Check id attr set correctly",
"1", "/data/iter/country[2]/@id", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Check id node set correctly",
"1", "/data/iter/country[2]/id", evalCtx);
}
/**
* Tests:
* -Adding a timestamp attribute to a node in the model when the corresponding question's
* value is changed
* -Setting a default value for one question based on the answer to another
* -Deserialization of a FormDef
*/
@Test
public void testQuestionLevelActionsAndSerialization() throws Exception {
// Generate a normal version of the fpi
FormParseInit fpi =
new FormParseInit("/xform_tests/test_question_level_actions.xml");
// Then generate one from a deserialized version of the initial form def
FormDef fd = fpi.getFormDef();
PersistableSandbox sandbox = new PersistableSandbox();
byte[] serialized = sandbox.serialize(fd);
FormDef deserializedFormDef = sandbox.deserialize(serialized, FormDef.class);
FormParseInit fpiFromDeserialization = new FormParseInit(deserializedFormDef);
// First test normally
testQuestionLevelActions(fpi);
// Then test with the deserialized version (to test that FormDef serialization is working properly)
testQuestionLevelActions(fpiFromDeserialization);
}
public void testQuestionLevelActions(FormParseInit fpi)
throws Exception {
FormEntryController fec = initFormEntry(fpi);
EvaluationContext evalCtx = fpi.getFormDef().getEvaluationContext();
ExprEvalUtils.assertEqualsXpathEval(
"Test that xforms-ready event triggered the form-level setvalue action",
"default value", "/data/selection", evalCtx);
Calendar birthday = Calendar.getInstance();
birthday.set(1993, Calendar.MARCH, 26);
int questionIndex = 0;
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null) {
continue;
}
// Note this relies on the questions in the test xml file staying in the current order
if (questionIndex == 0) {
fec.answerQuestion(new StringData("Answer to text question"));
} else if (questionIndex == 1) {
fec.answerQuestion(new SelectOneData(new Selection("one")));
} else if (questionIndex == 2) {
fec.answerQuestion(new DateData(birthday.getTime()));
}
questionIndex++;
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
Object evalResult = ExprEvalUtils.xpathEval(evalCtx, "/data/text/@time");
assertTrue("Check that a timestamp was set for the text question",
evalResult instanceof Date);
evalResult = ExprEvalUtils.xpathEval(evalCtx, "/data/selection/@time");
assertTrue("Check that a timestamp was set for the selection question",
evalResult instanceof Date);
evalResult = ExprEvalUtils.xpathEval(evalCtx, "/data/birthday/@time");
assertTrue("Check that a timestamp was set for the date question",
evalResult instanceof Date);
long currentInMillis = Calendar.getInstance().getTimeInMillis();
long birthdayInMillis = birthday.getTimeInMillis();
long diff = currentInMillis - birthdayInMillis;
long MILLISECONDS_IN_A_YEAR = 31536000000L;
double expectedAge = (double) (diff / MILLISECONDS_IN_A_YEAR);
ExprEvalUtils.assertEqualsXpathEval("Check that a default value for the age question was " +
"set correctly based upon provided answer to birthday question",
expectedAge, "/data/age", evalCtx);
}
/**
* Tests trigger caching related to cascading relevancy calculations to children.
*/
@Test
public void testTriggerCaching() throws Exception {
// Running the form creates a few animals with weights that count down from the init_weight.
// Skips over a specified entry by setting it to irrelevant.
FormParseInit fpi = new FormParseInit("/xform_tests/test_trigger_caching.xml");
FormEntryController fec = initFormEntry(fpi);
stepThroughEntireForm(fec);
EvaluationContext evalCtx = fpi.getFormDef().getEvaluationContext();
ExprEvalUtils.assertEqualsXpathEval("Check max animal weight",
400.0, "/data/heaviest_animal_weight", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Check min animal",
100.0, "/data/lightest_animal_weight", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Ensure we skip over setting attr of irrelevant entry",
"", "/data/animals[/data/skip_weighing_nth_animal]/weight/@time", evalCtx);
Object weighTimeResult =
ExprEvalUtils.xpathEval(evalCtx,
"/data/animals[/data/skip_weighing_nth_animal - 1]/weight/@time");
if ("".equals(weighTimeResult) || "-1".equals(weighTimeResult)) {
fail("@time should be set for relevant animal weight.");
}
ExprEvalUtils.assertEqualsXpathEval("Assert genus skip value",
1.0, "/data/skip_genus_nth_animal", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Ensure genus at skip entry is irrelevant",
"", "/data/animals[1]/genus/species", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("Ensure genuse at non-skip entry has default value",
"default", "/data/animals[2]/genus/species", evalCtx);
ExprEvalUtils.assertEqualsXpathEval(
"Relevancy of skipped genus entry should be irrelevant to, due to the way it is calculated",
"", "/data/disabled_species", evalCtx);
}
/**
* Regressions around complex repeat behaviors
*/
@Test
public void testLoopedRepeatIndexFetches() throws Exception {
FormParseInit fpi = new FormParseInit("/xform_tests/test_looped_form_index_fetch.xml");
FormEntryController fec = initFormEntry(fpi);
fec.stepToNextEvent();
fec.stepToNextEvent();
fec.answerQuestion(new IntegerData(2));
while(fec.stepToNextEvent() != FormEntryController.EVENT_QUESTION);
fec.answerQuestion(new UncastData("yes"));
while(fec.stepToNextEvent() != FormEntryController.EVENT_QUESTION) ;
fec.getNextIndex(fec.getModel().getFormIndex(), true);
fec.answerQuestion(new IntegerData(2));
fec.getNextIndex(fec.getModel().getFormIndex(), true);
}
/**
* Android-level form save on complete used to run through all
* triggerables. Disabling this, for performance reasons, exposed a bug
* were triggerables that fire on repeat inserts and have expressions that
* reference future (to be inserted) repeat entries never get re-fired due
* to over contextualization. This has been fixed by generalizing the
* triggerable context where path predicates are present for intersecting
* references in the triggerable expression.
*/
@Test
public void testModelIterationLookahead() throws XPathSyntaxException {
FormParseInit fpi = new FormParseInit("/xform_tests/model_iteration_lookahead.xml");
FormEntryController fec = initFormEntry(fpi);
stepThroughEntireForm(fec);
EvaluationContext evalCtx = fpi.getFormDef().getEvaluationContext();
ExprEvalUtils.assertEqualsXpathEval("",
"20", "/data/myiterator/iterator[1]/target_value", evalCtx);
ExprEvalUtils.assertEqualsXpathEval("",
100.0, "/data/myiterator/iterator[1]/relevancy_depending_on_future", evalCtx);
}
/**
* Testing that two identical bind conditions, modulo the operator (=, <),
* are treated as distict entities. Regression test for an issue where
* `equals` method for binary conditions wasn't taking condition type
* (arith, bool, equality) into account.
*/
@Test
public void testSimilarBindConditionsAreDistinguished() throws Exception {
FormParseInit fpi =
new FormParseInit("/xform_tests/test_display_conditions_regression.xml");
FormEntryController fec = initFormEntry(fpi);
boolean visibleLabelWasPresent = false;
do {
QuestionDef q = fpi.getCurrentQuestion();
if (q == null || q.getTextID() == null || "".equals(q.getTextID())) {
continue;
}
if (q.getTextID().equals("visible-label")) {
visibleLabelWasPresent = true;
}
if (q.getTextID().equals("invisible-label")) {
fail("Label whose display condition should be false was showing");
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
if (!visibleLabelWasPresent) {
fail("Label whose display condition should be true was not showing");
}
}
// regression test for when we weren't decrementing multiplicities correctly when repeats were deleted
@Test
public void testDeleteRepeatMultiplicities() throws IOException {
FormParseInit fpi = new FormParseInit("/multiple_repeats.xml");
FormEntryController fec = initFormEntry(fpi, "en");
fec.stepToNextEvent();
fec.newRepeat();
fec.stepToNextEvent();
fec.answerQuestion(new StringData("First repeat, first iteration: question2"));
fec.stepToNextEvent();
fec.answerQuestion(new StringData("First repeat, first iteration: question3"));
fec.stepToNextEvent();
fec.newRepeat();
fec.stepToNextEvent();
fec.answerQuestion(new StringData("First repeat, second iteration: question2"));
fec.stepToNextEvent();
fec.answerQuestion(new StringData("First repeat, second iteration: question3"));
fec.stepToNextEvent();
fec.stepToNextEvent();
// moving from first repeat (question1) to second (question4)
fec.newRepeat();
fec.stepToNextEvent();
fec.answerQuestion(new StringData("Second repeat, first iteration: question5"));
fec.stepToNextEvent();
fec.answerQuestion(new StringData("Second repeat, first iteration: question6"));
fec.stepToNextEvent();
fec.newRepeat();
fec.stepToNextEvent();
fec.answerQuestion(new StringData("Second repeat, second iteration: question5"));
fec.stepToNextEvent();
fec.answerQuestion(new StringData("Second repeat, second iteration: question6"));
fec.stepToPreviousEvent();
fec.stepToPreviousEvent();
TreeElement root = fpi.getFormDef().getInstance().getRoot();
// confirm both groups have two iterations and second iteration is set
assertEquals(root.getChildMultiplicity("question4"), 2);
assertNotEquals(root.getChild("question4", 1), null);
assertEquals(root.getChildMultiplicity("question1"), 2);
assertNotEquals(root.getChild("question1", 1), null);
fec.deleteRepeat(0);
// Confirm that the deleted repeat is gone and its sibling's multiplicity reduced
assertEquals(root.getChildMultiplicity("question4"), 1);
assertEquals(root.getChild("question4", 1), null);
// Confirm that the other repeat is unchanged
assertEquals(root.getChildMultiplicity("question1"), 2);
assertNotEquals(root.getChild("question1", 1), null);
}
/**
* Regression: IText function in xpath was not properly using the current
* locale instead of the default
*/
@Test
public void testITextXPathFunction() throws XPathSyntaxException {
FormParseInit fpi = new FormParseInit("/xform_tests/itext_function.xml");
// init form with the 'new' locale instead of the default 'old' locale
FormEntryController fec = initFormEntry(fpi, "new");
boolean inlinePassed = false;
boolean nestedPassed = false;
do {
TreeReference currentRef = fec.getModel().getFormIndex().getReference();
if(currentRef == null) { continue; }
if(currentRef.genericize().toString().equals("/data/inline")) {
assertEquals("Inline IText Method Callout", "right",
fec.getModel().getCaptionPrompt().getQuestionText());
inlinePassed = true;
}
if(currentRef.genericize().toString().equals("/data/nested")) {
assertEquals("Nexted IText Method Callout", "right",
fec.getModel().getCaptionPrompt().getQuestionText());
nestedPassed = true;
}
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
if(!inlinePassed) {
Assert.fail("Inline itext callout did not occur");
}
if(!nestedPassed) {
Assert.fail("Nested itext callout did not occur");
}
EvaluationContext evalCtx = fpi.getFormDef().getEvaluationContext();
ExprEvalUtils.assertEqualsXpathEval("IText calculation contained the wrong value",
"right", "/data/calculation", evalCtx);
}
private static void stepThroughEntireForm(FormEntryController fec) {
do {
} while (fec.stepToNextEvent() != FormEntryController.EVENT_END_OF_FORM);
}
private static FormEntryController initFormEntry(FormParseInit fpi) {
return initFormEntry(fpi, null);
}
private static FormEntryController initFormEntry(FormParseInit fpi, String locale) {
FormEntryController fec = fpi.getFormEntryController();
fpi.getFormDef().initialize(true, null, locale);
fec.jumpToIndex(FormIndex.createBeginningOfFormIndex());
return fec;
}
} |
package eu.cloudopting.domain;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.validator.constraints.Email;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A user.
*/
@Entity
@Table(name = "T_USER")
public class User extends AbstractAuditingEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Pattern(regexp = "^[a-z0-9]*$")
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 5, max = 100)
@Column(length = 100)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(max = 100)
@Column(length = 100, unique = true)
private String email;
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 5)
@Column(name = "lang_key", length = 5)
private String langKey;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
private String resetKey;
@Temporal(TemporalType.DATE)
@Column(name = "reset_date", nullable = true)
private Date resetDate = null;
@ManyToOne
@JoinColumn(name = "organization_id", referencedColumnName = "id")
private Organizations organizationId;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "T_USER_AUTHORITY",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
private Set<Authority> authorities = new HashSet<>();
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
private Set<PersistentToken> persistentTokens = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Date getResetDate() {
return resetDate;
}
public void setResetDate(Date resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
public Set<PersistentToken> getPersistentTokens() {
return persistentTokens;
}
public void setPersistentTokens(Set<PersistentToken> persistentTokens) {
this.persistentTokens = persistentTokens;
}
public Organizations getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Organizations organizationId) {
this.organizationId = organizationId;
}
@JsonGetter("roles")
public List<String> getRoles(){
return getAuthorities().stream().map(Authority::getName).collect(Collectors.toList());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
if (!login.equals(user.login)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return login.hashCode();
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} |
package services.player;
import intents.GalacticIntent;
import intents.PlayerEventIntent;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import main.ProjectSWG;
import network.packets.Packet;
import network.packets.soe.SessionRequest;
import network.packets.swg.login.AccountFeatureBits;
import network.packets.swg.login.ClientIdMsg;
import network.packets.swg.login.ClientPermissionsMessage;
import network.packets.swg.login.ServerId;
import network.packets.swg.login.ServerString;
import network.packets.swg.login.creation.ClientVerifyAndLockNameRequest;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse;
import network.packets.swg.login.creation.ClientCreateCharacter;
import network.packets.swg.login.creation.ClientVerifyAndLockNameResponse.ErrorMessage;
import network.packets.swg.login.creation.CreateCharacterFailure;
import network.packets.swg.login.creation.CreateCharacterFailure.NameFailureReason;
import network.packets.swg.login.creation.CreateCharacterSuccess;
import network.packets.swg.login.creation.RandomNameRequest;
import network.packets.swg.login.creation.RandomNameResponse;
import network.packets.swg.zone.GalaxyLoopTimesRequest;
import network.packets.swg.zone.GalaxyLoopTimesResponse;
import network.packets.swg.zone.HeartBeatMessage;
import resources.Galaxy;
import resources.Location;
import resources.Race;
import resources.Terrain;
import resources.client_info.ClientFactory;
import resources.client_info.visitors.ProfTemplateData;
import resources.config.ConfigFile;
import resources.control.Service;
import resources.objects.creature.CreatureObject;
import resources.objects.player.PlayerObject;
import resources.objects.tangible.TangibleObject;
import resources.player.Player;
import resources.player.PlayerEvent;
import resources.services.Config;
import services.objects.ObjectManager;
import utilities.namegen.SWGNameGenerator;
public class ZoneService extends Service {
private SWGNameGenerator nameGenerator;
private Map <String, ProfTemplateData> profTemplates;
private ClientFactory clientFac;
private PreparedStatement createCharacter;
private PreparedStatement getCharacter;
public ZoneService() {
nameGenerator = new SWGNameGenerator();
clientFac = new ClientFactory();
}
@Override
public boolean initialize() {
String createCharacterSql = "INSERT INTO characters (id, name, race, userId, galaxyId) VALUES (?, ?, ?, ?, ?)";
createCharacter = getLocalDatabase().prepareStatement(createCharacterSql);
getCharacter = getLocalDatabase().prepareStatement("SELECT * FROM characters WHERE name = ?");
nameGenerator.loadAllRules();
loadProfTemplates();
return super.initialize();
}
public void handlePacket(GalacticIntent intent, Player player, long networkId, Packet p) {
if (p instanceof SessionRequest)
sendServerInfo(intent.getGalaxy(), networkId);
if (p instanceof ClientIdMsg)
handleClientIdMsg(player, (ClientIdMsg) p);
if (p instanceof RandomNameRequest)
handleRandomNameRequest(player, (RandomNameRequest) p);
if (p instanceof ClientVerifyAndLockNameRequest)
handleApproveNameRequest(intent.getPlayerManager(), player, (ClientVerifyAndLockNameRequest) p);
if (p instanceof ClientCreateCharacter)
handleCharCreation(intent.getObjectManager(), player, (ClientCreateCharacter) p);
if (p instanceof GalaxyLoopTimesRequest)
handleGalaxyLoopTimesRequest(player, (GalaxyLoopTimesRequest) p);
}
private void sendServerInfo(Galaxy galaxy, long networkId) {
Config c = getConfig(ConfigFile.PRIMARY);
String name = c.getString("ZONE-SERVER-NAME", galaxy.getName());
int id = c.getInt("ZONE-SERVER-ID", galaxy.getId());
sendPacket(networkId, new ServerString(name + ":" + id));
sendPacket(networkId, new ServerId(id));
}
private void handleClientIdMsg(Player player, ClientIdMsg clientId) {
System.out.println(player.getUsername() + " has connected to the zone server.");
sendPacket(player.getNetworkId(), new HeartBeatMessage());
sendPacket(player.getNetworkId(), new AccountFeatureBits());
sendPacket(player.getNetworkId(), new ClientPermissionsMessage());
}
private void handleRandomNameRequest(Player player, RandomNameRequest request) {
RandomNameResponse response = new RandomNameResponse(request.getRace(), "");
String race = Race.getRaceByFile(request.getRace()).getSpecies();
response.setRandomName(nameGenerator.generateRandomName(race));
sendPacket(player.getNetworkId(), response);
}
private void handleApproveNameRequest(PlayerManager playerMgr, Player player, ClientVerifyAndLockNameRequest request) {
// TODO: Lore reserved name checks
if (!characterExistsForName(request.getName()))
sendPacket(player.getNetworkId(), new ClientVerifyAndLockNameResponse(request.getName(), ErrorMessage.NAME_APPROVED));
else
sendPacket(player.getNetworkId(), new ClientVerifyAndLockNameResponse(request.getName(), ErrorMessage.NAME_DECLINED_IN_USE));
}
private void handleCharCreation(ObjectManager objManager, Player player, ClientCreateCharacter create) {
System.out.println("Create Character: " + create.getName());
long characterId = createCharacter(objManager, player, create);
if (createCharacterInDb(characterId, create.getName(), player)) {
sendPacket(player, new CreateCharacterSuccess(characterId));
new PlayerEventIntent(player, PlayerEvent.PE_CREATE_CHARACTER).broadcast();
} else {
System.err.println("ZoneService: Unable to create character and put into database!");
sendPacket(player, new CreateCharacterFailure(NameFailureReason.NAME_RETRY));
}
}
private boolean createCharacterInDb(long characterId, String name, Player player) {
if (characterExistsForName(name))
return false;
synchronized (createCharacter) {
try {
createCharacter.setLong(1, characterId);
createCharacter.setString(2, name);
createCharacter.setString(3, ((CreatureObject)player.getCreatureObject()).getRace().getFilename());
createCharacter.setInt(4, player.getUserId());
createCharacter.setInt(5, player.getGalaxyId());
return createCharacter.executeUpdate() == 1;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
private boolean characterExistsForName(String name) {
synchronized (getCharacter) {
try {
getCharacter.setString(1, name);
return getCharacter.executeQuery().next();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
private long createCharacter(ObjectManager objManager, Player player, ClientCreateCharacter create) {
Location start = getStartLocation(create.getStart());
Race race = Race.getRaceByFile(create.getRace());
CreatureObject creatureObj = (CreatureObject) objManager.createObject(race.getFilename());
PlayerObject playerObj = (PlayerObject) objManager.createObject("object/player/shared_player.iff");
setCreatureObjectValues(objManager, creatureObj, create);
setPlayerObjectValues(playerObj, create);
createHair(objManager, creatureObj, create.getHair(), create.getHairCustomization());
createStarterClothing(objManager, creatureObj, create.getRace(), create.getClothes());
creatureObj.setVolume(0x000F4240);
creatureObj.setLocation(start);
creatureObj.setOwner(player);
creatureObj.setSlot("ghost", playerObj);
playerObj.setTag(player.getAccessLevel());
player.setCreatureObject(creatureObj);
return creatureObj.getObjectId();
}
private void createHair(ObjectManager objManager, CreatureObject creatureObj, String hair, byte [] customization) {
if (hair.isEmpty())
return;
TangibleObject hairObj = (TangibleObject) objManager.createObject(ClientFactory.formatToSharedFile(hair));
hairObj.setAppearanceData(customization);
creatureObj.setSlot("hair", hairObj);
creatureObj.addEquipment(hairObj);
}
private void setCreatureObjectValues(ObjectManager objManager, CreatureObject creatureObj, ClientCreateCharacter create) {
TangibleObject inventory = (TangibleObject) objManager.createObject("object/tangible/inventory/shared_character_inventory.iff");
TangibleObject datapad = (TangibleObject) objManager.createObject("object/tangible/datapad/shared_character_datapad.iff");
creatureObj.setRace(Race.getRaceByFile(create.getRace()));
creatureObj.setAppearanceData(create.getCharCustomization());
creatureObj.setHeight(create.getHeight());
creatureObj.setName(create.getName());
creatureObj.setPvpType(20);
creatureObj.getSkills().add("species_" + creatureObj.getRace().getSpecies());
creatureObj.setSlot("inventory", inventory);
creatureObj.setSlot("datapad", datapad);
creatureObj.addEquipment(inventory);
creatureObj.addEquipment(datapad);
}
private void setPlayerObjectValues(PlayerObject playerObj, ClientCreateCharacter create) {
playerObj.setProfession(create.getProfession());
Calendar date = Calendar.getInstance();
playerObj.setBornDate(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}
private void handleGalaxyLoopTimesRequest(Player player, GalaxyLoopTimesRequest req) {
sendPacket(player, new GalaxyLoopTimesResponse(ProjectSWG.getCoreTime()/1000));
}
private void createStarterClothing(ObjectManager objManager, CreatureObject player, String race, String profession) {
if (player.getSlottedObject("inventory") == null)
return;
for (String template : profTemplates.get(profession).getItems(ClientFactory.formatToSharedFile(race))) {
TangibleObject clothing = (TangibleObject) objManager.createObject(template);
player.addChild(clothing);
}
}
private void loadProfTemplates() {
profTemplates = new ConcurrentHashMap<String, ProfTemplateData>();
profTemplates.put("crafting_artisan", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_brawler.iff"));
profTemplates.put("combat_brawler", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_brawler.iff"));
profTemplates.put("social_entertainer", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_social_entertainer.iff"));
profTemplates.put("combat_marksman", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_combat_marksman.iff"));
profTemplates.put("science_medic", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_science_medic.iff"));
profTemplates.put("outdoors_scout", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_outdoors_scout.iff"));
profTemplates.put("jedi", (ProfTemplateData) clientFac.getInfoFromFile("creation/profession_defaults_jedi.iff"));
}
private Location getStartLocation(String start) {
Location location = new Location();
location.setTerrain(Terrain.TATOOINE);
location.setX(3525 + (Math.random()-.5) * 5);
location.setY(4);
location.setZ(-4807 + (Math.random()-.5) * 5);
location.setOrientationX(0);
location.setOrientationY(0);
location.setOrientationZ(0);
location.setOrientationW(1);
return location;
}
} |
package nl.mpi.kinnate.kintypestrings;
import javax.xml.bind.annotation.XmlAttribute;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.DataTypes.RelationType;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityData.SymbolType;
import nl.mpi.kinnate.kindata.EntityRelation;
public class KinType {
private KinType() {
}
private KinType(String codeStringLocal, DataTypes.RelationType relationTypeLocal, EntityData.SymbolType symbolTypeLocal, String displayStringLocal) {
codeString = codeStringLocal;
relationType = relationTypeLocal;
symbolType = symbolTypeLocal;
displayString = displayStringLocal;
}
@XmlAttribute(name = "code", namespace = "http://mpi.nl/tla/kin")
protected String codeString = null;
@XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin")
protected DataTypes.RelationType relationType = null;
@XmlAttribute(name = "symbol", namespace = "http://mpi.nl/tla/kin")
protected EntityData.SymbolType symbolType = null;
@XmlAttribute(name = "name", namespace = "http://mpi.nl/tla/kin")
protected String displayString = null;
public String getCodeString() {
return codeString;
}
public String getDisplayString() {
return displayString;
}
public RelationType getRelationType() {
return relationType;
}
public SymbolType getSymbolType() {
return symbolType;
}
public boolean isEgoType() {
// todo: this could be better handled by adding a boolean: isego to each KinType
return codeString.contains("E");
}
public boolean matchesRelation(EntityRelation entityRelation, String kinTypeModifier) {
// todo: make use of the kin type modifier
if (entityRelation.getAlterNode().isEgo != this.isEgoType()) {
return false;
}
if (relationType != null && !relationType.equals(entityRelation.relationType)) {
return false;
}
if (symbolType == null || symbolType == EntityData.SymbolType.square) {
return true; // it is better to return all the relations regardless of symbol in this case
// if the symbol is square then either circle or triangle are matches (square is matched later)
// if (EntityData.SymbolType.circle.name().equals(entityRelation.getAlterNode().getSymbolType())) {
// return true;
// if (EntityData.SymbolType.triangle.name().equals(entityRelation.getAlterNode().getSymbolType())) {
// return true;
}
if (!symbolType.name().equals(entityRelation.getAlterNode().getSymbolType())) {
return false;
}
return true;
}
public boolean matchesEgoEntity(EntityData entityData, String kinTypeModifier) {
// todo make use of the kin type modifier or remove it if it proves irelevant
if (!entityData.isEgo || !this.isEgoType()) {
return false;
}
if (symbolType == EntityData.SymbolType.square) {
return true; // it is better to return all the relations regardless of symbol in this case
// if the symbol is square then either circle or triangle are matches (square is matched later)
// if (EntityData.SymbolType.circle.name().equals(entityData.getSymbolType())) {
// return true;
// if (EntityData.SymbolType.triangle.name().equals(entityData.getSymbolType())) {
// return true;
}
if (!symbolType.name().equals(entityData.getSymbolType())) {
return false;
}
return true;
}
public static KinType[] getReferenceKinTypes() {
return referenceKinTypes;
}
protected static KinType[] referenceKinTypes = new KinType[]{
// other types
// todo: the gendered ego kin types Em and Ef are probably not correct and should be verified
new KinType("Ef", DataTypes.RelationType.none, EntityData.SymbolType.circle, "Ego Female"),
new KinType("Em", DataTypes.RelationType.none, EntityData.SymbolType.triangle, "Ego Male"),
// type 1
new KinType("Fa", DataTypes.RelationType.ancestor, EntityData.SymbolType.triangle, "Father"),
new KinType("Mo", DataTypes.RelationType.ancestor, EntityData.SymbolType.circle, "Mother"),
new KinType("Br", DataTypes.RelationType.sibling, EntityData.SymbolType.triangle, "Brother"),
new KinType("Si", DataTypes.RelationType.sibling, EntityData.SymbolType.circle, "Sister"),
new KinType("So", DataTypes.RelationType.descendant, EntityData.SymbolType.triangle, "Son"),
new KinType("Da", DataTypes.RelationType.descendant, EntityData.SymbolType.circle, "Daughter"),
new KinType("Hu", DataTypes.RelationType.union, EntityData.SymbolType.triangle, "Husband"),
new KinType("Wi", DataTypes.RelationType.union, EntityData.SymbolType.circle, "Wife"),
new KinType("Pa", DataTypes.RelationType.ancestor, EntityData.SymbolType.square, "Parent"),
new KinType("Sb", DataTypes.RelationType.sibling, EntityData.SymbolType.square, "Sibling"), //todo: are Sp and Sb correct?
new KinType("Sp", DataTypes.RelationType.union, EntityData.SymbolType.square, "Spouse"),
new KinType("Ch", DataTypes.RelationType.descendant, EntityData.SymbolType.square, "Child"),
// type 2
new KinType("F", DataTypes.RelationType.ancestor, EntityData.SymbolType.triangle, "Father"),
new KinType("M", DataTypes.RelationType.ancestor, EntityData.SymbolType.circle, "Mother"),
new KinType("B", DataTypes.RelationType.sibling, EntityData.SymbolType.triangle, "Brother"),
new KinType("Z", DataTypes.RelationType.sibling, EntityData.SymbolType.circle, "Sister"),
new KinType("S", DataTypes.RelationType.descendant, EntityData.SymbolType.triangle, "Son"),
new KinType("D", DataTypes.RelationType.descendant, EntityData.SymbolType.circle, "Daughter"),
new KinType("H", DataTypes.RelationType.union, EntityData.SymbolType.triangle, "Husband"),
new KinType("W", DataTypes.RelationType.union, EntityData.SymbolType.circle, "Wife"),
new KinType("P", DataTypes.RelationType.ancestor, EntityData.SymbolType.square, "Parent"),
new KinType("G", DataTypes.RelationType.sibling, EntityData.SymbolType.square, "Sibling"),
new KinType("E", DataTypes.RelationType.none, EntityData.SymbolType.square, "Ego"),
new KinType("C", DataTypes.RelationType.descendant, EntityData.SymbolType.square, "Child"),
// new KinType("X", DataTypes.RelationType.none, EntityData.SymbolType.none) // X is intended to indicate unknown or no type, for instance this is used after import to add all nodes to the graph
// non ego types to be used to start a kin type string but cannot be used except at the beginning
new KinType("m", DataTypes.RelationType.none, EntityData.SymbolType.triangle, "Male"),
new KinType("f", DataTypes.RelationType.none, EntityData.SymbolType.circle, "Female"),
new KinType("x", DataTypes.RelationType.none, EntityData.SymbolType.square, "Undefined"),
new KinType("*", null, null, "Any Relation"),};
} |
package nl.mpi.kinnate.kintypestrings;
import javax.xml.bind.annotation.XmlAttribute;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.DataTypes.RelationType;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityData.SymbolType;
import nl.mpi.kinnate.kindata.EntityRelation;
public class KinType {
private KinType() {
}
private KinType(String codeStringLocal, DataTypes.RelationType relationTypeLocal, EntityData.SymbolType symbolTypeLocal, String displayStringLocal) {
codeString = codeStringLocal;
relationType = relationTypeLocal;
symbolType = symbolTypeLocal;
displayString = displayStringLocal;
}
@XmlAttribute(name = "code", namespace = "http://mpi.nl/tla/kin")
protected String codeString = null;
@XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin")
protected DataTypes.RelationType relationType = null;
@XmlAttribute(name = "symbol", namespace = "http://mpi.nl/tla/kin")
protected EntityData.SymbolType symbolType = null;
@XmlAttribute(name = "name", namespace = "http://mpi.nl/tla/kin")
protected String displayString = null;
public String getCodeString() {
return codeString;
}
public String getDisplayString() {
return displayString;
}
public RelationType getRelationType() {
return relationType;
}
public SymbolType getSymbolType() {
return symbolType;
}
public boolean isEgoType() {
// todo: this could be better handled by adding a boolean: isego to each KinType
return codeString.contains("E");
}
public boolean matchesRelation(EntityRelation entityRelation, String kinTypeModifier) {
// todo: make use of the kin type modifier
if (entityRelation.getAlterNode().isEgo != this.isEgoType()) {
return false;
}
if (relationType != null && !relationType.equals(entityRelation.relationType)) {
return false;
}
if (symbolType == null || symbolType == EntityData.SymbolType.square) {
return true; // it is better to return all the relations regardless of symbol in this case
// if the symbol is square then either circle or triangle are matches (square is matched later)
// if (EntityData.SymbolType.circle.name().equals(entityRelation.getAlterNode().getSymbolType())) {
// return true;
// if (EntityData.SymbolType.triangle.name().equals(entityRelation.getAlterNode().getSymbolType())) {
// return true;
}
if (!symbolType.name().equals(entityRelation.getAlterNode().getSymbolType())) {
return false;
}
return true;
}
public boolean matchesEgoEntity(EntityData entityData, String kinTypeModifier) {
// todo make use of the kin type modifier or remove it if it proves irelevant
if (!entityData.isEgo || !this.isEgoType()) {
return false;
}
if (symbolType == EntityData.SymbolType.square) {
return true; // it is better to return all the relations regardless of symbol in this case
// if the symbol is square then either circle or triangle are matches (square is matched later)
// if (EntityData.SymbolType.circle.name().equals(entityData.getSymbolType())) {
// return true;
// if (EntityData.SymbolType.triangle.name().equals(entityData.getSymbolType())) {
// return true;
}
if (!symbolType.name().equals(entityData.getSymbolType())) {
return false;
}
return true;
}
public static KinType[] getReferenceKinTypes() {
return referenceKinTypes;
}
private static KinType[] referenceKinTypes = new KinType[]{
// other types
// todo: the gendered ego kin types Em and Ef are probably not correct and should be verified
new KinType("Ef", DataTypes.RelationType.none, EntityData.SymbolType.circle, "Ego Female"),
new KinType("Em", DataTypes.RelationType.none, EntityData.SymbolType.triangle, "Ego Male"),
// type 1
new KinType("Fa", DataTypes.RelationType.ancestor, EntityData.SymbolType.triangle, "Father"),
new KinType("Mo", DataTypes.RelationType.ancestor, EntityData.SymbolType.circle, "Mother"),
new KinType("Br", DataTypes.RelationType.sibling, EntityData.SymbolType.triangle, "Brother"),
new KinType("Si", DataTypes.RelationType.sibling, EntityData.SymbolType.circle, "Sister"),
new KinType("So", DataTypes.RelationType.descendant, EntityData.SymbolType.triangle, "Son"),
new KinType("Da", DataTypes.RelationType.descendant, EntityData.SymbolType.circle, "Daughter"),
new KinType("Hu", DataTypes.RelationType.union, EntityData.SymbolType.triangle, "Husband"),
new KinType("Wi", DataTypes.RelationType.union, EntityData.SymbolType.circle, "Wife"),
new KinType("Pa", DataTypes.RelationType.ancestor, EntityData.SymbolType.square, "Parent"),
new KinType("Sb", DataTypes.RelationType.sibling, EntityData.SymbolType.square, "Sibling"), //todo: are Sp and Sb correct?
new KinType("Sp", DataTypes.RelationType.union, EntityData.SymbolType.square, "Spouse"),
new KinType("Ch", DataTypes.RelationType.descendant, EntityData.SymbolType.square, "Child"),
// type 2
new KinType("F", DataTypes.RelationType.ancestor, EntityData.SymbolType.triangle, "Father"),
new KinType("M", DataTypes.RelationType.ancestor, EntityData.SymbolType.circle, "Mother"),
new KinType("B", DataTypes.RelationType.sibling, EntityData.SymbolType.triangle, "Brother"),
new KinType("Z", DataTypes.RelationType.sibling, EntityData.SymbolType.circle, "Sister"),
new KinType("S", DataTypes.RelationType.descendant, EntityData.SymbolType.triangle, "Son"),
new KinType("D", DataTypes.RelationType.descendant, EntityData.SymbolType.circle, "Daughter"),
new KinType("H", DataTypes.RelationType.union, EntityData.SymbolType.triangle, "Husband"),
new KinType("W", DataTypes.RelationType.union, EntityData.SymbolType.circle, "Wife"),
new KinType("P", DataTypes.RelationType.ancestor, EntityData.SymbolType.square, "Parent"),
new KinType("G", DataTypes.RelationType.sibling, EntityData.SymbolType.square, "Sibling"),
new KinType("E", DataTypes.RelationType.none, EntityData.SymbolType.square, "Ego"),
new KinType("C", DataTypes.RelationType.descendant, EntityData.SymbolType.square, "Child"),
// new KinType("X", DataTypes.RelationType.none, EntityData.SymbolType.none) // X is intended to indicate unknown or no type, for instance this is used after import to add all nodes to the graph
// non ego types to be used to start a kin type string but cannot be used except at the beginning
new KinType("m", DataTypes.RelationType.none, EntityData.SymbolType.triangle, "Male"),
new KinType("f", DataTypes.RelationType.none, EntityData.SymbolType.circle, "Female"),
new KinType("x", DataTypes.RelationType.none, EntityData.SymbolType.square, "Undefined"),
new KinType("*", null, null, "Any Relation"),};
} |
package common;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.Ignore;
import de.ust.skill.common.java.api.Access;
import de.ust.skill.common.java.api.FieldDeclaration;
import de.ust.skill.common.java.api.FieldType;
import de.ust.skill.common.java.api.GeneralAccess;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.api.SkillFile;
import de.ust.skill.common.java.internal.SkillObject;
import de.ust.skill.common.java.internal.fieldDeclarations.AutoField;
import de.ust.skill.common.java.internal.fieldDeclarations.InterfaceField;
import de.ust.skill.common.java.internal.fieldTypes.ConstantIntegerType;
import de.ust.skill.common.java.internal.fieldTypes.ConstantLengthArray;
import de.ust.skill.common.java.internal.fieldTypes.SingleArgumentType;
/**
* Some test code commonly used by all tests.
*
* @author Timm Felden
*/
@Ignore
abstract public class CommonTest {
/**
* This constant is used to guide reflective init
*/
private static final int reflectiveInitSize = 10;
public CommonTest() {
super();
}
/**
* TODO move to common tests
*/
protected static Path tmpFile(String string) throws Exception {
File r = File.createTempFile(string, ".sf");
// r.deleteOnExit();
return r.toPath();
}
/**
* TODO move to common tests
*/
protected final static String sha256(String name) throws Exception {
return sha256(new File("src/test/resources/" + name).toPath());
}
/**
* TODO move to common tests
*/
protected final static String sha256(Path path) throws Exception {
byte[] bytes = Files.readAllBytes(path);
StringBuilder sb = new StringBuilder();
for (byte b : MessageDigest.getInstance("SHA-256").digest(bytes))
sb.append(String.format("%02X", b));
return sb.toString();
}
protected static void reflectiveInit(SkillFile sf) {
// create instances
sf.allTypesStream().parallel().forEach(t -> {
try {
for (int i = reflectiveInitSize; i != 0; i
t.make();
} catch (@SuppressWarnings("unused") SkillException e) {
// the type can not have more instances
}
});
// set fields
sf.allTypesStream().parallel().forEach(t -> {
for (SkillObject o : t) {
Iterator<? extends FieldDeclaration<?>> it = t.fields();
while (it.hasNext()) {
final FieldDeclaration<?> f = it.next();
if (!(f instanceof AutoField) && !(f.type() instanceof ConstantIntegerType<?>)
&& !(f instanceof InterfaceField))
set(sf, o, f);
}
}
});
}
private static <T, Obj extends SkillObject> void set(SkillFile sf, Obj o, FieldDeclaration<T> f) {
T v = value(sf, f.type());
// System.out.printf("%s#%d.%s = %s\n", o.getClass().getName(),
// o.getSkillID(), f.name(), v.toString());
o.set(f, v);
}
/**
* unchecked, because the insane amount of casts is necessary to reflect the
* implicit value based type system
*/
@SuppressWarnings("unchecked")
private static <T> T value(SkillFile sf, FieldType<T> type) {
if (type instanceof GeneralAccess<?>) {
// get a random object
Iterator<T> is = (Iterator<T>) ((GeneralAccess<?>) type).iterator();
for (int i = ThreadLocalRandom.current().nextInt(reflectiveInitSize) % 200; i != 0; i
is.next();
return is.next();
}
switch (type.typeID()) {
case 5:
// random type
Iterator<? extends Access<? extends SkillObject>> ts = sf.allTypes().iterator();
Access<? extends SkillObject> t = ts.next();
for (int i = ThreadLocalRandom.current().nextInt(200); i != 0 && ts.hasNext(); i
t = ts.next();
// random object
Iterator<? extends SkillObject> is = t.iterator();
for (int i = ThreadLocalRandom.current().nextInt(Math.min(200, reflectiveInitSize)); i != 0; i
is.next();
return (T) is.next();
case 6:
return (T) (Boolean) ThreadLocalRandom.current().nextBoolean();
case 7:
return (T) (Byte) (byte) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 8:
return (T) (Short) (short) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 9:
return (T) (Integer) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 10:
case 11:
return (T) (Long) (ThreadLocalRandom.current().nextLong() % reflectiveInitSize);
case 12:
return (T) (Float) ThreadLocalRandom.current().nextFloat();
case 13:
return (T) (Double) ThreadLocalRandom.current().nextDouble();
case 14:
return (T) "";
case 15: {
ConstantLengthArray<T> cla = (ConstantLengthArray<T>) type;
ArrayList<Object> rval = new ArrayList<>((int) cla.length);
for (int i = (int) cla.length; i != 0; i
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 17: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
ArrayList<Object> rval = new ArrayList<>(length);
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 18: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
LinkedList<Object> rval = new LinkedList<>();
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 19: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
HashSet<Object> rval = new HashSet<>();
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 20:
return (T) new HashMap<Object, Object>();
default:
throw new IllegalStateException();
}
}
protected static <T, U> de.ust.skill.common.java.api.FieldDeclaration<T> cast(de.ust.skill.common.java.api.FieldDeclaration<U> arg){
return (de.ust.skill.common.java.api.FieldDeclaration<T>)arg;
}
} |
package code;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebView;
import shape.*;
import java.net.URL;
import java.util.ResourceBundle;
public class MainWindow implements Initializable{
public AnchorPane canwrap, fracDimensionWrap;
public Canvas canvas;
public WebView webView;
private GraphicsContext gContext;
private FractalShape selectedShape;
@FXML
private ListView<String> listView;
private ObservableList<String> listViewData = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
//Init Canvas
canvas = new Canvas();
gContext = canvas.getGraphicsContext2D();
canwrap.getChildren().add(canvas);
//Init Fractal dimension WebView
webView = new WebView();
fracDimensionWrap.getChildren().add(webView);
//Init Fractal shapes list
listViewData.add("Horizontal Circles");
listViewData.add("Horizontal and Vertical Circles");
listViewData.add("Sierpinski Triangle");
listViewData.add("Sierpinski Carpet");
listViewData.add("Cantor Set");
listViewData.add("Koch Curve");
listViewData.add("Koch Curve (Quadratic_1)");
listViewData.add("Koch Curve (Quadratic_2)");
listViewData.add("Dragon Curve");
listViewData.add("Twin Dragon Curve");
listViewData.add("Levy C curve");
listViewData.add("Koch Snowflake");
listViewData.add("Koch Anti Snowflake");
listViewData.add("Koch Coastline");
listViewData.add("Mandelbrot Set");
listViewData.add("Tree");
listViewData.add("Tree 60 degree");
listViewData.add("Tree 90 degree");
listViewData.add("Pythagoras tree");
listViewData.add("Hilbert Curve");
listViewData.add("TSquare");
listViewData.add("Hexaflake");
listView.setItems(listViewData);
listView.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent arg0) {
resetCanvas();
resizeCanvas();
selectedShape = createFractalObject(getCurrentSelection());
}
});
}
public void resizeCanvas(){
canvas.setWidth(canwrap.getWidth());
canvas.setHeight(canwrap.getHeight());
}
public void resetCanvas(){
gContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
if(selectedShape != null) selectedShape = null;
webView.getEngine().loadContent(FractalShape.emptyFractalDimension);
}
@FXML
public void drawNextDepthLevel(){
if(selectedShape != null){
resizeCanvas();
selectedShape.drawNextDepthLevel();
}
else{
System.out.println("Please select SHAPE from the list first!!!");
}
}
@FXML
public void drawPrevDepthLevel(){
if(selectedShape != null){
resizeCanvas();
selectedShape.drawPrevDepthLevel();
}
else{
System.out.println("Please select SHAPE from the list first!!!");
}
}
FractalShape createFractalObject(String strShape){
switch (strShape){
case "Horizontal Circles":
return new HorizontalCircles(9, canvas, webView);
case "Sierpinski Triangle":
return new SierpinskiTriangle(8, canvas, webView);
case "Sierpinski Carpet":
return new SierpinskiCarpet(6, canvas, webView);
case "Cantor Set":
return new CantorSet(7, canvas, webView);
case "Horizontal and Vertical Circles":
return new HorizontalAndVerticalCircles(8, canvas, webView);
case "Koch Curve":
return new KochCurve(6, canvas, webView);
case "Koch Curve (Quadratic_1)":
return new KochCurveQuadratic1(8, canvas, webView);
case "Koch Curve (Quadratic_2)":
return new KochCurveQuadratic2(6, canvas, webView);
case "Dragon Curve":
return new DragonCurve(18, canvas, webView, "single", "dragon");
case "Twin Dragon Curve":
return new DragonCurve(18, canvas, webView, "double", "dragon");
case "Levy C curve":
return new DragonCurve(18, canvas, webView, "single", "cCurve");
case "Koch Snowflake":
return new KochSnowFlake(9, canvas, webView, "snowflake");
case "Koch Anti Snowflake":
return new KochSnowFlake(10, canvas, webView, "antisnowflake");
case "Koch Coastline":
return new KochCoastline(9, canvas, webView);
case "Mandelbrot Set":
return new MandelbrotSet(7, canvas, webView);
case "Tree":
return new Tree(10, canvas, webView, 15, 37, .65);
case "Tree 60 degree":
return new Tree(10, canvas, webView, 0, 60, .50);
case "Tree 90 degree":
return new Tree(10, canvas, webView, 0, 90, .50);
case "Pythagoras tree":
return new PythagorasTree(14, canvas, webView);
case "Hilbert Curve":
return new HilbertCurve(10, canvas, webView);
case "TSquare":
return new TSquare(11, canvas, webView);
case "Hexaflake":
return new Hexaflake(6, canvas, webView);
default:
System.out.println("Selected shape doesn't exist in list !!!");
return null;
}
}
private String getCurrentSelection(){
return listView.getSelectionModel().getSelectedItem();
}
public void OpenAboutPage(){
System.out.println("Opening about page");
About.display();
}
} |
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
public class RequestFromUIControllerToGetaResource extends RequestFromUIController implements Runnable
{
/**
*
* Miguel Velez
* April 29, 2015
*
* This class is a request from ui controller to get a resource
*
* Class variables:
*
* boolean[] responses;
* the part numbers that correspond to responses of this request
*
* Constructors:
*
* public RequestFromUIControllerToGetaResource(ID id)
* create a request to find resources from peers
*
* Methods:
*
* public void updateRequest(UDPMessage udpMessage);
* update the request
*
* public void run()
* Process packets from the UI and community
*
* public Thread startAsThread()
* Start this class as a thread
*
*
* Modification History:
*
* May 7, 2015
* Original version.
*
* May 13, 2015
* Implemented getting a part number and sending to UI.
*
* May 14, 2015
* Using a thread to synchronize the sending and receiving.
*
*/
private boolean[] responses;
private ID resourceID;
public RequestFromUIControllerToGetaResource(ID id, ID resourceId, InetSocketAddress uiController, OutgoingPacketQueue outgoingPacket, int numberOfParts)
{
// Create a request to find resources from peers
// Call the super constructor
super(id, uiController, outgoingPacket);
this.resourceID = resourceId;
this.responses = new boolean[numberOfParts];
// System.out.println(this.responses.length);
}
@Override
public void updateRequest(UDPMessage udpMessage)
{
// Send the datagram packet to the UI controller
// Check if null
if(udpMessage == null)
{
throw new IllegalArgumentException("The UDP message that you provided is null");
}
// Get the request part
byte[] partRequested = new byte[PartNumbers.getLengthInBytes()];
System.arraycopy(udpMessage.getMessage(), ID.getLengthInBytes(), partRequested, 0, PartNumbers.getLengthInBytes());
// System.out.println(partRequested[0] + " - " + partRequested[1] + " - " + partRequested[2] + " - " + partRequested[3]);
// Get the integer representation of the part
int partNumberRequested = ByteBuffer.wrap(partRequested).getInt();
// // Get an int from a byte array
// for(int i = 0; i < PartNumbers.getLengthInBytes(); i++) {
// partNumberRequested = partNumberRequested | ((partRequested[i] & 0xFF) << ((PartNumbers.getLengthInBytes() - 1 - i) * 8));
// System.out.println("Part requested: " + partNumberRequested);
// System.out.println("Before synchronize");
// Synchronize the responses array
synchronized(this.responses)
{
// System.out.println("Have we seen this part: " + partNumberRequested + " - " + this.responses[partNumberRequested]);
// Check if we have seen this response before
if(!this.responses[partNumberRequested])
{
// System.out.println("Part not seen before");
// Add a response with the part number
this.responses[partNumberRequested] = new Boolean(true);
// Get the response packet
byte[] responseMessage = udpMessage.getMessage();
// Get the bytes that we requested
byte[] bytesToSend = new byte[488];
// Pass the resource id
System.arraycopy(udpMessage.getID1().getBytes(), 0, bytesToSend, 0, ID.getLengthInBytes());
// Get the starting byte
long startByte = partNumberRequested * (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (8));
System.out.println("start bytes: " + startByte);
byte[] byteNumber = ByteBuffer.allocate(8).putLong(startByte).array();
System.out.println(byteNumber[0] + " - " + byteNumber[1] + " - " + byteNumber[2] + " - " + byteNumber[3] + " - " + byteNumber[4] + " - " + byteNumber[5] + " - " + byteNumber[6] + " - " + byteNumber[7]);
// Put the 4 bytes of the starting byte at the 16 slot to send
System.arraycopy(byteNumber, 0, bytesToSend, ID.getLengthInBytes(), 8);
// Get the end byte
long endByte = startByte + (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (8));
System.out.println("End bytes: " + endByte);
byteNumber = ByteBuffer.allocate(8).putLong(endByte).array();
System.out.println(byteNumber[0] + " - " + byteNumber[1] + " - " + byteNumber[2] + " - " + byteNumber[3] + " - " + byteNumber[4] + " - " + byteNumber[5] + " - " + byteNumber[6] + " - " + byteNumber[7]);
// Put the 4 bytes of the end byte in spot 20 of the bytes to send
System.arraycopy(byteNumber, 0, bytesToSend, (8) + ID.getLengthInBytes(), (8));
// Copy the bytes to send
System.arraycopy(responseMessage, ID.getLengthInBytes() + 4, bytesToSend, (16) + ID.getLengthInBytes(), 456);
// Create a new datagram
DatagramPacket resourceBytes = new DatagramPacket(bytesToSend, bytesToSend.length);
// Set the address of the UICOntroller
resourceBytes.setAddress(this.getUIControllerAddress().getAddress());
// Set the port of the UIController
resourceBytes.setPort(this.getUIControllerAddress().getPort());
//System.out.println(new String(bytesToSend));
// Send the bytes as start, end, bytes
this.getQueue().enQueue(resourceBytes);
// System.out.println("Sent to ui part:" + partNumberRequested);
// Notify to get a new part
this.responses.notify();
}
}
}
@Override
public void run()
{
for (int i = 0; i < this.responses.length; i++)
{
// Synchronize the responses array
synchronized(this.responses)
{
// Get a byte array from the part number
byte[] partNumber = new byte[4];
// for(int j = 0; j < PartNumbers.getLengthInBytes(); j++) {
// partNumber[j] = (byte) (i >> ((PartNumbers.getLengthInBytes() - 1 - j) * 8));
int temp = i;
// System.out.println("\n" + i);
for(int j = PartNumbers.getLengthInBytes() - 1; j >= 0; j
partNumber[j] = (byte) (temp & 0xFF);
temp = temp >>> 8;
// System.out.println(">>>> "+ (int)partNumber[j]);
}
// partNumber = ByteBuffer.allocate(4).putInt(i).array();
// System.out.println(i+":"+ByteBuffer.wrap(partNumber).getInt());
byte[] message = new byte[ID.getLengthInBytes() + PartNumbers.getLengthInBytes()];
// new String(ID.idFactory().getBytes()) + new String(partNumber)
System.arraycopy(ID.idFactory().getBytes(), 0, message, 0, ID.getLengthInBytes());
System.arraycopy(partNumber, 0, message, ID.getLengthInBytes(), PartNumbers.getLengthInBytes());
// Create a UDP message with format RequestID, ResourceID, TTL, RandomID, partNumber
UDPMessage getMessage = new UDPMessage(this.getID(), this.resourceID, new TimeToLive(), message);
// Send to peers
GossipPartners.getInstance().send(getMessage);
// System.out.println("Requested part: " + i);
// While we have not receive the part number that we requested
while(!this.responses[i])
{
try
{
// Wait
this.responses.wait();
}
catch (InterruptedException ei)
{
}
}
}
}
}
public Thread startAsThread()
{
Thread thread = new Thread();
thread = new Thread(this);
// Execute the run method
thread.start();
return thread;
}
} |
package edu.mit.dspace;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.SiteAuthenticator;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
/**
* MIT implementation of DSpace Web UI authentication. This version detects
* whether the user is an MIT user, and if so, the user is redirected to the
* certificate login page. Otherwise, the email/password page is used.
* <P>
* The special group at MIT is an "MIT Users" group. Users who are on an
* MIT IP address, or have an e-mail ending in "mit.edu" are implictly
* members of this group.
*
* @author Robert Tansley
* @version $Revision$
*/
public class MITAuthenticator implements SiteAuthenticator
{
/** log4j category */
private static Logger log = Logger.getLogger(SiteAuthenticator.class);
public void startAuthentication(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
if (isMITUser(request))
{
// Try and get a certificate by default
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/certificate-login"));
}
else
{
// Present the username/password screen (with cert option)
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/password-login"));
}
}
public int[] getSpecialGroups(Context context,
HttpServletRequest request)
throws SQLException
{
// Add user to "MIT Users" special group if they're an MIT user
EPerson user = context.getCurrentUser();
boolean hasMITEmail = (user != null &&
user.getEmail().toLowerCase().endsWith("@mit.edu"));
if (hasMITEmail || isMITUser(request))
{
// add the user to the special group "MIT Users"
Group mitGroup = Group.findByName(context, "MIT Users");
if (mitGroup == null)
{
// Oops - the group isn't there.
log.warn(LogManager.getHeader(context,
"No MIT Group found!! Admin needs to create one!",
""));
return new int[0];
}
return new int[] {mitGroup.getID()};
}
return new int[0];
}
/**
* Check to see if the user is an MIT user. At present, it just
* checks the source IP address. Note this is independent of user
* authentication - if the user is an off-site MIT user, this will
* still return false.
*
* @param request current request
*
* @return true if the user is an MIT user.
*/
public static boolean isMITUser(HttpServletRequest request)
{
String addr = request.getRemoteAddr();
final String[] mitIPs =
{
"18.",
"128.52.",
"129.55.", // Lincoln
"192.52.65.", // Haystack
"192.52.61.", // Haystack
"198.125.160.", // Physicists/ESnet ranges purchased
"198.125.161.",
"198.125.162.",
"198.125.163.",
"198.125.176.",
"198.125.177.",
"198.125.178.",
"198.125.179."
};
for (int i = 0; i < mitIPs.length; i++)
{
if (addr.startsWith(mitIPs[i]))
{
return true;
}
}
return false;
}
} |
package etomica.config;
import etomica.api.IAtomLeaf;
import etomica.api.IAtomPositioned;
import etomica.api.IBox;
import etomica.api.IMolecule;
import etomica.api.ISpecies;
import etomica.api.IVector;
import etomica.lattice.BravaisLatticeCrystal;
import etomica.lattice.IndexIteratorRectangular;
import etomica.space.Boundary;
import etomica.space.ISpace;
import etomica.space.RotationTensor;
import etomica.space3d.Vector3D;
/**
*
*
* @authors ajschultz, msellers
*/
public class GrainBoundaryTiltConfiguration implements Configuration {
RotationTensor eulerRotationL2BoxTOP;
RotationTensor eulerRotationB2LatticeTOP;
RotationTensor eulerRotationL2BoxBOTTOM;
RotationTensor eulerRotationB2LatticeBOTTOM;
BravaisLatticeCrystal latticeTOP, latticeBOTTOM;
ISpecies [] species;
double cutoff;
double angle;
double dist;
double spacing;
protected ISpecies fixedSpecies, mobileSpecies;
private ISpace space;
IVector [] reciprocal, origin, plane;
IVector normal;
int [] millerPlane;
public GrainBoundaryTiltConfiguration(BravaisLatticeCrystal aLatticeTOP,
BravaisLatticeCrystal aLatticeBOTTOM, ISpecies [] aSpecies,
double aCutoff, ISpace space){
super();
latticeTOP = aLatticeTOP;
latticeBOTTOM = aLatticeBOTTOM;
cutoff = aCutoff;
species = aSpecies;
this.space = space;
eulerRotationL2BoxTOP = latticeTOP.getSpace().makeRotationTensor();
eulerRotationB2LatticeTOP = latticeTOP.getSpace().makeRotationTensor();
eulerRotationL2BoxBOTTOM = latticeBOTTOM.getSpace().makeRotationTensor();
eulerRotationB2LatticeBOTTOM = latticeBOTTOM.getSpace().makeRotationTensor();
resetRotation();
}
public void setFixedSpecies(ISpecies newFixedSpecies) {
fixedSpecies = newFixedSpecies;
}
public void setMobileSpecies(ISpecies newMobileSpecies) {
mobileSpecies = newMobileSpecies;
}
public ISpecies getFixedSpecies() {
return fixedSpecies;
}
public ISpecies getMobileSpecies() {
return mobileSpecies;
}
public void resetRotation(){
eulerRotationL2BoxTOP.reset();
eulerRotationL2BoxBOTTOM.reset();
eulerRotationB2LatticeTOP.reset();
eulerRotationB2LatticeBOTTOM.reset();
}
/**
* Sets tensor for rotation about the indicated axis (0=x,1=y,2=z) by
* the given angle. Calls method from RotationTensor3D.
*/
public void setRotationTOP(int axis, double aAngle){
angle = aAngle;
RotationTensor rotT = latticeTOP.getSpace().makeRotationTensor();
rotT.setAxial(axis, angle);
rotT.TE(eulerRotationL2BoxTOP);
eulerRotationL2BoxTOP.E(rotT);
eulerRotationB2LatticeTOP.E(eulerRotationL2BoxTOP);
eulerRotationB2LatticeTOP.invert();
}
public void setRotationBOTTOM(int axis, double aAngle){
angle = aAngle;
RotationTensor rotT = latticeBOTTOM.getSpace().makeRotationTensor();
rotT.setAxial(axis, angle);
rotT.TE(eulerRotationL2BoxBOTTOM);
eulerRotationL2BoxBOTTOM.E(rotT);
eulerRotationB2LatticeBOTTOM.E(eulerRotationL2BoxBOTTOM);
eulerRotationB2LatticeBOTTOM.invert();
}
/**
* Allows a user to specify a plane for GB
*/
public void setGBplane(int [] m){
millerPlane = m;
origin = new IVector[space.D()];
for(int i=0; i<space.D(); i++){
origin[i] = space.makeVector();
origin[i].setX(i,1);
}
reciprocal = latticeTOP.getPrimitive().makeReciprocal().vectors();
normal = space.makeVector();
for(int i=0; i<space.D(); i++){
normal.PEa1Tv1(millerPlane[i], reciprocal[i]);
}
spacing = Math.PI*2.0/Math.sqrt(normal.squared());
IVector projection = space.makeVector();
//rotate Miller plane into Y axis, about Z axis (through XY plane).
projection.E(normal);
//get XY projection of normal
projection.setX(2, 0.0);
double theta = Math.acos(projection.dot(origin[1]) / Math.sqrt(projection.squared()));
setRotationTOP(2,theta);
setRotationBOTTOM(2,theta);
//rotate Miller plane into Z axis, about X axis (through YZ plane).
projection.E(normal);
//get normal after rotation
eulerRotationL2BoxTOP.transform(projection);
double phi = Math.acos(projection.dot(origin[2]) / Math.sqrt(projection.squared()));
System.out.println(phi);
setRotationTOP(0,phi);
setRotationBOTTOM(0,-phi);
}
/**
* Resizes simulation box to preserve periodic boundary conditions after rotation of lattice.
* @param box
*/
public void setBoxSize(IBox box, int[] boxMultiples){
int [] m = new int[millerPlane.length];
for(int i=0; i<m.length; i++){
m[i] = millerPlane[i];
if(m[i]==0){
m[i]=1;
}
}
//Create vector array of Miller plane XYZ intercepts (least common multiple at X intercept)
plane = new IVector[space.D()];
for(int i=0; i<plane.length; i++){
plane[i] = space.makeVector();
}
plane[0].setX(0, m[0]*m[1]*m[2]*latticeTOP.getLatticeConstants()[0]);
plane[1].setX(1, m[0]*m[1]*m[2]*latticeTOP.getLatticeConstants()[1]);
plane[2].setX(2, m[0]*m[1]*m[2]*latticeTOP.getLatticeConstants()[2]);
for(int i=0; i<plane.length; i++){
if(millerPlane[i]==0){
plane[i].setX(i,0);
}
}
//Find X periodicity - magnitude of Miller plane intersection of X and Y axis.
IVector xaxisperiod = space.makeVector();
xaxisperiod.Ev1Mv2(plane[0], plane[1]);
double xaxispbc = Math.sqrt(xaxisperiod.squared());
//Find Y periodicity - magnitude of vector formed by Miler plane intersections of Z axis and XY plane.
IVector yaxisperiod = space.makeVector();
double yaxispbc = Math.sqrt(Math.pow(2.0*plane[2].x(2),2) + Math.pow(plane[0].x(0),2) + Math.pow(plane[1].x(1),2) );
//If plane does not intersect X axis
if(millerPlane[0]==0){
xaxispbc=latticeTOP.getLatticeConstants()[0];
}
//If plane does not intersect Y axis
if(millerPlane[1]==0){
yaxisperiod.Ev1Mv2(plane[0], plane[2]);
yaxispbc=Math.sqrt(yaxisperiod.squared());
xaxispbc=latticeTOP.getLatticeConstants()[1];
}
//If plane does not intersect Z axis
if(millerPlane[2]==0){
yaxispbc=latticeTOP.getLatticeConstants()[2];
}
//Set Box size
box.getBoundary().setDimensions(new Vector3D(xaxispbc*boxMultiples[0], yaxispbc*boxMultiples[1], 2.0*Math.PI/Math.sqrt(normal.squared())*boxMultiples[2]));
}
public void initializeCoordinates(IBox box){
if(!(box.getBoundary() instanceof Boundary)) {
throw new RuntimeException("Cannot initialize coordinates for a box containing a non etomica.space.Boundary");
}
/**
* FILL ATOMS IN TOP DOMAIN
*/
IVector boxCorner = space.makeVector();
IVector latticeVector = space.makeVector();
// Get extremes of rotated simulation domain A (usually top half of Box)
for(int i=-1; i<3; i++){
// Map corners of A domain
boxCorner.E(box.getBoundary().getDimensions());
boxCorner.TE(0.5);
boxCorner.setX(2, boxCorner.x(2)*0.5);
if (i!=-1){
boxCorner.setX(i, -boxCorner.x(i));
}
//Transform to lattice space coords
eulerRotationB2LatticeTOP.transform(boxCorner);
for(int j=0; j<3; j++){
// Loop over all dimensions at box corner
if (Math.abs(boxCorner.x(j))>latticeVector.x(j)){
latticeVector.setX(j, Math.abs(boxCorner.x(j)));
}
}
}
//Compute number of cells to fit in box
int [] ncellsTOP = new int[space.D()+1];
IVector latticeCenter = space.makeVector();
for(int i=0; i<ncellsTOP.length-1; i++){
ncellsTOP[i] = (int)Math.ceil(latticeVector.x(i)*2/latticeTOP.getPrimitive().vectors()[i].x(i));
latticeCenter.setX(i, 0.5*ncellsTOP[i]*latticeTOP.getPrimitive().vectors()[i].x(i));
}
ncellsTOP[ncellsTOP.length-1] = latticeTOP.getBasis().getScaledCoordinates().length;
IndexIteratorRectangular indexIteratorTOP = new IndexIteratorRectangular(space.D()+1);
indexIteratorTOP.setSize(ncellsTOP);
indexIteratorTOP.reset();
while(indexIteratorTOP.hasNext()){
IVector transformedPosition = space.makeVector();
transformedPosition.E((IVector)latticeTOP.site(indexIteratorTOP.next()));
transformedPosition.ME(latticeCenter);
eulerRotationL2BoxTOP.transform(transformedPosition);
transformedPosition.setX(2,transformedPosition.x(2)+(0.25*box.getBoundary().getDimensions().x(2)));
// If the atom position is outside the original simulation domain A (top half of simulation box)
if(!((Boundary)box.getBoundary()).getShape().contains(transformedPosition)||transformedPosition.x(2)<-0.0001){
continue;
}
// Check to see if this atom needs to be fixed.
IMolecule a = null;
if(transformedPosition.x(2)>(box.getBoundary().getDimensions().x(2)/2.0 - cutoff)){
a = fixedSpecies.makeMolecule();
}
else{
a = mobileSpecies.makeMolecule();
}
box.addMolecule(a);
((IAtomPositioned)a.getChildList().getAtom(0)).getPosition().E(transformedPosition);
}
/**
* FILL ATOMS IN BOTTOM DOMAIN
*/
// Get extremes of rotated simulation domain B (usually bottom half of Box)
for(int i=-1; i<3; i++){
// Map corners of B domain
boxCorner.E(box.getBoundary().getDimensions());
boxCorner.TE(0.5);
boxCorner.setX(2, boxCorner.x(2)*0.5);
if (i!=-1){
boxCorner.setX(i, -boxCorner.x(i));
}
//Transform to lattice space coords
eulerRotationB2LatticeBOTTOM.transform(boxCorner);
for(int j=0; j<3; j++){
// Loop over all dimensions at box corner
if (Math.abs(boxCorner.x(j))>latticeVector.x(j)){
latticeVector.setX(j, Math.abs(boxCorner.x(j)));
}
}
}
//Compute number of cells to fit in box
int [] ncellsBOTTOM = new int[space.D()+1];
for(int i=0; i<ncellsBOTTOM.length-1; i++){
ncellsBOTTOM[i] = (int)Math.ceil(latticeVector.x(i)*2/latticeBOTTOM.getPrimitive().vectors()[i].x(i));
latticeCenter.setX(i, 0.5*ncellsBOTTOM[i]*latticeBOTTOM.getPrimitive().vectors()[i].x(i));
}
ncellsBOTTOM[ncellsBOTTOM.length-1] = latticeBOTTOM.getBasis().getScaledCoordinates().length;
IndexIteratorRectangular indexIteratorBOTTOM = new IndexIteratorRectangular(space.D()+1);
indexIteratorBOTTOM.setSize(ncellsBOTTOM);
indexIteratorBOTTOM.reset();
while(indexIteratorBOTTOM.hasNext()){
IVector transformedPosition = space.makeVector();
transformedPosition.E((IVector)latticeBOTTOM.site(indexIteratorBOTTOM.next()));
transformedPosition.ME(latticeCenter);
eulerRotationL2BoxBOTTOM.transform(transformedPosition);
//Notice negative sign for bottom domain
transformedPosition.setX(2,transformedPosition.x(2)+(-0.25*box.getBoundary().getDimensions().x(2)));
// If the atom position is outside the original simulation domain B (bottom half of simulation box)
if(!((Boundary)box.getBoundary()).getShape().contains(transformedPosition)||transformedPosition.x(2)>0.0001){
continue;
}
// Check to see if this atom needs to be fixed. Notice signs/inequalities
IMolecule a = null;
if(transformedPosition.x(2)<(-box.getBoundary().getDimensions().x(2)/2.0 + cutoff)){
a = fixedSpecies.makeMolecule();
}
else{
a = mobileSpecies.makeMolecule();
}
box.addMolecule(a);
((IAtomPositioned)a.getChildList().getAtom(0)).getPosition().E(transformedPosition);
}
/**
* REMOVE OVERLAPPING ATOMS AT GRAIN BOUNDARY INTERFACE
*/
dist = 3.0;
IVector rij = space.makeVector();
int removeCount = 0;
double range = 0.0;
for(int i=0; i<box.getLeafList().getAtomCount()-1; i++){
for(int j=i+1; j<box.getLeafList().getAtomCount(); j++){
rij.E(((IAtomPositioned)box.getLeafList().getAtom(i)).getPosition());
rij.ME(((IAtomPositioned)box.getLeafList().getAtom(j)).getPosition());
box.getBoundary().nearestImage(rij);
range = rij.squared();
if(range<dist){
box.removeMolecule(((IAtomLeaf)box.getLeafList().getAtom(j)).getParentGroup());
removeCount++;
}
}
}
//Create gap between grains
/**
for(int i=0; i<box.getLeafList().getAtomCount()-1; i++){
if(Math.abs(((IAtomPositioned)box.getLeafList().getAtom(i)).getPosition().x(2))<3){
box.removeMolecule(box.getLeafList().getAtom(i));
removeCount++;
}
}
*/
System.out.println("Tilt Grain Boundary of "+angle*180/Math.PI+" degrees created.");
System.out.println(removeCount+" atoms were within "+Math.sqrt(dist)+" of another, and removed.");
}
} |
package ch.elexis.core.common;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class InstanceStatus {
public enum STATE {
UNDEF, STARTING_UP, ACTIVE, SHUTTING_DOWN
};
private String uuid;
private String activeUser;
private String identifier;
private String version;
private STATE state = STATE.UNDEF;
private String operatingSystem;
// server written
private Date firstSeen;
private Date lastUpdate;
private String remoteAddress;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getActiveUser() {
return activeUser;
}
public void setActiveUser(String activeUser) {
this.activeUser = activeUser;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public STATE getState() {
return state;
}
public void setState(STATE state) {
this.state = state;
}
public String getOperatingSystem() {
return operatingSystem;
}
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
public Date getFirstSeen() {
return firstSeen;
}
public void setFirstSeen(Date firstSeen) {
this.firstSeen = firstSeen;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
@Override
public String toString() {
String identifier = getIdentifier() != null ? " @ " + getIdentifier() : "";
String ret = "[" + getUuid() + "] " + getActiveUser() + identifier + " (Version " + getVersion() + " @ "
+ getOperatingSystem() + ") ";
if (getState() != STATE.ACTIVE) {
ret += getState();
}
return ret;
}
} |
/**
* removing duplicates from String array.
*
* @author Vadim Mironov (multik6292@mail.ru/mironov6292@gmail.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.array;
import java.util.Arrays;
/**
* Class for removing duplicates from String array.
*/
public class ArrayDuplicate {
/**
* Method for removing duplicates from String array.
* @param array - int[] for removing duplicates
* @return int[] - array after removing duplicates
*/
public String[] remove(String[] array) {
int resultSize = array.length;
for (int i = 0; i < resultSize; i++) {
for (int j = i + 1; j < array.length - 1; j++) {
if (array[i].equals(array[j])) {
resultSize
for (int t = j; t < array.length - 1; t++) {
array[t] = array[t + 1];
}
}
}
}
return Arrays.copyOf(array, resultSize);
}
} |
package tk.wurst_client;
import tk.wurst_client.analytics.AnalyticsManager;
import tk.wurst_client.chat.ChatManager;
import tk.wurst_client.commands.CmdManager;
import tk.wurst_client.events.EventManager;
import tk.wurst_client.files.FileManager;
import tk.wurst_client.font.Fonts;
import tk.wurst_client.hooks.FrameHook;
import tk.wurst_client.mods.ModManager;
import tk.wurst_client.navigator.Navigator;
import tk.wurst_client.options.FriendsList;
import tk.wurst_client.options.KeybindManager;
import tk.wurst_client.options.OptionsManager;
import tk.wurst_client.special.SpfManager;
import tk.wurst_client.update.Updater;
public enum WurstClient
{
INSTANCE;
public static final String VERSION = "4.5";
public static final String MINECRAFT_VERSION = "1.10";
public AnalyticsManager analytics;
public ChatManager chat;
public CmdManager commands;
public EventManager events;
public FileManager files;
public FriendsList friends;
public ModManager mods;
public Navigator navigator;
public KeybindManager keybinds;
public OptionsManager options;
public SpfManager special;
public Updater updater;
private boolean enabled = true;
public void startClient()
{
events = new EventManager();
mods = new ModManager();
commands = new CmdManager();
special = new SpfManager();
files = new FileManager();
updater = new Updater();
chat = new ChatManager();
keybinds = new KeybindManager();
options = new OptionsManager();
friends = new FriendsList();
navigator = new Navigator();
files.init();
navigator.sortFeatures();
Fonts.loadFonts();
updater.checkForUpdate();
analytics =
new AnalyticsManager("UA-52838431-5", "client.wurst-client.tk");
files.saveOptions();
FrameHook.maximize();
}
public boolean isEnabled()
{
return enabled;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
if(!enabled)
mods.panicMod.onUpdate();
}
} |
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.StringTokenizer;
import jing.chem.ChemGraph;
import jing.chem.ForbiddenStructureException;
import jing.chem.Species;
import jing.chemParser.ChemParser;
import jing.chemUtil.Graph;
import jing.param.Global;
import jing.param.Temperature;
import jing.rxn.Kinetics;
import jing.rxn.Reaction;
import jing.rxn.TemplateReactionGenerator;
import jing.rxnSys.ReactionModelGenerator;
public class PopulateReactions {
/**
* Generates a list of all possible reactions, and their modified Arrhenius
* parameters, between all species supplied in the input file.
*
* The input file's first line should specify the system temperature. The
* line should be formatted as follows:
* Temperature: 500 (K)
* The input (.txt) file should contain a list of species, with the first
* line of each species being a user-defined name for the species and the
* remaining lines containing the graph (in the form of an adjacency list).
* There is no limit on the number of ChemGraphs the user may supply.
*
* The output of the function is two .txt files: PopRxnsOutput_rxns.txt and
* PopRxnsOutput_spcs.txt. The first contains the list of reactions (including
* the modified Arrhenius parameters and RMG-generated comments) and the second
* the list of species (including the ChemGraph) that are involved in the list
* of reactions.
*/
public static void main(String[] args) {
initializeSystemProperties();
// Set Global.lowTemp and Global.highTemp
// The values of the low/highTemp are not used in the function
// (to the best of my knowledge).
// They are necessary for the instances of additionalKinetics,
// e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
Global.lowTemperature = new Temperature(300,"K");
Global.highTemperature = new Temperature(1500,"K");
// Define an integer to count the number of sets of duplicate kinetics
int numDupKinetics = 0;
// Define variable 'speciesSet' to store the species contained in the input file
LinkedHashSet speciesSet = new LinkedHashSet();
// Define variable 'reactions' to store all possible rxns between the species in speciesSet
LinkedHashSet reactions = new LinkedHashSet();
// Define two string variables 'listOfReactions' and 'listOfSpecies'
// These strings will hold the list of rxns (including the structure,
// modified Arrhenius parameters, and source/comments) and the list of
// species (including the chemkin name and graph), respectively
String listOfReactions = "Arrhenius 'A' parameter has units of: mol,cm3,s\n" +
"Arrhenius 'n' parameter is unitless\n" +
"Arrhenius 'E' parameter has units of: kcal/mol\n\n";
String listOfSpecies = "";
// Open and read the input file
try {
FileReader fr_input = new FileReader(args[0]);
BufferedReader br_input = new BufferedReader(fr_input);
// Read in the first line of the input file
// This line should hold the temperature of the system, e.g.
// Temperature: 500 (K)
String line = ChemParser.readMeaningfulLine(br_input);
Temperature systemTemp = null;
if (!line.startsWith("Temperature")) {
System.err.println("Error reading input file: Could not locate System Temperature.\n" +
"The first line of the input file should read: \"Temperature: Value (Units)\"");
} else {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This token should be "Temperature:"
systemTemp = new Temperature(Double.parseDouble(st.nextToken()),ChemParser.removeBrace(st.nextToken()));
}
Temperature systemTemp_K = new Temperature(systemTemp.getK(),"K");
// Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.setTemp4BestKinetics(systemTemp_K);
TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
listOfReactions += "System Temperature: " + systemTemp_K.getK() + "K\n\n";
line = ChemParser.readMeaningfulLine(br_input);
StringTokenizer st = new StringTokenizer(line);
// The first line should start with "Solvation", otherwise do nothing and display a message to the user
if (st.nextToken().startsWith("Solvation")) {
line = st.nextToken().toLowerCase();
// The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do nothing and display a message to the user
// Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet committed.
if (line.equals("on")) {
Species.useSolvation = true;
// rmg.setUseDiffusion(true);
listOfReactions += "Solution-phase chemistry!\n\n";
} else if (line.equals("off")) {
Species.useSolvation = false;
// rmg.setUseDiffusion(false);
listOfReactions += "Gas-phase chemistry.\n\n";
} else {
System.out.println("Error in reading thermo_input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'.");
return;
}
}
line = ChemParser.readMeaningfulLine(br_input);
while (line != null) {
// The first line of a new species is the user-defined name
String speciesName = line;
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(br_input);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(speciesName,cg);
// Add the new species to the set of species
speciesSet.add(species);
// Define a dummy hash set 'new_reactions' to hold the list
// of rxns for the new species against the species seed
LinkedHashSet new_reactions = new LinkedHashSet();
// React the new species with the set of species (including itself)
new_reactions = rtLibrary.react(speciesSet,species);
reactions.addAll(new_reactions);
// Read the next line of the input file
line = ChemParser.readMeaningfulLine(br_input);
}
// Iterate over all rxns, abstracting the necessary information,
// and store the results in the 'listOfReactions' string
Iterator iter_rxns = reactions.iterator();
while (iter_rxns.hasNext()){
Reaction r = (Reaction)iter_rxns.next();
if (r.hasAdditionalKinetics()) {
++numDupKinetics;
HashSet indiv_rxn = r.getAllKinetics();
for (Iterator iter = indiv_rxn.iterator(); iter.hasNext();) {
Kinetics k_rxn = (Kinetics)iter.next();
if (r.isForward()) listOfReactions += r.toString() + "\t" + updateListOfReactions(k_rxn) + "\tDUP " + numDupKinetics + "\n";
else if (r.isBackward()) listOfReactions += r.getReverseReaction().toString() + "\t" + updateListOfReactions(k_rxn) + "\tDUP " + numDupKinetics + "\n";
else listOfReactions += r.toString() + "\t" + updateListOfReactions(k_rxn) + "\tDUP " + numDupKinetics + "\n";
}
} else {
if (r.isForward()) listOfReactions += r.toString() + "\t" + updateListOfReactions(r.getKinetics());
//else if (r.isBackward()) listOfReactions += r.toString() + "\t" + updateListOfReactions(r.getFittedReverseKinetics(),r.getReactionTemplate().getName());
else if (r.isBackward()) listOfReactions += r.getReverseReaction().toString() + "\t" + updateListOfReactions(r.getReverseReaction().getKinetics());
else listOfReactions += r.toString() + "\t" + updateListOfReactions(r.getKinetics());
}
// Add the products of the reactions to the list of species
// hash set. The reactants of each reaction are already
// present. This list will allow us to generate the graphs
// for all species involved in rxns.
speciesSet.addAll(r.getProductList());
}
Iterator iter_species = speciesSet.iterator();
// Define dummy integer 'i' so our getChemGraph().toString()
// call only returns the graph
int i = 0;
while (iter_species.hasNext()) {
Species species = (Species)iter_species.next();
listOfSpecies += species.getChemkinName() + "\n" +
species.getChemGraph().toString(i) + "\n";
}
// Write the output files
try{
File rxns = new File("PopRxnsOutput_rxns.txt");
FileWriter fw_rxns = new FileWriter(rxns);
fw_rxns.write(listOfReactions);
fw_rxns.close();
File spcs = new File("PopRxnsOutput_spcs.txt");
FileWriter fw_spcs = new FileWriter(spcs);
fw_spcs.write(listOfSpecies);
fw_spcs.close();
}
catch (IOException e) {
System.out.println("Could not write PopRxnsOutput.txt files");
System.exit(0);
}
// Display to the user that the program was successful and also
// inform them where the results may be located
System.out.println("Reaction population complete. Results are stored"
+ " in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
} catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
} catch(IOException e) {
System.err.println("Something wrong with ChemParser.readChemGraph");
}
}
public static void initializeSystemProperties() {
File GATPFit = new File("GATPFit");
ChemParser.deleteDir(GATPFit);
GATPFit.mkdir();
String name= "RMG_database";
String workingDir = System.getenv("RMG");
System.setProperty("RMG.workingDirectory", workingDir);
System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile",workingDir + "/databases/" + name + "/forbiddenStructure/forbiddenStructure.txt");
System.setProperty("jing.chem.ThermoGAGroupLibrary.pathName", workingDir + "/databases/" + name + "/thermo");
System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", workingDir + "/databases/" + name + "/kinetics");
};
public static String updateListOfReactions(Kinetics rxn_k) {
String output = rxn_k.getAValue() + "\t" + rxn_k.getNValue()
+ "\t" + rxn_k.getEValue() + "\t" + rxn_k.getSource()
+ "\t" + rxn_k.getComment() + "\n";
return output;
}
public static String updateListOfReactions(Kinetics rxn_k, String reverseRxnName) {
String output = rxn_k.getAValue() + "\t" + rxn_k.getNValue()
+ "\t" + rxn_k.getEValue() + "\t" + reverseRxnName + ": "
+ rxn_k.getSource() + "\t" + rxn_k.getComment() + "\n";
return output;
}
} |
package joliex.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import jolie.net.CommMessage;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
public class FileService extends JavaService
{
private static void readBase64IntoValue( File file, Value value )
throws IOException
{
FileInputStream fis = new FileInputStream( file );
byte[] buffer = new byte[ (int)file.length() ];
fis.read( buffer );
fis.close();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
value.setValue( encoder.encode( buffer ) );
}
private static void readBinaryIntoValue( File file, Value value )
throws IOException
{
FileInputStream fis = new FileInputStream( file );
byte[] buffer = new byte[ (int)file.length() ];
fis.read( buffer );
fis.close();
value.setValue( new ByteArray( buffer ) );
}
private static void readTextIntoValue( File file, Value value )
throws IOException
{
String separator = System.getProperty( "line.separator" );
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader reader = new BufferedReader( new FileReader( file ) );
while( (line=reader.readLine()) != null ) {
buffer.append( line );
buffer.append( separator );
}
reader.close();
value.setValue( buffer.toString() );
}
public CommMessage readFile( CommMessage message )
throws FaultException
{
Value filenameValue = message.value().getChildren( "filename" ).first();
if ( !filenameValue.isString() ) {
throw new FaultException( "FileNotFound" );
}
Value retValue = Value.create();
String format = message.value().getFirstChild( "format" ).strValue();
try {
if ( "base64".equals( format ) ) {
readBase64IntoValue( new File( filenameValue.strValue() ), retValue );
} else if ( "binary".equals( format ) ) {
readBinaryIntoValue( new File( filenameValue.strValue() ), retValue );
} else {
readTextIntoValue( new File( filenameValue.strValue() ), retValue );
}
} catch( FileNotFoundException e ) {
throw new FaultException( "FileNotFound", e );
} catch( IOException e ) {
throw new FaultException( e );
}
return new CommMessage( message.operationName(), "/", retValue );
}
public CommMessage writeFile( CommMessage request )
throws FaultException
{
Value filenameValue = request.value().getFirstChild( "filename" );
if ( !filenameValue.isString() ) {
throw new FaultException( "FileNotFound" );
}
Value content = request.value().getFirstChild( "content" );
try {
if ( content.isByteArray() ) {
FileOutputStream os = new FileOutputStream( filenameValue.strValue() );
os.write( ((ByteArray)content.valueObject()).getBytes() );
os.flush();
} else {
FileWriter writer = new FileWriter( filenameValue.strValue() );
writer.write( content.strValue() );
System.out.println( content.strValue());
writer.flush();
}
} catch( IOException e ) {
throw new FaultException( e );
}
return CommMessage.createEmptyMessage();
}
} |
package org.jpos.q2.qbean;
import org.jpos.q2.Q2;
import org.jpos.q2.QBean;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.QPersist;
import org.jdom.Element;
import org.jpos.util.Log;
import org.jpos.util.Logger;
import javax.management.*;
/**
* @author <a href="mailto:taherkordy@dpi2.dpi.net.ir">Alireza Taherkordi</a>
*
* <http-adaptor class="org.jpos.q2.qbean.HttpAdaptor"
* name="http-adaptor" >
* <attr name="host">localhost</attr>
* <attr name="port" type="java.lang.Integer">8082</attr>
* </http-adaptor>
*
* set host property to "localhost" if you want to can't access the server
* from another computer,This is good for security reasons.
*
* @version $Revision$ $Date$
*/
public class HttpAdaptor
extends mx4j.adaptor.http.HttpAdaptor
implements HttpAdaptorMBean , QBean, QPersist
{
Element persist;
int state;
Q2 server;
String name, loggerName, user, password;
boolean modified;
ObjectName processorName;
Log log;
public HttpAdaptor () {
super();
state = -1;
}
public void setServer (Q2 server) {
this.server = server;
}
public Q2 getServer () {
return server;
}
public void setName (String name) {
this.name = name;
setModified (true);
}
public String getName () {
return name;
}
public void setUser (String user) {
this.user = user;
}
public String getUser () {
return user;
}
public void setPassword (String password) {
this.password = password;
}
public void setLogger (String loggerName) {
this.loggerName = loggerName;
log = new Log (Logger.getLogger (loggerName), getName ());
setModified (true);
}
public String getLogger ()
{
return log.getLogger().getName();
}
public void init ()
{
if (state != -1)
return;
try {
setModified (false);
processorName = new ObjectName("MX4J:name=mx4j.adaptor.http.XSLTProcessor");
mx4j.adaptor.http.XSLTProcessor processorMBean = new mx4j.adaptor.http.XSLTProcessor();
getServer().getMBeanServer().registerMBean(processorMBean,processorName);
setProcessorName(processorName);
if (user != null && password != null) {
addAuthorization(user, password);
setAuthenticationMethod ("basic");
}
state = QBean.STOPPED;
} catch (Exception e) {
if (log != null)
log.warn ("init", e);
}
}
public void start()
{
if (state != QBean.DESTROYED &&
state != QBean.STOPPED &&
state != QBean.FAILED)
return;
this.state = QBean.STARTING;
try {
super.start();
} catch (Throwable t) {
state = QBean.FAILED;
t.printStackTrace();
return;
}
state = QBean.STARTED;
}
public void stop ()
{
if (state != QBean.STARTED)
return;
state = QBean.STOPPING;
try {
super.stop();
} catch (Throwable t) {
state = QBean.FAILED;
t.printStackTrace();
return;
}
state = QBean.STOPPED;
}
public void destroy ()
{
if (state == QBean.DESTROYED)
return;
if (state != QBean.STOPPED)
stop();
try {
getServer().getMBeanServer().unregisterMBean(processorName);
} catch (Exception e) {
if (log != null)
log.warn ("destroy", e);
}
state = QBean.DESTROYED;
}
public int getState () {
return state;
}
public String getStateAsString () {
return QBeanSupport.stateString[state];
}
public void setState (int state) {
this.state = state;
}
public void setPersist (Element persist) {
this.persist = persist ;
}
private Element createAttr (String name, String value, String type) {
Element e = new Element ("attr");
e.setAttribute ("name", name);
if (type != null)
e.setAttribute ("type", type);
e.setText (value);
return e;
}
private Element createAttr (String name, String value) {
return createAttr (name, value, null);
}
public synchronized Element getPersist () {
setModified (false);
Element e = new Element (persist.getName());
Element classPath = persist.getChild ("classpath");
if (classPath != null)
e.addContent (classPath);
e.setAttribute ("class", getClass().getName());
if (!e.getName().equals (getName ()))
e.setAttribute ("name", getName());
if (loggerName != null)
e.setAttribute ("logger", loggerName);
e.addContent (
createAttr ("host", getHost())
);
e.addContent (
createAttr (
"port", Integer.toString (getPort()), "java.lang.Integer")
);
if (user != null && password != null) {
e.addContent (createAttr ("user", user));
e.addContent (createAttr ("password", password));
}
return (persist = e);
}
public synchronized void setModified (boolean modified) {
this.modified = modified;
}
public synchronized boolean isModified () {
return modified;
}
protected boolean running () {
return state == QBean.STARTING || state == QBean.STARTED;
}
public void setHost (String host) {
setModified (true);
super.setHost (host);
}
public void setPort (int port) {
setModified (true);
super.setPort (port);
}
public void shutdownQ2 () {
getServer().shutdown ();
}
} |
package carpentersblocks.entity.item;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import carpentersblocks.api.ICarpentersHammer;
import carpentersblocks.util.BlockProperties;
import carpentersblocks.util.PlayerPermissions;
import carpentersblocks.util.handler.DyeHandler;
import carpentersblocks.util.handler.TileHandler;
import carpentersblocks.util.registry.IconRegistry;
import carpentersblocks.util.registry.ItemRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class EntityCarpentersTile extends EntityBase {
private int ticks;
private boolean boundsSet;
private final static byte ID_DIR = 13;
private final static byte ID_DYE = 14;
private final static byte ID_TILE = 15;
private final static byte ID_ROT = 16;
private final static String TAG_TILE = "tile";
private final static String TAG_DIR = "dir";
private final static String TAG_DYE = "dye";
private final static String TAG_ROT = "rot";
/** Depth of tile. */
private final static double depth = 0.0625D;
private final static double[][] bounds =
{
{ 0.0D, 1.0D - depth, 0.0D, 1.0D, 1.0D, 1.0D },
{ 0.0D, 0.0D, 0.0D, 1.0D, depth, 1.0D },
{ 0.0D, 0.0D, 1.0D - depth, 1.0D, 1.0D, 1.0D },
{ 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, depth },
{ 1.0D - depth, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D },
{ 0.0D, 0.0D, 0.0D, depth, 1.0D, 1.0D }
};
public EntityCarpentersTile(World world)
{
super(world);
}
public EntityCarpentersTile(EntityPlayer entityPlayer, World world, int x, int y, int z, ForgeDirection dir, ForgeDirection offset_side, boolean ignoreNeighbors)
{
super(world, entityPlayer);
posX = x;
posY = y;
posZ = z;
setDirection(dir);
setBoundingBox();
if (!ignoreNeighbors) {
List<EntityCarpentersTile> list = new ArrayList<EntityCarpentersTile>();
double factor = 0.2D;
boundingBox.contract(0.1D, 0.1D, 0.1D);
switch (offset_side) {
case DOWN:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(0.0D, -factor, 0.0D));
break;
case UP:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(0.0D, factor, 0.0D));
break;
case NORTH:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(0.0D, 0.0D, -factor));
break;
case SOUTH:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(0.0D, 0.0D, factor));
break;
case WEST:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(-factor, 0.0D, 0.0D));
break;
case EAST:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.offset(factor, 0.0D, 0.0D));
break;
default:
switch (dir) {
case DOWN:
case UP:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.expand(factor, 0.0D, factor));
break;
case NORTH:
case SOUTH:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.expand(factor, factor, 0.0D));
break;
case WEST:
case EAST:
list = world.getEntitiesWithinAABB(EntityCarpentersTile.class, boundingBox.expand(0.0D, factor, factor));
break;
default: {}
}
}
for (EntityCarpentersTile tile : list)
{
/* Skip checking diagonal tiles when tile is placed in center. */
if (offset_side.equals(ForgeDirection.UNKNOWN))
{
switch (dir) {
case DOWN:
case UP:
if (!(tile.posX == posX || tile.posZ == posZ)) {
continue;
}
break;
case NORTH:
case SOUTH:
if (!(tile.posX == posX || tile.posY == posY)) {
continue;
}
break;
case WEST:
case EAST:
if (!(tile.posZ == posZ || tile.posY == posY)) {
continue;
}
break;
default: {}
}
}
/* Match up tile properties with neighbor. */
if (!tile.getDye().equals(getDefaultDye())) {
setDye(tile.getDye());
}
if (tile.getRotation() != 0) {
setRotation(tile.getRotation());
}
if (!tile.getTile().equals(getDefaultTile())) {
setTile(tile.getTile());
}
}
}
}
/**
* Keeps moving the entity up so it isn't colliding with blocks and other requirements for this entity to be spawned
* (only actually used on players though its also on Entity)
*/
@Override
@SideOnly(Side.CLIENT)
protected void preparePlayerToSpawn() { }
/**
* Sets the width and height of the entity. Args: width, height
*/
@Override
protected void setSize(float width, float height) { }
/**
* Sets the x,y,z of the entity from the given parameters. Also seems to set up a bounding box.
*/
@Override
public void setPosition(double x, double y, double z) { }
/**
* Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX,
* posY, posZ, yaw, pitch
*/
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double posX, double posY, double posZ, float yaw, float pitch, int par9) { }
/**
* Called when a player mounts an entity. e.g. mounts a pig, mounts a boat.
*/
@Override
public void mountEntity(Entity entity) { }
@Override
protected boolean func_145771_j(double x, double y, double z)
{
return false;
}
public String getDefaultTile()
{
return "blank";
}
public String getDefaultDye()
{
return "dyeWhite";
}
public void playTileSound()
{
BlockProperties.playBlockSound(worldObj, new ItemStack(Blocks.hardened_clay), (int) Math.floor(posX), (int) Math.floor(posY), (int) Math.floor(posZ));
}
public void playDyeSound()
{
BlockProperties.playBlockSound(worldObj, new ItemStack(Blocks.sand), (int) Math.floor(posX), (int) Math.floor(posY), (int) Math.floor(posZ));
}
public double[] getBounds()
{
return bounds[getDataWatcher().getWatchableObjectInt(ID_DIR)];
}
public void setBoundingBox()
{
double bounds[] = getBounds();
boundingBox.setBounds(posX + bounds[0], posY + bounds[1], posZ + bounds[2], posX + bounds[3], posY + bounds[4], posZ + bounds[5]);
}
public ForgeDirection getDirection()
{
return ForgeDirection.getOrientation(getDataWatcher().getWatchableObjectInt(ID_DIR));
}
public void setDirection(ForgeDirection dir)
{
getDataWatcher().updateObject(ID_DIR, new Integer(dir.ordinal()));
}
public void setRotation(int rotation)
{
getDataWatcher().updateObject(ID_ROT, new Integer(rotation));
}
public void rotate()
{
int rotation = getRotation();
setRotation(++rotation & 3);
}
public int getRotation()
{
return getDataWatcher().getWatchableObjectInt(ID_ROT);
}
public void setDye(String dye)
{
getDataWatcher().updateObject(ID_DYE, new String(dye));
}
public String getDye()
{
return getDataWatcher().getWatchableObjectString(ID_DYE);
}
public void setTile(String tile)
{
getDataWatcher().updateObject(ID_TILE, new String(tile));
}
public String getTile()
{
return getDataWatcher().getWatchableObjectString(ID_TILE);
}
/**
* Sets next tile design.
*/
private void setNextIcon()
{
setTile(TileHandler.getNext(getTile()));
}
/**
* Sets previous tile design.
*/
private void setPrevIcon()
{
setTile(TileHandler.getPrev(getTile()));
}
public IIcon getIcon()
{
if (getTile().equals(getDefaultTile())) {
return IconRegistry.icon_blank_tile;
} else {
int idx = TileHandler.tileList.indexOf(getTile());
if (idx == -1) {
this.setTile(getDefaultTile());
idx = 0;
}
return IconRegistry.icon_tile.get(TileHandler.tileList.indexOf(getTile()));
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
@Override
public void readEntityFromNBT(NBTTagCompound nbtTagCompound)
{
getDataWatcher().updateObject(ID_TILE, String.valueOf(nbtTagCompound.getString(TAG_TILE)));
getDataWatcher().updateObject(ID_DYE, String.valueOf(nbtTagCompound.getString(TAG_DYE)));
getDataWatcher().updateObject(ID_DIR, Integer.valueOf(nbtTagCompound.getInteger(TAG_DIR)));
getDataWatcher().updateObject(ID_ROT, Integer.valueOf(nbtTagCompound.getInteger(TAG_ROT)));
super.readEntityFromNBT(nbtTagCompound);
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
@Override
public void writeEntityToNBT(NBTTagCompound nbtTagCompound)
{
nbtTagCompound.setString(TAG_TILE, getDataWatcher().getWatchableObjectString(ID_TILE));
nbtTagCompound.setString(TAG_DYE, getDataWatcher().getWatchableObjectString(ID_DYE));
nbtTagCompound.setInteger(TAG_DIR, getDataWatcher().getWatchableObjectInt(ID_DIR));
nbtTagCompound.setInteger(TAG_ROT, getDataWatcher().getWatchableObjectInt(ID_ROT));
super.writeEntityToNBT(nbtTagCompound);
}
/**
* Called when this entity is broken. Entity parameter may be null.
*/
public void onBroken(Entity entity)
{
if (entity instanceof EntityPlayer) {
EntityPlayer entityPlayer = (EntityPlayer) entity;
ItemStack itemStack = entityPlayer.getHeldItem();
boolean hasHammer = false;
if (itemStack != null) {
Item item = itemStack.getItem();
if (item instanceof ICarpentersHammer) {
hasHammer = true;
}
}
if (entityPlayer.capabilities.isCreativeMode && !hasHammer) {
return;
}
}
entityDropItem(getItemDrop(), 0.0F);
}
/**
* Called to update the entity's position/logic.
*/
@Override
public void onUpdate()
{
if (!boundsSet) {
setBoundingBox();
boundsSet = true;
}
if (!worldObj.isRemote) {
if (ticks++ >= 20) {
ticks = 0;
if (!isDead && !onValidSurface()) {
setDead();
onBroken((Entity)null);
}
}
}
}
/**
* Returns representative ItemStack for entity.
*/
private ItemStack getItemDrop()
{
return new ItemStack(ItemRegistry.itemCarpentersTile);
}
/**
* Called when a user uses the creative pick block button on this entity.
*
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, Null if nothing should be added.
*/
@Override
public ItemStack getPickedResult(MovingObjectPosition target)
{
return getItemDrop();
}
@Override
public boolean shouldRenderInPass(int pass)
{
// TODO: Switch to pass 1 when alpha rendering is fixed.
return pass == 0;
}
/**
* Returns true if tile is on a valid surface.
*/
public boolean onValidSurface()
{
ForgeDirection dir = getDirection();
int x_offset = MathHelper.floor_double(posX) - dir.offsetX;
int y_offset = MathHelper.floor_double(posY) - dir.offsetY;
int z_offset = MathHelper.floor_double(posZ) - dir.offsetZ;
Block block = worldObj.getBlock(x_offset, y_offset, z_offset);
return !(block != null && !block.isSideSolid(worldObj, x_offset, y_offset, z_offset, dir));
}
/**
* Called when the entity is attacked.
*/
@Override
public boolean attackEntityFrom(DamageSource damageSource, float par2)
{
if (!worldObj.isRemote) {
Entity entity = damageSource.getEntity();
boolean dropItem = false;
if (entity instanceof EntityPlayer) {
EntityPlayer entityPlayer = (EntityPlayer) entity;
ItemStack itemStack = entityPlayer.getHeldItem();
if (itemStack != null) {
if (itemStack.getItem() instanceof ICarpentersHammer) {
if (entity.isSneaking()) {
if (!isDead) {
dropItem = true;
}
} else {
setNextIcon();
}
} else {
if (!isDead) {
dropItem = true;
}
}
} else if (entityPlayer.capabilities.isCreativeMode) {
dropItem = true;
}
}
playTileSound();
if (dropItem)
{
setDead();
setBeenAttacked();
onBroken(damageSource.getEntity());
return true;
}
}
return false;
}
@Override
/**
* First layer of player interaction.
*/
public boolean interactFirst(EntityPlayer entityPlayer)
{
if (worldObj.isRemote) {
return true;
} else if (PlayerPermissions.canPlayerEdit(this, (int) Math.floor(posX), (int) Math.floor(posY), (int) Math.floor(posZ), entityPlayer)) {
ItemStack itemStack = entityPlayer.getHeldItem();
if (itemStack != null) {
if (itemStack.getItem() instanceof ICarpentersHammer) {
if (entityPlayer.isSneaking()) {
rotate();
} else {
setPrevIcon();
}
playTileSound();
} else if (BlockProperties.isDye(itemStack, true)) {
setDye(DyeHandler.getDyeName(itemStack));
playDyeSound();
}
return true;
}
}
return false;
}
/**
* Tries to moves the entity by the passed in displacement. Args: x, y, z
*/
@Override
public void moveEntity(double x, double y, double z)
{
if (!worldObj.isRemote && !isDead && x * x + y * y + z * z > 0.0D)
{
setDead();
onBroken((Entity)null);
}
}
/**
* Adds to the current velocity of the entity. Args: x, y, z
*/
@Override
public void addVelocity(double x, double y, double z)
{
if (!worldObj.isRemote && !isDead && x * x + y * y + z * z > 0.0D)
{
setDead();
onBroken((Entity)null);
}
}
@Override
protected void entityInit()
{
super.entityInit();
getDataWatcher().addObject(ID_TILE, new String("blank"));
getDataWatcher().addObject(ID_DYE, new String("dyeWhite"));
getDataWatcher().addObject(ID_DIR, new Integer(0));
getDataWatcher().addObject(ID_ROT, new Integer(0));
}
/**
* Returns true if other Entities should be prevented from moving through this Entity.
*/
@Override
public boolean canBeCollidedWith()
{
return true;
}
/**
* returns the bounding box for this entity
*/
@Override
public AxisAlignedBB getBoundingBox()
{
return boundingBox;
}
@Override
public float getCollisionBorderSize()
{
return 0.0F;
}
@Override
protected boolean shouldSetPosAfterLoading()
{
return false;
}
} |
package net.sf.farrago.db;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.util.logging.*;
import javax.jmi.reflect.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.ddl.*;
import net.sf.farrago.fem.config.*;
import net.sf.farrago.fem.fennel.*;
import net.sf.farrago.fem.sql2003.*;
import net.sf.farrago.fennel.*;
import net.sf.farrago.namespace.*;
import net.sf.farrago.ojrex.*;
import net.sf.farrago.plugin.*;
import net.sf.farrago.query.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.session.*;
import net.sf.farrago.trace.*;
import net.sf.farrago.util.*;
import org.eigenbase.oj.rex.*;
import org.eigenbase.rel.*;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.validate.*;
import org.eigenbase.trace.*;
import org.eigenbase.util.*;
import org.eigenbase.util.property.*;
import org.netbeans.mdr.handlers.*;
/**
* FarragoDatabase is a top-level singleton representing an instance of a
* Farrago database engine.
*
* <p>NOTE jvs 14-Dec-2005: FarragoDatabase inherits from FarragoDbSingleton for
* backwards compatibility. This tie may eventually be severed so that multiple
* instances of FarragoDatabase can be created in the same JVM.
*
* @author John V. Sichi
* @version $Id$
*/
public class FarragoDatabase
extends FarragoDbSingleton
{
// TODO jvs 11-Aug-2004: Get rid of this once corresponding TODO in
// FarragoDbSession.prepare is resolved.
public static final Object DDL_LOCK = new Integer(1994);
private FarragoRepos systemRepos;
private FarragoRepos userRepos;
private FennelDbHandle fennelDbHandle;
private OJRexImplementorTable ojRexImplementorTable;
protected FarragoSessionFactory sessionFactory;
private FarragoPluginClassLoader pluginClassLoader;
private List<FarragoSessionModelExtension> modelExtensions;
private FarragoDdlLockManager ddlLockManager;
private FarragoSessionTxnMgr txnMgr;
/**
* Cache of all sorts of stuff.
*/
private FarragoObjectCache codeCache;
/**
* Cache of FarragoMedDataWrappers.
*/
private FarragoObjectCache dataWrapperCache;
/**
* File containing trace configuration.
*/
private File traceConfigFile;
/**
* Provides unique identifiers for sessions and statements.
*/
private AtomicLong uniqueId = new AtomicLong(1);
/**
* Creates a <code>FarragoDatabase</code>.
*
* @param sessionFactory factory for various database-level objects
* @param init whether to initialize the system catalog (the first time the
* database is started)
*/
public FarragoDatabase(
FarragoSessionFactory sessionFactory,
boolean init)
{
if (instance == null) {
instance = this;
}
try {
FarragoCompoundAllocation startOfWorldAllocation =
new FarragoCompoundAllocation();
this.addAllocation(startOfWorldAllocation);
StringProperty prop = FarragoProperties.instance().traceConfigFile;
String loggingConfigFile = prop.get();
if (loggingConfigFile == null) {
throw FarragoResource.instance().MissingHomeProperty.ex(
prop.getPath());
}
traceConfigFile = new File(loggingConfigFile);
dumpTraceConfig();
this.sessionFactory = sessionFactory;
// Tell MDR about our plugin ClassLoader so that it can find
// extension model JMI interfaces in plugin jars.
pluginClassLoader = new FarragoPluginClassLoader();
BaseObjectHandler.setClassLoaderProvider(
new ClassLoaderProvider() {
public ClassLoader getClassLoader()
{
return pluginClassLoader;
}
public Class defineClass(
String className,
byte [] classfile)
{
return null;
}
});
// Load all model plugin URL's early so that MDR won't try to
// generate its own bytecode for JMI interfaces.
loadBootUrls();
systemRepos = sessionFactory.newRepos(this, false);
userRepos = systemRepos;
if (init) {
FarragoCatalogInit.createSystemObjects(systemRepos);
}
// REVIEW: system/user configuration
FemFarragoConfig currentConfig = systemRepos.getCurrentConfig();
tracer.config(
"java.class.path = "
+ System.getProperty("java.class.path"));
tracer.config(
"java.library.path = "
+ System.getProperty("java.library.path"));
if (systemRepos.isFennelEnabled()) {
systemRepos.beginReposTxn(true);
try {
loadFennel(
startOfWorldAllocation,
sessionFactory.newFennelCmdExecutor(),
init);
} finally {
systemRepos.endReposTxn(false);
}
} else {
tracer.config("Fennel support disabled");
}
long codeCacheMaxBytes = getCodeCacheMaxBytes(currentConfig);
codeCache = new FarragoObjectCache(this, codeCacheMaxBytes);
// TODO: parameter for cache size limit
dataWrapperCache = new FarragoObjectCache(this, Long.MAX_VALUE);
ojRexImplementorTable =
new FarragoOJRexImplementorTable(
SqlStdOperatorTable.instance());
// Create instances of plugin model extensions for shared use
// by all sessions.
loadModelPlugins();
// REVIEW: sequencing from this point on
if (currentConfig.isUserCatalogEnabled()) {
userRepos = sessionFactory.newRepos(this, true);
if (userRepos.getSelfAsCatalog() == null) {
// REVIEW: request this explicitly?
FarragoCatalogInit.createSystemObjects(userRepos);
}
// During shutdown, we want to reverse this process, making
// userRepos revert to systemRepos. ReposSwitcher takes
// care of this before userRepos gets closed.
addAllocation(new ReposSwitcher());
}
// Start up timer. This comes last so that the first thing we do
// in close is to cancel it, avoiding races with other shutdown
// activity.
Timer timer = new Timer();
new FarragoTimerAllocation(this, timer);
timer.schedule(
new WatchdogTask(),
1000,
1000);
if (currentConfig.getCheckpointInterval() > 0) {
long checkpointIntervalMillis =
currentConfig.getCheckpointInterval();
checkpointIntervalMillis *= 1000;
timer.schedule(
new CheckpointTask(),
checkpointIntervalMillis,
checkpointIntervalMillis);
}
ddlLockManager = new FarragoDdlLockManager();
txnMgr = sessionFactory.newTxnMgr();
sessionFactory.specializedInitialization(this);
} catch (Throwable ex) {
tracer.throwing("FarragoDatabase", "<init>", ex);
close(true);
throw FarragoResource.instance().DatabaseLoadFailed.ex(ex);
}
}
/**
* @return the shared code cache for this database
*/
public FarragoObjectCache getCodeCache()
{
return codeCache;
}
/**
* @return the shared data wrapper cache for this database
*/
public FarragoObjectCache getDataWrapperCache()
{
return dataWrapperCache;
}
/**
* @return ClassLoader for loading plugins
*/
public FarragoPluginClassLoader getPluginClassLoader()
{
return pluginClassLoader;
}
/**
* @return list of installed {@link FarragoSessionModelExtension} instances
*/
public List<FarragoSessionModelExtension> getModelExtensions()
{
return modelExtensions;
}
/**
* @return transaction manager for this database
*/
public FarragoSessionTxnMgr getTxnMgr()
{
return txnMgr;
}
private File getBootUrlFile()
{
return
new File(
FarragoProperties.instance().getCatalogDir(),
"FarragoBootUrls.lst");
}
private void loadBootUrls()
{
FileReader fileReader;
try {
fileReader = new FileReader(getBootUrlFile());
} catch (FileNotFoundException ex) {
// if file doesn't exist, it's safe to assume that there
// are no model plugins yet
return;
}
LineNumberReader lineReader = new LineNumberReader(fileReader);
try {
for (;;) {
String line = lineReader.readLine();
if (line == null) {
break;
}
URL url =
new URL(
FarragoProperties.instance().expandProperties(line));
pluginClassLoader.addPluginUrl(url);
}
} catch (Throwable ex) {
throw FarragoResource.instance().CatalogBootUrlReadFailed.ex(ex);
}
}
void saveBootUrl(String url)
{
// append
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(
getBootUrlFile(),
true);
PrintWriter pw = new PrintWriter(fileWriter);
pw.println(url);
pw.close();
fileWriter.close();
} catch (Throwable ex) {
throw FarragoResource.instance().CatalogBootUrlUpdateFailed.ex(ex);
} finally {
Util.squelchWriter(fileWriter);
}
}
private void loadModelPlugins()
{
List resourceBundles = new ArrayList();
sessionFactory.defineResourceBundles(resourceBundles);
modelExtensions = new ArrayList<FarragoSessionModelExtension>();
Collection<FemJar> allJars = systemRepos.allOfClass(FemJar.class);
for (FemJar jar : allJars) {
if (jar.isModelExtension()) {
FarragoSessionModelExtension modelExtension =
sessionFactory.newModelExtension(
pluginClassLoader,
jar);
modelExtensions.add(modelExtension);
modelExtension.defineResourceBundles(resourceBundles);
}
}
// add repository localization for model extensions
systemRepos.addResourceBundles(resourceBundles);
}
public void close(boolean suppressExcns)
{
try {
// This will close (in reverse order) all the FarragoAllocations
// opened by the constructor.
closeAllocation();
assertNoFennelHandles();
} catch (Throwable ex) {
warnOnClose(ex, suppressExcns);
}
fennelDbHandle = null;
systemRepos = null;
userRepos = null;
}
private void warnOnClose(
Throwable ex,
boolean suppressExcns)
{
tracer.warning(
"Caught " + ex.getClass().getName()
+ " during database shutdown:" + ex.getMessage());
if (!suppressExcns) {
tracer.log(Level.SEVERE, "warnOnClose", ex);
tracer.throwing("FarragoDatabase", "warnOnClose", ex);
throw Util.newInternal(ex);
}
}
private void dumpTraceConfig()
{
try {
FileReader fileReader = new FileReader(traceConfigFile);
StringWriter stringWriter = new StringWriter();
FarragoUtil.copyFromReaderToWriter(fileReader, stringWriter);
tracer.config(stringWriter.toString());
} catch (IOException ex) {
tracer.severe(
"Caught IOException while dumping trace configuration: "
+ ex.getMessage());
}
}
private void assertNoFennelHandles()
{
assert systemRepos != null : "FarragoDatabase.systemRepos is "
+ "null: server has probably already been started";
if (!systemRepos.isFennelEnabled()) {
return;
}
int n = FennelStorage.getHandleCount();
assert (n == 0) : "FennelStorage.getHandleCount() == " + n;
}
private void loadFennel(
FarragoCompoundAllocation startOfWorldAllocation,
FennelCmdExecutor cmdExecutor,
boolean init)
{
tracer.fine("Loading Fennel");
assertNoFennelHandles();
FemCmdOpenDatabase cmd = systemRepos.newFemCmdOpenDatabase();
FemFennelConfig fennelConfig =
systemRepos.getCurrentConfig().getFennelConfig();
Map attributeMap = JmiUtil.getAttributeValues(fennelConfig);
sessionFactory.applyFennelExtensionParameters(attributeMap);
FemDatabaseParam param;
Iterator iter = attributeMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String expandedValue =
FarragoProperties.instance().expandProperties(
entry.getValue().toString());
param = systemRepos.newFemDatabaseParam();
param.setName(entry.getKey().toString());
param.setValue(expandedValue);
cmd.getParams().add(param);
}
// databaseDir is set dynamically, allowing the catalog
// to be moved
param = systemRepos.newFemDatabaseParam();
param.setName("databaseDir");
param.setValue(
FarragoProperties.instance().getCatalogDir().getAbsolutePath());
cmd.getParams().add(param);
iter = cmd.getParams().iterator();
while (iter.hasNext()) {
param = (FemDatabaseParam) iter.next();
// REVIEW: use Fennel tracer instead?
tracer.config(
"Fennel parameter " + param.getName() + "="
+ param.getValue());
}
cmd.setCreateDatabase(init);
NativeTrace.createInstance("net.sf.fennel.");
fennelDbHandle =
new FennelDbHandle(systemRepos,
systemRepos,
this,
cmdExecutor,
cmd);
tracer.config("Fennel successfully loaded");
}
/**
* @return shared OpenJava implementation table for SQL operators
*/
public OJRexImplementorTable getOJRexImplementorTable()
{
return ojRexImplementorTable;
}
/**
* @return system repos for this database
*/
public FarragoRepos getSystemRepos()
{
return systemRepos;
}
/**
* @return user repos for this database
*/
public FarragoRepos getUserRepos()
{
return userRepos;
}
/**
* @return the Fennel database handle associated with this database
*/
public FennelDbHandle getFennelDbHandle()
{
return fennelDbHandle;
}
/**
* @return the DDL lock manager associated with this database
*/
public FarragoDdlLockManager getDdlLockManager()
{
return ddlLockManager;
}
/**
* Gets a unique identifier: never 0.
*
* @return next unique identifier
*/
public long getUniqueId()
{
return uniqueId.incrementAndGet();
}
// REVIEW mberkowitz 28-Mar-06: Is it better for the FarragoDatabase
// to save a map (id -> FarragoSessionInfo)
// and a map (id -> FarragoSessionExecutingStmtInfo)?
/**
* look up session info by session id.
*
* @param id
*
* @return FarragoSessionInfo
*/
public FarragoSessionInfo findSessionInfo(long id)
{
for (FarragoSession s : getSessions(this)) {
FarragoSessionInfo info = s.getSessionInfo();
if (info.getId() == id) {
return info;
}
}
return null;
}
/**
* look up executing statement info by statement id.
*
* @param id
*
* @return FarragoSessionExecutingStmtInfo
*/
public FarragoSessionExecutingStmtInfo findExecutingStmtInfo(long id)
{
for (FarragoSession s : getSessions(this)) {
FarragoSessionExecutingStmtInfo info =
s.getSessionInfo().getExecutingStmtInfo(id);
if (info != null) {
return info;
}
}
return null;
}
/**
* Kill a farrago session.
*
* @param id session identifier
*/
public void killSession(long id)
throws Throwable
{
tracer.info("killSession " + id);
FarragoSessionInfo info = findSessionInfo(id);
if (info == null) {
throw FarragoResource.instance().SessionNotFound.ex(id);
}
FarragoDbSession target = (FarragoDbSession) info.getSession();
if (target.isClosed()) {
tracer.info("killSession " + id + ": already closed");
return;
}
target.kill();
}
private void kill(FarragoSessionExecutingStmtInfo info)
throws Throwable
{
FarragoSessionStmtContext stmt = info.getStmtContext();
if (stmt == null) {
Long id = info.getId();
tracer.info("killExecutingStmt " + id + ": statement not found");
throw new Throwable("executing statement not found: " + id); // i18n
}
if (tracer.isLoggable(Level.INFO)) {
tracer.info(
"killStatement " + info.getId()
+ "(session " + stmt.getSession().getSessionInfo().getId()
+ "), "
+ stmt.getSql());
}
stmt.cancel();
stmt.unprepare();
}
/**
* Kill an executing statement: cancel it and deallocate it.
*
* @param id statement id
*/
public void killExecutingStmt(long id)
throws Throwable
{
tracer.info("killExecutingStmt " + id);
FarragoSessionExecutingStmtInfo info = findExecutingStmtInfo(id);
if (info == null) {
tracer.info("killExecutingStmt " + id + ": statement not found");
throw new Throwable("executing statement not found: " + id); // i18n
}
kill(info);
}
/**
* Kills all statements that are executing SQL that matches a given pattern,
* but does not match a second pattern. Not an error if none match.
*
* @param match pattern to match. Null string matches nothing, to be safe.
* @param nomatch pattern not to match
*
* @return count of killed statements.
*/
public int killExecutingStmtMatching(String match, String nomatch)
throws Throwable
{
int ct = 0;
tracer.info(
"killExecutingStmtMatching " + match + " but not " + nomatch);
// scan all statements
if (match.length() > 0) {
for (FarragoSession sess : getSessions(this)) {
FarragoSessionInfo sessInfo = sess.getSessionInfo();
for (Long id : sessInfo.getExecutingStmtIds()) {
FarragoSessionExecutingStmtInfo info =
sessInfo.getExecutingStmtInfo(id);
if (info.getSql().contains(nomatch)) {
continue;
}
if (info.getSql().contains(match)) {
kill(info);
ct++;
}
}
}
}
tracer.info("killed " + ct + " statements");
return ct;
}
/**
* Prepares an SQL expression; uses a cached implementation if available,
* otherwise caches the one generated here.
*
* @param stmtContext embracing stmt context
*
* @param stmtValidator generic stmt validator
* @param sqlNode the parsed form of the statement
* @param owner the FarragoAllocationOwner which will be responsible for the
* returned stmt
* @param analyzedSql receives information about a prepared expression
*
* @return statement implementation, or null when analyzedSql is non-null
*/
public FarragoSessionExecutableStmt prepareStmt(
FarragoSessionStmtContext stmtContext,
FarragoSessionStmtValidator stmtValidator,
SqlNode sqlNode,
FarragoAllocationOwner owner,
FarragoSessionAnalyzedSql analyzedSql)
{
final FarragoSessionPreparingStmt stmt =
stmtValidator.getSession().getPersonality().newPreparingStmt(
stmtContext, stmtValidator);
return prepareStmtImpl(stmt, sqlNode, owner, analyzedSql);
}
/**
* Implements a logical or physical query plan but does not execute it.
*
* @param prep the FarragoSessionPreparingStmt that is managing the query.
* @param rootRel root of query plan (relational expression)
* @param sqlKind SqlKind for the relational expression: only
* SqlKind.Explain and SqlKind.Dml are special cases.
* @param logical true for a logical query plan (still needs to be
* optimized), false for a physical plan.
* @param owner the FarragoAllocationOwner which will be responsible for the
* returned stmt
*
* @return statement implementation
*/
public FarragoSessionExecutableStmt implementStmt(
FarragoSessionPreparingStmt prep,
RelNode rootRel,
SqlKind sqlKind,
boolean logical,
FarragoAllocationOwner owner)
{
try {
FarragoSessionExecutableStmt executable =
prep.implement(rootRel, sqlKind, logical);
owner.addAllocation(executable);
return executable;
} finally {
prep.closeAllocation();
}
}
private FarragoSessionExecutableStmt prepareStmtImpl(
final FarragoSessionPreparingStmt stmt,
final SqlNode sqlNode,
FarragoAllocationOwner owner,
FarragoSessionAnalyzedSql analyzedSql)
{
final EigenbaseTimingTracer timingTracer =
stmt.getStmtValidator().getTimingTracer();
// REVIEW jvs 27-Aug-2005: what are the security implications of
// EXPLAIN PLAN?
// It would be silly to cache EXPLAIN PLAN results, so deal with them
// directly.
if (sqlNode.isA(SqlKind.Explain)) {
FarragoSessionExecutableStmt executableStmt =
stmt.prepare(sqlNode, sqlNode);
owner.addAllocation(executableStmt);
return executableStmt;
}
// Use unparsed validated SQL as cache key. This eliminates trivial
// differences such as whitespace and implicit qualifiers.
SqlValidator sqlValidator = stmt.getSqlValidator();
final SqlNode validatedSqlNode;
if ((analyzedSql != null) && (analyzedSql.paramRowType != null)) {
Map nameToTypeMap = new HashMap();
for (RelDataTypeField field
: analyzedSql.paramRowType.getFieldList()) {
nameToTypeMap.put(
field.getName(),
field.getType());
}
validatedSqlNode =
sqlValidator.validateParameterizedExpression(
sqlNode,
nameToTypeMap);
} else {
validatedSqlNode = sqlValidator.validate(sqlNode);
}
stmt.postValidate(validatedSqlNode);
timingTracer.traceTime("end validation");
SqlDialect sqlDialect =
new SqlDialect(stmt.getSession().getDatabaseMetaData());
final String sql = validatedSqlNode.toSqlString(sqlDialect);
if (analyzedSql != null) {
if (validatedSqlNode instanceof SqlSelect) {
// assume we're validating a view
SqlSelect select = (SqlSelect) validatedSqlNode;
if (select.getOrderList() != null) {
analyzedSql.hasTopLevelOrderBy = true;
}
}
// Need to force preparation so we can dig out required info, so
// don't use cache. Also, don't need to go all the way with
// stmt implementation either; can stop after validation, which
// provides needed metadata. (In fact, we CAN'T go much further,
// because if a view is being created as part of a CREATE SCHEMA
// statement, some of the tables it depends on may not have
// storage defined yet.)
analyzedSql.canonicalString = sql;
stmt.analyzeSql(validatedSqlNode, analyzedSql);
timingTracer.traceTime("end analyzeSql");
return null;
}
FarragoObjectCache.Entry cacheEntry;
FarragoObjectCache.CachedObjectFactory stmtFactory =
new FarragoObjectCache.CachedObjectFactory() {
public void initializeEntry(
Object key,
FarragoObjectCache.UninitializedEntry entry)
{
timingTracer.traceTime("code cache miss");
assert (key.equals(sql));
FarragoSessionExecutableStmt executableStmt =
stmt.prepare(validatedSqlNode, sqlNode);
long memUsage =
FarragoUtil.getStringMemoryUsage(sql)
+ executableStmt.getMemoryUsage();
entry.initialize(executableStmt, memUsage);
}
};
FarragoSessionExecutableStmt executableStmt;
do {
// prepare the statement, caching the results in codeCache
cacheEntry = codeCache.pin(sql, stmtFactory, false);
executableStmt =
(FarragoSessionExecutableStmt) cacheEntry.getValue();
// Sometimes the implementation of a statement cannot be shared, and
// must not be cached. Test this when the statement is prepared, and
// so already in the cache.
if (!stmt.mayCacheImplementation()) {
codeCache.detach(cacheEntry);
// does not close the FarragoSessionExecutableStmt
cacheEntry = null;
} else if (isStale(
stmt.getRepos(),
executableStmt)) {
cacheEntry.closeAllocation();
codeCache.discard(sql); // closes the
// FarragoSessionExecutableStmt
cacheEntry = null;
executableStmt = null;
}
} while (executableStmt == null);
if (cacheEntry != null) {
owner.addAllocation(cacheEntry);
} else {
owner.addAllocation(executableStmt);
}
return executableStmt;
}
private boolean isStale(
FarragoRepos repos,
FarragoSessionExecutableStmt stmt)
{
Iterator idIter = stmt.getReferencedObjectIds().iterator();
while (idIter.hasNext()) {
String mofid = (String) idIter.next();
RefBaseObject obj = repos.getMdrRepos().getByMofId(mofid);
if (obj == null) {
// TODO jvs 17-July-2004: Once we support ALTER TABLE, this
// won't be good enough. In addition to checking that the
// object still exists, we'll need to verify that its version
// number is the same as it was at the time stmt was prepared.
return true;
}
}
return false;
}
public void updateSystemParameter(DdlSetSystemParamStmt ddlStmt)
{
// TODO: something cleaner
boolean setCodeCacheSize = false;
String paramName = ddlStmt.getParamName();
if (paramName.equals("calcVirtualMachine")) {
// sanity check
if (!userRepos.isFennelEnabled()) {
CalcVirtualMachine vm =
userRepos.getCurrentConfig().getCalcVirtualMachine();
if (vm.equals(CalcVirtualMachineEnum.CALCVM_FENNEL)) {
throw FarragoResource.instance().ValidatorCalcUnavailable
.ex();
}
}
// when this parameter changes, we need to clear the code cache,
// since cached plans may be based on the old setting
codeCache.setMaxBytes(0);
// this makes sure that we reset the cache to the correct size
// below
setCodeCacheSize = true;
}
if (paramName.equals("codeCacheMaxBytes")) {
setCodeCacheSize = true;
}
if (setCodeCacheSize) {
codeCache.setMaxBytes(
getCodeCacheMaxBytes(systemRepos.getCurrentConfig()));
}
if (paramName.equals("cachePagesInit") ||
paramName.equals("expectedConcurrentStatements") ||
paramName.equals("cacheReservePercentage")) {
executeFennelSetParam(paramName, ddlStmt.getParamValue());
}
}
private long getCodeCacheMaxBytes(FemFarragoConfig config)
{
long codeCacheMaxBytes = config.getCodeCacheMaxBytes();
if (codeCacheMaxBytes == -1) {
codeCacheMaxBytes = Long.MAX_VALUE;
}
return codeCacheMaxBytes;
}
private void executeFennelSetParam(String paramName, SqlLiteral paramValue)
{
if (!systemRepos.isFennelEnabled()) {
return;
}
systemRepos.beginTransientTxn();
try {
FemCmdSetParam cmd = systemRepos.newFemCmdSetParam();
cmd.setDbHandle(fennelDbHandle.getFemDbHandle(systemRepos));
FemDatabaseParam param = systemRepos.newFemDatabaseParam();
param.setName(paramName);
param.setValue(paramValue.toString());
cmd.setParam(param);
fennelDbHandle.executeCmd(cmd);
} finally {
systemRepos.endTransientTxn();
}
}
public void requestCheckpoint(
boolean fuzzy,
boolean async)
{
if (!systemRepos.isFennelEnabled()) {
return;
}
systemRepos.beginTransientTxn();
try {
FemCmdCheckpoint cmd = systemRepos.newFemCmdCheckpoint();
cmd.setDbHandle(fennelDbHandle.getFemDbHandle(systemRepos));
cmd.setFuzzy(fuzzy);
cmd.setAsync(async);
fennelDbHandle.executeCmd(cmd);
} finally {
systemRepos.endTransientTxn();
}
}
/**
* Main entry point which creates a new Farrago database.
*
* @param args ignored
*/
public static void main(String [] args)
{
FarragoDatabase database =
new FarragoDatabase(
new FarragoDbSessionFactory(),
true);
database.close(false);
}
/**
* 1 Hz task for background activities. Currently all it does is re-read the
* trace configuration file whenever it changes.
*/
private class WatchdogTask
extends TimerTask
{
private long prevTraceConfigTimestamp;
WatchdogTask()
{
prevTraceConfigTimestamp = traceConfigFile.lastModified();
}
// implement Runnable
public void run()
{
long traceConfigTimestamp = traceConfigFile.lastModified();
if (traceConfigTimestamp == 0) {
return;
}
if (traceConfigTimestamp > prevTraceConfigTimestamp) {
prevTraceConfigTimestamp = traceConfigTimestamp;
tracer.config("Reading modified trace configuration file");
try {
LogManager.getLogManager().readConfiguration();
} catch (IOException ex) {
// REVIEW: do more? There's a good chance this will end
// up in /dev/null.
tracer.severe(
"Caught IOException while updating "
+ "trace configuration: " + ex.getMessage());
}
dumpTraceConfig();
}
}
}
private class CheckpointTask
extends TimerTask
{
// implement Runnable
public void run()
{
requestCheckpoint(true, true);
}
}
private class ReposSwitcher
implements FarragoAllocation
{
public void closeAllocation()
{
userRepos = systemRepos;
}
}
}
// End FarragoDatabase.java |
package com.coshx.drekkar;
import android.webkit.WebView;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @class EventBus
* @brief In charge of watching a subscriber / webview pair. If any event is captured, it forwards
* it to dispatcher (except init one). Argument passed as well when whenReady callback is run.
*/
public class EventBus implements IWebViewJSEndpoint {
private class Initializer {
WhenReady callback;
Boolean inBackground;
Initializer(WhenReady callback, Boolean inBackground) {
this.callback = callback;
this.inBackground = inBackground;
}
}
private final Object initializationLock = new Object();
private final Object subscriberLock = new Object();
private WeakReference<Object> reference;
private WeakReference<WebView> webView;
private WeakReference<Drekkar> dispatcher;
/**
* Bus subscribers
*/
private List<EventSubscriber> subscribers;
/**
* Denotes if the bus has received init event from JS
*/
private Boolean isInitialized;
/**
* Pending initialization subscribers
*/
private List<Initializer> initializers;
// Buffer to save initializers temporary, in order to prevent them from being garbage collected
private Map<Integer, Initializer> onGoingInitializers;
private int onGoingInitializersId;
EventBus(Drekkar dispatcher, Object reference, WebView webView) {
this.dispatcher = new WeakReference<Drekkar>(dispatcher);
this.reference = new WeakReference<Object>(reference);
this.webView = new WeakReference<WebView>(webView);
this.isInitialized = false;
this.subscribers = new ArrayList<>();
this.initializers = new ArrayList<>();
this.onGoingInitializers = new HashMap<>();
this.onGoingInitializersId = 0;
WebViewJSEndpoint.subscribe(webView, this);
}
Object getReference() {
return reference.get();
}
WebView getWebView() {
return webView.get();
}
/**
* Runs JS script into current context
*/
void forwardToJS(final String toRun) {
ThreadingHelper.main(
new Runnable() {
@Override
public void run() {
WebView w = webView.get();
if (w != null) {
w.loadUrl("javascript:" + toRun);
}
}
}
);
}
/**
* Allows dispatcher to fire any event on this bus
*/
void raise(final String name, final Object data) {
synchronized (subscriberLock) {
for (EventSubscriber s : subscribers) {
final EventSubscriber finalS = s;
if (s.name.equals(name)) {
Runnable action = new Runnable() {
@Override
public void run() {
finalS.callback.run(name, data);
}
};
if (finalS.inBackground) {
ThreadingHelper.background(action);
} else {
ThreadingHelper.main(action);
}
}
}
}
}
void whenReady(final WhenReady callback) {
ThreadingHelper.background(
new Runnable() {
@Override
public void run() {
if (isInitialized) {
ThreadingHelper.background(
new Runnable() {
@Override
public void run() {
callback.run(EventBus.this);
}
}
);
} else {
synchronized (initializationLock) {
if (isInitialized) {
ThreadingHelper.background(
new Runnable() {
@Override
public void run() {
callback.run(EventBus.this);
}
}
);
} else {
initializers.add(new Initializer(callback, true));
}
}
}
}
}
);
}
void whenReadyOnMain(final WhenReady callback) {
ThreadingHelper.background(
new Runnable() {
@Override
public void run() {
if (isInitialized) {
ThreadingHelper.main(
new Runnable() {
@Override
public void run() {
callback.run(EventBus.this);
}
}
);
} else {
synchronized (initializationLock) {
if (isInitialized) {
ThreadingHelper.main(
new Runnable() {
@Override
public void run() {
callback.run(EventBus.this);
}
}
);
} else {
initializers.add(new Initializer(callback, false));
}
}
}
}
}
);
}
@Override
public void handle(String busName, String eventName, String data) {
// All buses are notified about that incoming event. Then, each bus has to investigate first if it
// is a potential receiver
if (dispatcher.get() != null && dispatcher.get().getName().equals(busName)) {
if (eventName.equals("DrekkarInit") && !isInitialized) { // Reserved event name.
// Triggers whenReady
// Initialization must be run on the main thread. Otherwise, some events would be triggered before onReady
// has been run and hence be lost.
isInitialized = true;
for (Initializer i : initializers) {
final int index = onGoingInitializersId;
final WhenReady callback = i.callback;
Runnable action = new Runnable() {
@Override
public void run() {
callback.run(EventBus.this);
onGoingInitializers.remove(index);
}
};
onGoingInitializers.put(index, i);
onGoingInitializersId++;
if (i.inBackground) {
ThreadingHelper.background(action);
} else {
ThreadingHelper.main(action);
}
}
initializers = new ArrayList<>();
} else {
if (dispatcher.get() != null) {
dispatcher.get().dispatch(new Arguments(busName, eventName, data));
}
}
}
}
/**
* Posts event
*
* @param eventName Event's name
*/
public void post(String eventName) {
if (dispatcher.get() != null) {
dispatcher.get().post(eventName, null);
}
}
/**
* Posts event with extra data
*
* @param eventName Event's name
* @param data Data to post (see documentation for supported types)
*/
public <T> void post(String eventName, T data) {
if (dispatcher.get() != null) {
dispatcher.get().post(eventName, data);
}
}
/**
* Subscribes to event. Callback is run with the event's name and extra data (if any).
*
* @param eventName Event to watch
* @param callback Action to run when fired
*/
public void register(String eventName, Callback callback) {
synchronized (subscriberLock) {
subscribers.add(new EventSubscriber(eventName, callback, true));
}
}
/**
* Subscribes to event. Callback is run on main thread with the event's name and extra data (if
* any).
*
* @param eventName Event to watch
* @param callback Action to run when fired
*/
public void registerOnMain(String eventName, Callback callback) {
synchronized (subscriberLock) {
subscribers.add(new EventSubscriber(eventName, callback, false));
}
}
public void unregister(Object subscriber) {
if (reference.get() != null && subscriber.hashCode() == reference.get().hashCode()) {
dispatcher.get().deleteBus(this);
WebViewJSEndpoint.unsubscribe(webView.get(), this);
reference = new WeakReference<Object>(null);
webView = new WeakReference<WebView>(null);
}
}
} |
package uk.org.ownage.dmdirc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import uk.org.ownage.dmdirc.logger.ErrorLevel;
import uk.org.ownage.dmdirc.logger.Logger;
/**
* Reads/writes the application's config file
* @author chris
*/
public class Config {
/**
* The application's current configuration
*/
private static Properties properties;
/** Disallow creation of a new instance of Config */
private Config() {
}
/**
* Returns the singleton instance of ServerManager
* @return Instance of ServerManager
*/
public static Properties getConfig() {
if (properties == null) {
initialise();
}
return properties;
}
/**
* Returns the full path to the application's config file
* @return config file
*/
private static String getConfigFile() {
return getConfigDir()+"dmdirc.xml";
}
/**
* Returns the application's config directory
* @return configuration directory
*/
public static String getConfigDir() {
String fs = System.getProperty("file.separator");
//This is nasty.
String baseDir = System.getenv("APPDATA");
if (baseDir == null) {
System.getProperty("user.home");
}
//End nasty
return baseDir+fs+".DMDirc"+fs;
}
/**
* Returns the default settings for DMDirc
* @return default settings
*/
private static Properties getDefaults() {
Properties defaults = new Properties();
defaults.setProperty("general.commandchar","/");
defaults.setProperty("general.closemessage","DMDirc exiting");
defaults.setProperty("general.quitmessage","Using DMDirc");
defaults.setProperty("general.partmessage","Using DMDirc");
defaults.setProperty("general.cyclemessage","Cycling");
defaults.setProperty("general.globaldisconnectmessage","true");
// These are temporary until we get identity support
defaults.setProperty("general.defaultnick","DMDircUser");
defaults.setProperty("general.alternatenick","DMDircUser_");
defaults.setProperty("general.server","blueyonder.uk.quakenet.org");
defaults.setProperty("general.port","7000");
defaults.setProperty("general.password","");
defaults.setProperty("ui.backgroundcolour", "0");
defaults.setProperty("ui.foregroundcolour", "1");
defaults.setProperty("ui.maximisewindows","false");
defaults.setProperty("ui.sortByMode", "true");
defaults.setProperty("ui.sortByCase", "false");
defaults.setProperty("ui.inputbuffersize", "50");
defaults.setProperty("ui.showversion", "true");
defaults.setProperty("tabcompletion.casesensitive", "false");
defaults.setProperty("logging.dateFormat","EEE, d MMM yyyy HH:mm:ss Z");
defaults.setProperty("logging.programLogging","true");
defaults.setProperty("logging.debugLogging","true");
defaults.setProperty("logging.debugLoggingSysOut","true");
return defaults;
}
/**
* Determines if the specified option exists
* @return true iff the option exists, false otherwise
* @param domain the domain of the option
* @param option the name of the option
*/
public static boolean hasOption(String domain, String option) {
if (properties == null) {
initialise();
}
return (properties.getProperty(domain+"."+option) != null);
}
/**
* Returns the specified option
* @return the value of the specified option
* @param domain the domain of the option
* @param option the name of the option
*/
public static String getOption(String domain, String option) {
if (properties == null) {
initialise();
}
return properties.getProperty(domain+"."+option);
}
/**
* Sets a specified option
* @param domain domain of the option
* @param option name of the option
* @param value value of the option
*/
public static void setOption(String domain, String option, String value) {
if (properties == null) {
initialise();
}
properties.setProperty(domain+"."+option, value);
}
/**
* Loads the config file from disc, if it exists else initialises defaults
* and creates file
*/
private static void initialise() {
properties = getDefaults();
File file = new File(getConfigFile());
if (file.exists()) {
try {
properties.loadFromXML(new FileInputStream(file));
} catch (InvalidPropertiesFormatException ex) {
Logger.error(ErrorLevel.INFO, ex);
} catch (FileNotFoundException ex) {
//Do nothing, defaults used
} catch (IOException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
} else {
try {
(new File(getConfigDir())).mkdirs();
file.createNewFile();
Config.save();
} catch (IOException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
}
/**
* Saves the config file to disc
*/
public static void save() {
if (properties == null) {
initialise();
}
try {
properties.storeToXML(new FileOutputStream(new File(getConfigFile())), null);
} catch (FileNotFoundException ex) {
Logger.error(ErrorLevel.INFO, ex);
} catch (IOException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
} |
package us.deathmarine.luyten;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.fife.ui.rtextarea.RTextScrollPane;
import com.strobel.assembler.InputTypeLoader;
import com.strobel.assembler.metadata.ITypeLoader;
import com.strobel.assembler.metadata.JarTypeLoader;
import com.strobel.assembler.metadata.MetadataSystem;
import com.strobel.assembler.metadata.TypeDefinition;
import com.strobel.assembler.metadata.TypeReference;
import com.strobel.core.StringUtilities;
import com.strobel.core.VerifyArgument;
import com.strobel.decompiler.DecompilationOptions;
import com.strobel.decompiler.DecompilerSettings;
import com.strobel.decompiler.PlainTextOutput;
/**
* Jar-level model
*/
public class Model extends JSplitPane {
private static final long serialVersionUID = 6896857630400910200L;
private static final long MAX_JAR_FILE_SIZE_BYTES = 1_000_000_000;
private static final long MAX_UNPACKED_FILE_SIZE_BYTES = 1_000_000;
private static LuytenTypeLoader typeLoader = new LuytenTypeLoader();
public static MetadataSystem metadataSystem = new MetadataSystem(typeLoader);
private JTree tree;
private JTabbedPane house;
private File file;
private DecompilerSettings settings;
private DecompilationOptions decompilationOptions;
private Theme theme;
private MainWindow mainWindow;
private JProgressBar bar;
private JLabel label;
private HashSet<OpenFile> hmap = new HashSet<OpenFile>();
private Set<String> treeExpansionState;
private boolean open = false;
private State state;
private ConfigSaver configSaver;
private LuytenPreferences luytenPrefs;
public Model(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.bar = mainWindow.getBar();
this.setLabel(mainWindow.getLabel());
configSaver = ConfigSaver.getLoadedInstance();
settings = configSaver.getDecompilerSettings();
luytenPrefs = configSaver.getLuytenPreferences();
try {
String themeXml = luytenPrefs.getThemeXml();
theme = Theme.load(getClass().getResourceAsStream(LuytenPreferences.THEME_XML_PATH + themeXml));
} catch (Exception e1) {
try {
e1.printStackTrace();
String themeXml = LuytenPreferences.DEFAULT_THEME_XML;
luytenPrefs.setThemeXml(themeXml);
theme = Theme.load(getClass().getResourceAsStream(LuytenPreferences.THEME_XML_PATH + themeXml));
} catch (Exception e2) {
e2.printStackTrace();
}
}
tree = new JTree();
tree.setModel(new DefaultTreeModel(null));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setCellRenderer(new CellRenderer());
TreeListener tl = new TreeListener();
tree.addMouseListener(tl);
JPanel panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, 1));
panel2.setBorder(BorderFactory.createTitledBorder("Structure"));
panel2.add(new JScrollPane(tree));
house = new JTabbedPane();
house.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
house.addChangeListener(new TabChangeListener());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, 1));
panel.setBorder(BorderFactory.createTitledBorder("Code"));
panel.add(house);
this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.setDividerLocation(250 % mainWindow.getWidth());
this.setLeftComponent(panel2);
this.setRightComponent(panel);
decompilationOptions = new DecompilationOptions();
decompilationOptions.setSettings(settings);
decompilationOptions.setFullDecompilation(true);
}
public void showLegal(String legalStr) {
show("Legal", legalStr);
}
public void show(String name, String contents) {
OpenFile open = new OpenFile(name, "*/"+name, theme, mainWindow);
open.setContent(contents);
hmap.add(open);
addOrSwitchToTab(open);
}
private void addOrSwitchToTab(final OpenFile open) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
final String title = open.name;
RTextScrollPane rTextScrollPane = open.scrollPane;
if (house.indexOfTab(title) < 0) {
house.addTab(title, rTextScrollPane);
house.setSelectedIndex(house.indexOfTab(title));
int index = house.indexOfTab(title);
Tab ct = new Tab(title);
ct.getButton().addMouseListener(new CloseTab(title));
ct.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isMiddleMouseButton(e)){
int index = house.indexOfTab(title);
closeOpenTab(index);
}
}
});
house.setTabComponentAt(index, ct);
} else {
house.setSelectedIndex(house.indexOfTab(title));
}
open.onAddedToScreen();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void closeOpenTab(int index) {
RTextScrollPane co = (RTextScrollPane) house.getComponentAt(index);
RSyntaxTextArea pane = (RSyntaxTextArea) co.getViewport().getView();
OpenFile open = null;
for (OpenFile file : hmap)
if (pane.equals(file.textArea))
open = file;
if (open != null && hmap.contains(open))
hmap.remove(open);
house.remove(co);
if (open != null)
open.close();
}
private String getName(String path) {
if (path == null)
return "";
int i = path.lastIndexOf("/");
if (i == -1)
i = path.lastIndexOf("\\");
if (i != -1)
return path.substring(i + 1);
return path;
}
private class TreeListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent event) {
boolean isClickCountMatches = (event.getClickCount() == 1 && luytenPrefs.isSingleClickOpenEnabled())
|| (event.getClickCount() == 2 && !luytenPrefs.isSingleClickOpenEnabled());
if (!isClickCountMatches)
return;
if (!SwingUtilities.isLeftMouseButton(event))
return;
final TreePath trp = tree.getPathForLocation(event.getX(), event.getY());
if (trp == null)
return;
Object lastPathComponent = trp.getLastPathComponent();
boolean isLeaf = (lastPathComponent instanceof TreeNode && ((TreeNode) lastPathComponent).isLeaf());
if (!isLeaf)
return;
new Thread() {
public void run() {
openEntryByTreePath(trp);
}
}.start();
}
}
public void openEntryByTreePath(TreePath trp) {
String name = "";
String path = "";
try {
bar.setVisible(true);
if (trp.getPathCount() > 1) {
for (int i = 1; i < trp.getPathCount(); i++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) trp.getPathComponent(i);
TreeNodeUserObject userObject = (TreeNodeUserObject) node.getUserObject();
if (i == trp.getPathCount() - 1) {
name = userObject.getOriginalName();
} else {
path = path + userObject.getOriginalName() + "/";
}
}
path = path + name;
if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) {
if (state == null) {
JarFile jfile = new JarFile(file);
ITypeLoader jarLoader = new JarTypeLoader(jfile);
typeLoader.getTypeLoaders().add(jarLoader);
state = new State(file.getCanonicalPath(), file, jfile, jarLoader);
}
JarEntry entry = state.jarFile.getJarEntry(path);
if (entry == null) {
throw new FileEntryNotFoundException();
}
if (entry.getSize() > MAX_UNPACKED_FILE_SIZE_BYTES) {
throw new TooLargeFileException(entry.getSize());
}
String entryName = entry.getName();
if (entryName.endsWith(".class")) {
getLabel().setText("Extracting: " + name);
String internalName = StringUtilities.removeRight(entryName, ".class");
TypeReference type = metadataSystem.lookupType(internalName);
extractClassToTextPane(type, name, path, null);
} else {
getLabel().setText("Opening: " + name);
try (InputStream in = state.jarFile.getInputStream(entry);) {
extractSimpleFileEntryToTextPane(in, name, path);
}
}
}
} else {
name = file.getName();
path = file.getPath().replaceAll("\\\\", "/");
if (file.length() > MAX_UNPACKED_FILE_SIZE_BYTES) {
throw new TooLargeFileException(file.length());
}
if (name.endsWith(".class")) {
getLabel().setText("Extracting: " + name);
TypeReference type = metadataSystem.lookupType(path);
extractClassToTextPane(type, name, path, null);
} else {
getLabel().setText("Opening: " + name);
try (InputStream in = new FileInputStream(file);) {
extractSimpleFileEntryToTextPane(in, name, path);
}
}
}
getLabel().setText("Complete");
} catch (FileEntryNotFoundException e) {
getLabel().setText("File not found: " + name);
} catch (FileIsBinaryException e) {
getLabel().setText("Binary resource: " + name);
} catch (TooLargeFileException e) {
getLabel().setText("File is too large: " + name + " - size: " + e.getReadableFileSize());
} catch (Exception e) {
getLabel().setText("Cannot open: " + name);
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
} finally {
bar.setVisible(false);
}
}
void extractClassToTextPane(TypeReference type, String tabTitle, String path,
String navigatonLink) throws Exception {
if (tabTitle == null || tabTitle.trim().length() < 1 || path == null) {
throw new FileEntryNotFoundException();
}
OpenFile sameTitledOpen = null;
for (OpenFile nextOpen : hmap) {
if (tabTitle.equals(nextOpen.name)) {
sameTitledOpen = nextOpen;
break;
}
}
if (sameTitledOpen != null && path.equals(sameTitledOpen.path) &&
type.equals(sameTitledOpen.getType()) && sameTitledOpen.isContentValid()) {
sameTitledOpen.setInitialNavigationLink(navigatonLink);
addOrSwitchToTab(sameTitledOpen);
return;
}
// resolve TypeDefinition
TypeDefinition resolvedType = null;
if (type == null || ((resolvedType = type.resolve()) == null)) {
throw new Exception("Unable to resolve type.");
}
// open tab, store type information, start decompilation
if (sameTitledOpen != null) {
sameTitledOpen.path = path;
sameTitledOpen.invalidateContent();
sameTitledOpen.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
sameTitledOpen.setType(resolvedType);
sameTitledOpen.setInitialNavigationLink(navigatonLink);
sameTitledOpen.resetScrollPosition();
sameTitledOpen.decompile();
addOrSwitchToTab(sameTitledOpen);
} else {
OpenFile open = new OpenFile(tabTitle, path, theme, mainWindow);
open.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
open.setType(resolvedType);
open.setInitialNavigationLink(navigatonLink);
open.decompile();
hmap.add(open);
addOrSwitchToTab(open);
}
}
public void extractSimpleFileEntryToTextPane(InputStream inputStream, String tabTitle, String path)
throws Exception {
if (inputStream == null || tabTitle == null || tabTitle.trim().length() < 1 || path == null) {
throw new FileEntryNotFoundException();
}
OpenFile sameTitledOpen = null;
for (OpenFile nextOpen : hmap) {
if (tabTitle.equals(nextOpen.name)) {
sameTitledOpen = nextOpen;
break;
}
}
if (sameTitledOpen != null && path.equals(sameTitledOpen.path)) {
addOrSwitchToTab(sameTitledOpen);
return;
}
// build tab content
StringBuilder sb = new StringBuilder();
long nonprintableCharactersCount = 0;
try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
for (byte nextByte : line.getBytes()) {
if (nextByte <= 0) {
nonprintableCharactersCount++;
}
}
}
}
// guess binary or text
String extension = "." + tabTitle.replaceAll("^[^\\.]*$", "").replaceAll("[^\\.]*\\.", "");
boolean isTextFile = (OpenFile.WELL_KNOWN_TEXT_FILE_EXTENSIONS.contains(extension) ||
nonprintableCharactersCount < sb.length() / 5);
if (!isTextFile) {
throw new FileIsBinaryException();
}
// open tab
if (sameTitledOpen != null) {
sameTitledOpen.path = path;
sameTitledOpen.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
sameTitledOpen.resetScrollPosition();
sameTitledOpen.setContent(sb.toString());
addOrSwitchToTab(sameTitledOpen);
} else {
OpenFile open = new OpenFile(tabTitle, path, theme, mainWindow);
open.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
open.setContent(sb.toString());
hmap.add(open);
addOrSwitchToTab(open);
}
}
private class TabChangeListener implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
int selectedIndex = house.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
for (OpenFile open : hmap) {
if (house.indexOfTab(open.name) == selectedIndex) {
if (open.getType() != null && !open.isContentValid()) {
updateOpenClass(open);
break;
}
}
}
}
}
public void updateOpenClasses() {
// invalidate all open classes (update will hapen at tab change)
for (OpenFile open : hmap) {
if (open.getType() != null) {
open.invalidateContent();
}
}
// update the current open tab - if it is a class
for (OpenFile open : hmap) {
if (open.getType() != null && isTabInForeground(open)) {
updateOpenClass(open);
break;
}
}
}
private void updateOpenClass(final OpenFile open) {
if (open.getType() == null) {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
bar.setVisible(true);
getLabel().setText("Extracting: " + open.name);
open.invalidateContent();
open.decompile();
getLabel().setText("Complete");
} catch (Exception e) {
getLabel().setText("Error, cannot update: " + open.name);
} finally {
bar.setVisible(false);
}
}
}).start();
}
private boolean isTabInForeground(OpenFile open) {
String title = open.name;
int selectedIndex = house.getSelectedIndex();
return (selectedIndex >= 0 && selectedIndex == house.indexOfTab(title));
}
final class State implements AutoCloseable {
private final String key;
private final File file;
final JarFile jarFile;
final ITypeLoader typeLoader;
private State(String key, File file, JarFile jarFile, ITypeLoader typeLoader) {
this.key = VerifyArgument.notNull(key, "key");
this.file = VerifyArgument.notNull(file, "file");
this.jarFile = jarFile;
this.typeLoader = typeLoader;
}
@Override
public void close() {
if (typeLoader != null) {
Model.typeLoader.getTypeLoaders().remove(typeLoader);
}
Closer.tryClose(jarFile);
}
@SuppressWarnings("unused")
public File getFile() {
return file;
}
@SuppressWarnings("unused")
public String getKey() {
return key;
}
}
private class Tab extends JPanel {
private static final long serialVersionUID = -514663009333644974L;
private JLabel closeButton = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(
this.getClass().getResource("/resources/icon_close.png"))));
private JLabel tabTitle = new JLabel();
private String title = "";
public Tab(String t) {
super(new GridBagLayout());
this.setOpaque(false);
this.title = t;
this.tabTitle = new JLabel(title);
this.createTab();
}
public JLabel getButton() {
return this.closeButton;
}
public void createTab() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
this.add(tabTitle, gbc);
gbc.gridx++;
gbc.insets = new Insets(0, 5, 0, 0);
gbc.anchor = GridBagConstraints.EAST;
this.add(closeButton, gbc);
}
}
private class CloseTab extends MouseAdapter {
String title;
public CloseTab(String title) {
this.title = title;
}
@Override
public void mouseClicked(MouseEvent e) {
int index = house.indexOfTab(title);
closeOpenTab(index);
}
}
public DefaultMutableTreeNode loadNodesByNames(DefaultMutableTreeNode node, List<String> originalNames) {
List<TreeNodeUserObject> args = new ArrayList<>();
for (String originalName : originalNames) {
args.add(new TreeNodeUserObject(originalName));
}
return loadNodesByUserObj(node, args);
}
public DefaultMutableTreeNode loadNodesByUserObj(DefaultMutableTreeNode node, List<TreeNodeUserObject> args) {
if (args.size() > 0) {
TreeNodeUserObject name = args.remove(0);
DefaultMutableTreeNode nod = getChild(node, name);
if (nod == null)
nod = new DefaultMutableTreeNode(name);
node.add(loadNodesByUserObj(nod, args));
}
return node;
}
@SuppressWarnings("unchecked")
public DefaultMutableTreeNode getChild(DefaultMutableTreeNode node, TreeNodeUserObject name) {
Enumeration<DefaultMutableTreeNode> entry = node.children();
while (entry.hasMoreElements()) {
DefaultMutableTreeNode nods = entry.nextElement();
if (((TreeNodeUserObject) nods.getUserObject()).getOriginalName().equals(name.getOriginalName())) {
return nods;
}
}
return null;
}
public void loadFile(File file) {
if (open)
closeFile();
this.file = file;
loadTree();
}
public void updateTree() {
TreeUtil treeUtil = new TreeUtil(tree);
treeExpansionState = treeUtil.getExpansionState();
loadTree();
}
public void loadTree() {
new Thread(new Runnable() {
@Override
public void run() {
try {
if (file == null) {
return;
}
tree.setModel(new DefaultTreeModel(null));
if (file.length() > MAX_JAR_FILE_SIZE_BYTES) {
throw new TooLargeFileException(file.length());
}
if (file.getName().endsWith(".zip") || file.getName().endsWith(".jar")) {
JarFile jfile;
jfile = new JarFile(file);
getLabel().setText("Loading: " + jfile.getName());
bar.setVisible(true);
JarEntryFilter jarEntryFilter = new JarEntryFilter(jfile);
List<String> mass = null;
if (luytenPrefs.isFilterOutInnerClassEntries()) {
mass = jarEntryFilter.getEntriesWithoutInnerClasses();
} else {
mass = jarEntryFilter.getAllEntriesFromJar();
}
buildTreeFromMass(mass);
if (state == null) {
ITypeLoader jarLoader = new JarTypeLoader(jfile);
typeLoader.getTypeLoaders().add(jarLoader);
state = new State(file.getCanonicalPath(), file, jfile, jarLoader);
}
open = true;
getLabel().setText("Complete");
} else {
TreeNodeUserObject topNodeUserObject = new TreeNodeUserObject(getName(file.getName()));
final DefaultMutableTreeNode top = new DefaultMutableTreeNode(topNodeUserObject);
tree.setModel(new DefaultTreeModel(top));
settings.setTypeLoader(new InputTypeLoader());
open = true;
getLabel().setText("Complete");
// open it automatically
new Thread() {
public void run() {
TreePath trp = new TreePath(top.getPath());
openEntryByTreePath(trp);
};
}.start();
}
if (treeExpansionState != null) {
try {
TreeUtil treeUtil = new TreeUtil(tree);
treeUtil.restoreExpanstionState(treeExpansionState);
} catch (Exception exc) {
exc.printStackTrace();
}
}
} catch (TooLargeFileException e) {
getLabel().setText("File is too large: " + file.getName() + " - size: " + e.getReadableFileSize());
closeFile();
} catch (Exception e1) {
e1.printStackTrace();
getLabel().setText("Cannot open: " + file.getName());
closeFile();
} finally {
mainWindow.onFileLoadEnded(file, open);
bar.setVisible(false);
}
}
}).start();
}
private void buildTreeFromMass(List<String> mass) {
if (luytenPrefs.isPackageExplorerStyle()) {
buildFlatTreeFromMass(mass);
} else {
buildDirectoryTreeFromMass(mass);
}
}
private void buildDirectoryTreeFromMass(List<String> mass) {
TreeNodeUserObject topNodeUserObject = new TreeNodeUserObject(getName(file.getName()));
DefaultMutableTreeNode top = new DefaultMutableTreeNode(topNodeUserObject);
List<String> sort = new ArrayList<String>();
Collections.sort(mass, String.CASE_INSENSITIVE_ORDER);
for (String m : mass)
if (m.contains("META-INF") && !sort.contains(m))
sort.add(m);
Set<String> set = new HashSet<String>();
for (String m : mass) {
if (m.contains("/")) {
set.add(m.substring(0, m.lastIndexOf("/") + 1));
}
}
List<String> packs = Arrays.asList(set.toArray(new String[] {}));
Collections.sort(packs, String.CASE_INSENSITIVE_ORDER);
Collections.sort(packs, new Comparator<String>() {
public int compare(String o1, String o2) {
return o2.split("/").length - o1.split("/").length;
}
});
for (String pack : packs)
for (String m : mass)
if (!m.contains("META-INF") && m.contains(pack)
&& !m.replace(pack, "").contains("/"))
sort.add(m);
for (String m : mass)
if (!m.contains("META-INF") && !m.contains("/") && !sort.contains(m))
sort.add(m);
for (String pack : sort) {
LinkedList<String> list = new LinkedList<String>(Arrays.asList(pack.split("/")));
loadNodesByNames(top, list);
}
tree.setModel(new DefaultTreeModel(top));
}
private void buildFlatTreeFromMass(List<String> mass) {
TreeNodeUserObject topNodeUserObject = new TreeNodeUserObject(getName(file.getName()));
DefaultMutableTreeNode top = new DefaultMutableTreeNode(topNodeUserObject);
TreeMap<String, TreeSet<String>> packages = new TreeMap<>();
HashSet<String> classContainingPackageRoots = new HashSet<>();
Comparator<String> sortByFileExtensionsComparator = new Comparator<String>() {
// (assertion: mass does not contain null elements)
@Override
public int compare(String o1, String o2) {
int comp = o1.replaceAll("[^\\.]*\\.", "").compareTo(o2.replaceAll("[^\\.]*\\.", ""));
if (comp != 0)
return comp;
return o1.compareTo(o2);
}
};
for (String entry : mass) {
String packagePath = "";
String packageRoot = "";
if (entry.contains("/")) {
packagePath = entry.replaceAll("/[^/]*$", "");
packageRoot = entry.replaceAll("/.*$", "");
}
String packageEntry = entry.replace(packagePath + "/", "");
if (!packages.containsKey(packagePath)) {
packages.put(packagePath, new TreeSet<String>(sortByFileExtensionsComparator));
}
packages.get(packagePath).add(packageEntry);
if (!entry.startsWith("META-INF") && packageRoot.trim().length() > 0 &&
entry.matches(".*\\.(class|java|prop|properties)$")) {
classContainingPackageRoots.add(packageRoot);
}
}
// META-INF comes first -> not flat
for (String packagePath : packages.keySet()) {
if (packagePath.startsWith("META-INF")) {
List<String> packagePathElements = Arrays.asList(packagePath.split("/"));
for (String entry : packages.get(packagePath)) {
ArrayList<String> list = new ArrayList<>(packagePathElements);
list.add(entry);
loadNodesByNames(top, list);
}
}
}
// real packages: path starts with a classContainingPackageRoot -> flat
for (String packagePath : packages.keySet()) {
String packageRoot = packagePath.replaceAll("/.*$", "");
if (classContainingPackageRoots.contains(packageRoot)) {
for (String entry : packages.get(packagePath)) {
ArrayList<TreeNodeUserObject> list = new ArrayList<>();
list.add(new TreeNodeUserObject(packagePath, packagePath.replaceAll("/", ".")));
list.add(new TreeNodeUserObject(entry));
loadNodesByUserObj(top, list);
}
}
}
// the rest, not real packages but directories -> not flat
for (String packagePath : packages.keySet()) {
String packageRoot = packagePath.replaceAll("/.*$", "");
if (!classContainingPackageRoots.contains(packageRoot) &&
!packagePath.startsWith("META-INF") && packagePath.length() > 0) {
List<String> packagePathElements = Arrays.asList(packagePath.split("/"));
for (String entry : packages.get(packagePath)) {
ArrayList<String> list = new ArrayList<>(packagePathElements);
list.add(entry);
loadNodesByNames(top, list);
}
}
}
// the default package -> not flat
String packagePath = "";
if (packages.containsKey(packagePath)) {
for (String entry : packages.get(packagePath)) {
ArrayList<String> list = new ArrayList<>();
list.add(entry);
loadNodesByNames(top, list);
}
}
tree.setModel(new DefaultTreeModel(top));
}
public void closeFile() {
for (OpenFile co : hmap) {
int pos = house.indexOfTab(co.name);
if (pos >= 0)
house.remove(pos);
co.close();
}
final State oldState = state;
Model.this.state = null;
if (oldState != null) {
Closer.tryClose(oldState);
}
hmap.clear();
tree.setModel(new DefaultTreeModel(null));
metadataSystem = new MetadataSystem(typeLoader);
file = null;
treeExpansionState = null;
open = false;
mainWindow.onFileLoadEnded(file, open);
}
public void changeTheme(String xml) {
InputStream in = getClass().getResourceAsStream(LuytenPreferences.THEME_XML_PATH + xml);
try {
if (in != null) {
theme = Theme.load(in);
for (OpenFile f : hmap) {
theme.apply(f.textArea);
}
}
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null, e1.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
}
}
public File getOpenedFile() {
File openedFile = null;
if (file != null && open) {
openedFile = file;
}
if (openedFile == null) {
getLabel().setText("No open file");
}
return openedFile;
}
public String getCurrentTabTitle() {
String tabTitle = null;
try {
int pos = house.getSelectedIndex();
if (pos >= 0) {
tabTitle = house.getTitleAt(pos);
}
} catch (Exception e1) {
e1.printStackTrace();
}
if (tabTitle == null) {
getLabel().setText("No open tab");
}
return tabTitle;
}
public RSyntaxTextArea getCurrentTextArea() {
RSyntaxTextArea currentTextArea = null;
try {
int pos = house.getSelectedIndex();
if (pos >= 0) {
RTextScrollPane co = (RTextScrollPane) house.getComponentAt(pos);
currentTextArea = (RSyntaxTextArea) co.getViewport().getView();
}
} catch (Exception e1) {
e1.printStackTrace();
}
if (currentTextArea == null) {
getLabel().setText("No open tab");
}
return currentTextArea;
}
public void startWarmUpThread() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
String internalName = FindBox.class.getName();
TypeReference type = metadataSystem.lookupType(internalName);
TypeDefinition resolvedType = null;
if ((type == null) || ((resolvedType = type.resolve()) == null)) {
return;
}
StringWriter stringwriter = new StringWriter();
PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
plainTextOutput.setUnicodeOutputEnabled(decompilationOptions.getSettings().isUnicodeOutputEnabled());
settings.getLanguage().decompileType(resolvedType, plainTextOutput, decompilationOptions);
String decompiledSource = stringwriter.toString();
OpenFile open = new OpenFile(internalName, "*/" + internalName, theme, mainWindow);
open.setContent(decompiledSource);
JTabbedPane pane = new JTabbedPane();
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
pane.addTab("title", open.scrollPane);
pane.setSelectedIndex(pane.indexOfTab("title"));
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void navigateTo(final String uniqueStr) {
new Thread(new Runnable() {
@Override
public void run() {
if (uniqueStr == null)
return;
String[] linkParts = uniqueStr.split("\\|");
if (linkParts.length <= 1)
return;
String destinationTypeStr = linkParts[1];
try {
bar.setVisible(true);
getLabel().setText("Navigating: " + destinationTypeStr.replaceAll("/", "."));
TypeReference type = metadataSystem.lookupType(destinationTypeStr);
if (type == null)
throw new RuntimeException("Cannot lookup type: " + destinationTypeStr);
TypeDefinition typeDef = type.resolve();
if (typeDef == null)
throw new RuntimeException("Cannot resolve type: " + destinationTypeStr);
String tabTitle = typeDef.getName() + ".class";
extractClassToTextPane(typeDef, tabTitle, destinationTypeStr, uniqueStr);
getLabel().setText("Complete");
} catch (Exception e) {
getLabel().setText("Cannot navigate: " + destinationTypeStr.replaceAll("/", "."));
e.printStackTrace();
} finally {
bar.setVisible(false);
}
}
}).start();
}
public JLabel getLabel() {
return label;
}
public void setLabel(JLabel label) {
this.label = label;
}
public State getState(){
return state;
}
} |
package utilities.video;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
class VideoPlayer extends BorderPane {
private static final String PLAY_BUTTON_TEXT = "Play";
private static final String PAUSE_BUTTON_TEXT = "Pause";
private MediaPlayer myMediaPlayer;
private MediaView myMediaView;
private Slider myTimeSlider;
private final boolean replayVideo = true;
private boolean stopVideo = false;
private boolean cycleComplete = false;
private HBox myMediaBar;
public VideoPlayer (final MediaPlayer mediaPlayer) {
this.myMediaPlayer = mediaPlayer;
myMediaView = new MediaView(mediaPlayer);
Pane moviePane = new Pane() { };
moviePane.getChildren().add(myMediaView);
setCenter(moviePane);
myMediaBar = new HBox();
myMediaBar.setAlignment(Pos.CENTER);
BorderPane.setAlignment(myMediaBar, Pos.CENTER);
setBottom(myMediaBar);
final Button playButton = new Button(PLAY_BUTTON_TEXT);
definePlayButtonBehaviors(mediaPlayer, playButton);
myMediaBar.getChildren().add(playButton);
myTimeSlider = new Slider();
myMediaBar.getChildren().add(myTimeSlider);
mediaPlayer.setCycleCount(replayVideo ? MediaPlayer.INDEFINITE : 1);
defineMediaPlayerBehaviors(mediaPlayer, playButton);
}
private void defineMediaPlayerBehaviors (final MediaPlayer mediaPlayer, final Button playButton) {
mediaPlayer.setOnPlaying(new Runnable() {
public void run () {
if (stopVideo) {
mediaPlayer.pause();
stopVideo = false;
}
else {
playButton.setText(PAUSE_BUTTON_TEXT);
}
}
});
mediaPlayer.setOnPaused(new Runnable() {
public void run () {
playButton.setText(PLAY_BUTTON_TEXT);
}
});
mediaPlayer.setOnEndOfMedia(new Runnable() {
public void run () {
if (!replayVideo) {
playButton.setText(PLAY_BUTTON_TEXT);
stopVideo = true;
cycleComplete = true;
}
}
});
}
private void definePlayButtonBehaviors (final MediaPlayer mediaPlayer, final Button playButton) {
playButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle (ActionEvent e) {
Status status = mediaPlayer.getStatus();
if (status == Status.HALTED || status == Status.UNKNOWN) {
return;
}
if (status == Status.PAUSED || status == Status.READY || status == Status.STOPPED) {
if (cycleComplete) {
mediaPlayer.seek(mediaPlayer.getStartTime());
cycleComplete = false;
}
mediaPlayer.play();
}
else {
mediaPlayer.pause();
}
}
});
}
} |
package wei_chih.utility;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Pattern;
import wei_chih.service.Config;
/**
*
* @author Chienweichih
*/
public class MerkleTree implements Serializable {
private static class Node implements Serializable {
private final String fname;
private String digest;
private final Node parent;
private List<Node> children;
private Node(String fname, String digest, Node parent, List<Node> children) {
this.fname = fname;
this.digest = digest;
this.parent = parent;
this.children = children;
}
private Node(Node node, Node parent) {
this.fname = node.fname;
this.digest = node.digest;
this.parent = parent;
this.children = null;
if (node.isDirectory()) {
this.children = new ArrayList<>();
for (Node n : node.children) {
this.children.add(new Node(n, this));
}
}
}
private boolean isDirectory() {
return children != null;
}
private static Node getNode(String path, Node root) {
String pattern = Pattern.quote(File.separator);
String[] splittedFileName = path.split(pattern);
Node target = root;
if (splittedFileName.length <= 1) {
return target;
}
for (String token : Arrays.copyOfRange(splittedFileName, 1, splittedFileName.length)) {
int index = 0;
for (Node node : target.children) {
if (node.fname.equals(token)) {
break;
}
++index;
}
target = target.children.get(index);
}
return target;
}
}
private final Node root;
public MerkleTree(MerkleTree merkleTree) {
this.root = new Node(merkleTree.root, null);
}
public MerkleTree(File rootPath) {
this.root = create(rootPath, null);
}
private Node create(File file, Node parent) {
Node node = new Node(file.getName(), null, parent, null);
if (file.isFile()) {
node.digest = Utils.digest(file);
} else {
node.children = new ArrayList<>();
String folderDigest = "";
for (File f : sortedFiles(file.listFiles())) {
Node newNode = create(f, node);
node.children.add(newNode);
folderDigest += newNode.digest;
}
node.digest = Utils.digest(Utils.Str2Hex(folderDigest));
}
return node;
}
public void update(String fname, String digest) {
update(Node.getNode(fname, root), digest);
}
private void update(Node node, String digest) {
node.digest = digest;
while (node.parent != null) {
node = node.parent;
String newDigest = "";
for (Node n : node.children) {
newDigest += n.digest;
}
node.digest = Utils.digest(Utils.Str2Hex(newDigest));
}
}
public void delete(String fname) {
Node node = Node.getNode(fname, root);
fname = node.fname;
node = node.parent;
int index = 0;
for (Node n : node.children) {
if (n.fname.equals(fname)) {
break;
}
++index;
}
node.children.remove(index);
update(node.children.get(0), node.children.get(0).digest);
}
public String getRootHash() {
return root.digest;
}
public String getDigest(String path) {
return Node.getNode(path, root).digest;
}
private static List<File> sortedFiles(File[] unSortedFiles) {
if (unSortedFiles == null) {
System.err.println("exceptionininitializererror?");
}
List<File> files = Arrays.asList(unSortedFiles);
Collections.sort(files, (File lhs, File rhs) -> {
return lhs.getName().compareTo(rhs.getName());
});
return files;
}
private void print() {
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node node = queue.poll();
System.out.println(node.fname + " " + node.digest);
if (node.isDirectory()) {
for (Node n : node.children) {
queue.add(n);
}
}
}
}
public static void main(String[] args) {
long time;
for(int i = 0; i < 3; ++i) {
time = System.currentTimeMillis();
String dataDirPath;
if (args.length != 1) {
dataDirPath = Config.DATA_A_PATH;
} else {
dataDirPath = Utils.getDataDirPath(args[0]);
}
String hashValue = new MerkleTree(new File(dataDirPath)).getRootHash();
System.out.println("RootHash Hash Value: " + hashValue);
time = System.currentTimeMillis() - time;
System.out.println("Generate Root Hash Cost: " + time/1000.0 + "s");
}
}
} |
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Robot;
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import javax.swing.SwingUtilities;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class GameWindow
{
private final JFrame frame;
private BufferStrategy bStrat;
//used to move mouse
private Robot robot;
private final Keyboard input;
private Canvas canvas;
private final Point origin;
public GameWindow(String title, Dimension windowSize,final Keyboard input)
{
try{
robot = new Robot();
} catch(AWTException e) {
//TODO maybe.
}
this.input = input;
//set up the JFrame
frame = new JFrame(title);
frame.setSize(windowSize);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setIgnoreRepaint(true);
canvas = new Canvas();
canvas.setPreferredSize(windowSize);
canvas.setIgnoreRepaint(true);
canvas.addKeyListener(input);
canvas.addMouseMotionListener(input);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
canvas.createBufferStrategy(2);
bStrat = canvas.getBufferStrategy();
origin = frame.getLocationOnScreen();
origin.setLocation(origin.getX()+canvas.getWidth()/2, origin.getY()+canvas.getHeight()/2);
frame.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e)
{
Point frameLoc = frame.getLocationOnScreen();
origin.setLocation(frameLoc.getX()+canvas.getWidth()/2, frameLoc.getY()+canvas.getHeight()/2);
input.setOrigin(origin);
}
});
}
public JFrame getFrame() {return frame;}
public BufferStrategy getBufferStrategy() {return bStrat;}
public void resetMousePos()
{
robot.mouseMove((int)origin.getX(), (int)origin.getY());
}
//test
public static void main(String[] args)
{
GameWindow gWind = new GameWindow("test window", new Dimension(800, 600),null);
BufferStrategy bStrateg = gWind.getBufferStrategy();
Graphics g = bStrateg.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(50, 50, 300, 300);
g.dispose();
bStrateg.show();
}
} |
/* Implements a node in a linked list for GraphAdjacencyList */
class Node<T> {
protected Node<T> next;
protected T data;
public Node (T value) {
this.data = data;
this.next = null;
}
protected void appendToTail(Node<T> tailNode) {
Node<T> curr = this;
while(curr.next != null) {
curr = curr.next;
}
/* Set the end node */
curr.next = tailNode;
return;
}
/* Remove the node with data and return the new head node. */
protected Node<T> delete(Node<T> head, T data) {
/* Deleting the first node, move the head over. */
if (this.data == data) {
return head.next;
}
Node<T> curr = head;
while(curr.next != null) {
if (curr.next.data == data) {
curr.next = curr.next.next;
return curr;
}
curr = curr.next;
}
return head;
}
} |
package io.spine.client;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.Message;
import io.grpc.stub.StreamObserver;
import io.spine.base.MessageContext;
import java.util.function.Consumer;
/**
* Abstract base for client requests that subscribe to messages.
*
* @param <M>
* the type of the subscribed messages
* @param <C>
* the type of the context of messages or {@link io.spine.core.EmptyContext} if
* messages do not have a context
* @param <W>
* the type of the message that wraps a message and its context
* (e.g. {@link io.spine.core.Event}); if subscribed message type does not have a context,
* this parameter is likely to be the same as {@code M}
* @param <B>
* the type of this requests for return type covariance
*/
public abstract class
SubscribingRequest<M extends Message,
C extends MessageContext,
W extends Message,
B extends SubscribingRequest<M, C, W, B>>
extends FilteringRequest<M, Topic, TopicBuilder, SubscribingRequest<M, C, W, B>> {
SubscribingRequest(ClientRequest parent, Class<M> type) {
super(parent, type);
}
abstract Consumers.Builder<M, C, W, ?> consumers();
abstract MessageConsumer<M, C> toMessageConsumer(Consumer<M> consumer);
@CanIgnoreReturnValue
public SubscribingRequest<M, C, W, B> observe(Consumer<M> consumer) {
consumers().add(toMessageConsumer(consumer));
return self();
}
/**
* Assigns a handler for the error reported to
* {@link StreamObserver#onError(Throwable)} of
* the {@link StreamObserver} responsible for delivering messages
* to the consumers.
*
* <p>Once this handler is called, no more messages will be delivered to consumers.
*
* @see #onConsumingError(ConsumerErrorHandler)
*/
@CanIgnoreReturnValue
public SubscribingRequest<M, C, W, B> onStreamingError(ErrorHandler handler) {
consumers().onStreamingError(handler);
return self();
}
/**
* Assigns a handler for an error that may occur in the code of one of the consumers.
*
* <p>After this handler called, remaining consumers will get the message as usually.
*
* @see #onStreamingError(ErrorHandler)
*/
@CanIgnoreReturnValue
SubscribingRequest<M, C, W, B> onConsumingError(ConsumerErrorHandler<M> handler) {
consumers().onConsumingError(handler);
return self();
}
/**
* Creates and posts the subscription request to the server.
*/
public Subscription post() {
Topic topic = builder().build();
StreamObserver<W> observer = createObserver();
return subscribe(topic, observer);
}
/**
* Subscribes to receive all messages of the specified type.
*/
public Subscription all() {
Topic topic = factory().topic().allOf(messageType());
StreamObserver<W> observer = createObserver();
return subscribe(topic, observer);
}
private StreamObserver<W> createObserver() {
return consumers().build().toObserver();
}
private Subscription subscribe(Topic topic, StreamObserver<W> observer) {
Subscription subscription = client().subscribeTo(topic, observer);
return subscription;
}
} |
package nl.mpi.yaas.common.data;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement(name = "DataNodeId")
public class DataNodeId {
@XmlValue
String idString = null;
protected DataNodeId() {
}
public DataNodeId(String idString) {
this.idString = idString;
}
public String getIdString() {
return idString;
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + (this.idString != null ? this.idString.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DataNodeId other = (DataNodeId) obj;
if ((this.idString == null) ? (other.idString != null) : !this.idString.equals(other.idString)) {
return false;
}
return true;
}
} |
package org.neo4j.shell;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.Config.ENABLE_REMOTE_SHELL;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.kernel.Config;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.shell.impl.SameJvmClient;
import org.neo4j.shell.impl.ShellBootstrap;
import org.neo4j.shell.impl.ShellServerExtension;
import org.neo4j.shell.kernel.GraphDatabaseShellServer;
public class ShellTest
{
private AppCommandParser parse( String line ) throws Exception
{
return new AppCommandParser( new GraphDatabaseShellServer( null ),
line );
}
@Test
public void testParserEasy() throws Exception
{
AppCommandParser parser = this.parse( "ls -la" );
assertEquals( "ls", parser.getAppName() );
assertEquals( 2, parser.options().size() );
assertTrue( parser.options().containsKey( "l" ) );
assertTrue( parser.options().containsKey( "a" ) );
assertTrue( parser.arguments().isEmpty() );
}
@Test
public void testParserArguments() throws Exception
{
AppCommandParser parser = this
.parse( "set -t java.lang.Integer key value" );
assertEquals( "set", parser.getAppName() );
assertTrue( parser.options().containsKey( "t" ) );
assertEquals( "java.lang.Integer", parser.options().get( "t" ) );
assertEquals( 2, parser.arguments().size() );
assertEquals( "key", parser.arguments().get( 0 ) );
assertEquals( "value", parser.arguments().get( 1 ) );
assertException( "set -tsd" );
}
@Test
public void testEnableRemoteShell() throws Exception
{
int port = 8085;
GraphDatabaseService graphDb = new EmbeddedGraphDatabase(
"target/shell-neo", stringMap( ENABLE_REMOTE_SHELL, "port=" + port ) );
ShellLobby.newClient( port );
graphDb.shutdown();
}
@Test
public void testEnableServerOnDefaultPort() throws Exception
{
GraphDatabaseService graphDb = new EmbeddedGraphDatabase( "target/shell-neo", MapUtil.stringMap( Config.ENABLE_REMOTE_SHELL, "true" ) );
try
{
ShellLobby.newClient();
}
finally
{
graphDb.shutdown();
}
}
@Test
public void canConnectAsAgent() throws Exception
{
Integer port = Integer.valueOf( 1234 );
String name = "test-shell";
GraphDatabaseService graphDb = new EmbeddedGraphDatabase( "target/shell-neo" );
try
{
new ShellServerExtension().loadAgent( new ShellBootstrap( port.toString(), name ).serialize() );
}
finally
{
graphDb.shutdown();
}
ShellLobby.newClient( port.intValue(), name );
}
@Test
public void testRemoveReferenceNode() throws Exception
{
final GraphDatabaseShellServer server = new GraphDatabaseShellServer( "target/shell-neo", false, null );
ShellClient client = new SameJvmClient( server );
Documenter doc = new Documenter("sample session", client);
doc.add("pwd", "", "where are we?");
doc.add("set name \"Jon\"", "", "On the current node, set the key \"name\" to value \"Jon\"");
doc.add("start n=(0) return n", "peter", "send a cypher query");
doc.add("mkrel -c -d i -t LIKES --np \"{'app':'foobar'}\"", "", "make an incoming relationship of type LIKES, create the end node with the node properties specified.");
doc.add("ls", "1", "where are we?");
doc.add("cd 1", "", "change to the newly created node");
doc.add("ls -avr", "LIKES", "list relationships, including relationshship id");
doc.add( "mkrel -c -d i -t KNOWS --np \"{'name':'Bob'}\"", "", "create one more KNOWS relationship and the end node" );
doc.add( "pwd", "0", "print current history stack" );
doc.add( "ls -avr", "KNOWS", "verbose list relationships" );
doc.run();
//TODO: implement support for removing root node and previous nodes in the history stack of PWD
//client.getServer().interpretLine( "rmrel -d 0", client.session(), client.getOutput() );
// client.getServer().interpretLine( "cd", client.session(), client.getOutput() );
// client.getServer().interpretLine( "pwd", client.session(), client.getOutput() );
server.shutdown();
}
private void assertException( String command )
{
try
{
this.parse( command );
fail( "Should fail" );
}
catch ( Exception e )
{
// Good
}
}
} |
package ru.apetrov.start;
import ru.apetrov.models.*;
public class StartUI{
private Input input;
public StartUI(Input input){
this.input = input;
}
public void init(){
Tracker tracker = new Tracker();
boolean isExit = false;
do{
String action = input.ask("Select an action:\n1. - Add Item;\n2. - Edit Item;\n3. - Remove Item;\n4. - Find by Name;\n5. - Find by Descriotion;\n6. - Add Comment;\n7. - Get All Item.\n8. - Exit\n");
if (action.equals("1")){
String name = input.ask("Enter the name of the Item:");
String desc = input.ask("Enter the description of the Item:");
tracker.add(new Task(name, desc));
}
if (action.equals("2")){
String id = input.ask("Enter the id of the Item:");
if (tracker.findById(id) != null){
String name = input.ask("Enter the new name of the Item:");
String desc = input.ask("Enter the new description of the Item:");
Item editItem = new Task(name, desc);
editItem.setId(id);
tracker.edit(editItem);
}else{
System.out.println("Item with this Id does not exist");
}
}
if (action.equals("3")){
String id = input.ask("Enter the id of the Item:");
if (tracker.findById(id) != null){
Item delItem = tracker.findById(id);
tracker.remove(delItem);
}else{
System.out.println("Item with this Id does not exist");
}
}
if (action.equals("4")){
String name = input.ask("Enter the name of the Item:");
for (Item item : tracker.findByName(name)) {
System.out.println(item.getName());
}
}
if (action.equals("5")){
String desc = input.ask("Enter the description of the Item:");
for (Item item : tracker.findByDesc(desc)) {
System.out.println(item.getName());
}
}
if (action.equals("6")){
String id = input.ask("Enter the id of the Item:");
String text = input.ask("Enter Comment:");
if (tracker.findById(id) != null){
Item item = tracker.findById(id);
Comment comment = new Comment(text);
tracker.addComment(item, comment);
}else{
System.out.println("Item with this Id does not exist");
}
}
if (action.equals("7")){
for (Item item : tracker.getAll()){
System.out.println(item.getName());
System.out.println(item.getDescription());
System.out.println(item.getId());
System.out.println(item.getComment());
}
}
if (action.equals("8")){
isExit = true;
}
}while(!isExit);
}
public static void main(String[] args){
Input input = new ConsoleInput();
new StartUI(input).init();
}
} |
package com.domeke.app.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.render.Render;
public class MyCaptchaRender extends Render {
private static final long serialVersionUID = -7599510915228560611L;
private static final String[] strArr = { "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
private static String randomCodeKey = "JFINAL_JLHHWH_Key";
private static boolean caseInsensitive = true;
private int img_width = 85;
private int img_height = 20;
private int img_randNumber = 6;
public MyCaptchaRender() {
}
public MyCaptchaRender(String randomKey) {
if (StrKit.isBlank(randomKey))
throw new IllegalArgumentException("randomKey can not be blank");
randomCodeKey = randomKey;
}
public MyCaptchaRender(int width, int height, int count, boolean isCaseInsensitive) {
if (width <= 0 || height <= 0 || count <= 0) {
throw new IllegalArgumentException("Image width or height or count must be > 0");
}
this.img_width = width;
this.img_height = height;
this.img_randNumber = count;
caseInsensitive = isCaseInsensitive;
}
public MyCaptchaRender(String randomKey, int width, int height, int count, boolean isCaseInsensitive) {
if (StrKit.isBlank(randomKey))
throw new IllegalArgumentException("randomKey can not be blank");
randomCodeKey = randomKey;
if (width <= 0 || height <= 0 || count <= 0) {
throw new IllegalArgumentException("Image width or height or count must be > 0");
}
this.img_width = width;
this.img_height = height;
this.img_randNumber = count;
caseInsensitive = isCaseInsensitive;
}
public void render() {
BufferedImage image = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
String vCode = drawGraphic(image);
vCode = encrypt(vCode);
Cookie cookie = new Cookie(randomCodeKey, vCode);
cookie.setMaxAge(-1);
cookie.setPath("/");
response.addCookie(cookie);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream sos = null;
try {
sos = response.getOutputStream();
ImageIO.write(image, "jpeg", sos);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (sos != null)
try {
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String drawGraphic(BufferedImage image) {
Graphics g = image.createGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, img_width, img_height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 155
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(img_width);
int y = random.nextInt(img_height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// (img_randNumber)
String sRand = "";
for (int i = 0; i < img_randNumber; i++) {
String rand = String.valueOf(strArr[random.nextInt(strArr.length)]);
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return sRand;
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static final String encrypt(String srcStr) {
try {
String result = "";
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF).toUpperCase();
result += ((hex.length() == 1) ? "0" : "") + hex;
}
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean validate(Controller controller, String inputRandomCode) {
if (StrKit.isBlank(inputRandomCode))
return false;
try {
if (caseInsensitive)
inputRandomCode = inputRandomCode.toUpperCase();
inputRandomCode = encrypt(inputRandomCode);
return inputRandomCode.equals(controller.getCookie(randomCodeKey));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
} |
// Nexus Core - a framework for developing distributed applications
package com.threerings.nexus.distrib;
import com.threerings.nexus.io.Streamable;
/**
* Identifies a distributed object somewhere in the Nexus network. The object may be keyed, or a
* singleton, as dictated by subclasses.
*/
public abstract class Address<T extends NexusObject> implements Streamable
{
/** An address of a keyed object. */
public static class OfKeyed<T extends NexusObject & Keyed> extends OfTyped<T> {
/** The key identifying our target object. */
public final Comparable<?> key;
public OfKeyed (String host, Class<T> clazz, Comparable<?> key) {
super(host, clazz);
this.key = key;
}
@Override public String toString () {
return super.toString() + ":" + key;
}
@Override public int hashCode () {
return key.hashCode() ^ super.hashCode();
}
@Override public boolean equals (Object other) {
if (other == null || other.getClass() != getClass()) return false;
OfKeyed<?> oaddr = (OfKeyed<?>)other;
return oaddr.key.equals(key) && super.equals(oaddr);
}
}
/** An address of a singleton object. */
public static class OfSingleton<T extends NexusObject & Singleton> extends OfTyped<T> {
public OfSingleton (String host, Class<T> clazz) {
super(host, clazz);
}
}
/** An address of an anonymous object. */
public static class OfAnonymous extends Address<NexusObject> {
/** The id of the target object. */
public final int id;
public OfAnonymous (String host, int id) {
super(host);
if (id <= 0) throw new IllegalArgumentException("Id must be >= 0.");
this.id = id;
}
@Override public String toString () {
return super.toString() + ":" + id;
}
@Override public int hashCode () {
return id ^ super.hashCode();
}
@Override public boolean equals (Object other) {
if (other.getClass() != getClass()) return false;
OfAnonymous oaddr = (OfAnonymous)other;
return (oaddr.id == id) && super.equals(oaddr);
}
}
/**
* Returns the address of the supplied NexusObject, with the proper generic type.
*/
public static <T extends NexusObject> Address<T> of (T object) {
@SuppressWarnings("unchecked") Address<T> addr = (Address<T>)object.getAddress();
return addr;
}
/**
* Creates an address for a keyed instance on the specified host.
*/
public static <T extends NexusObject & Keyed> Address<T> create (
String host, Class<T> clazz, Comparable<?> key) {
return new OfKeyed<T>(host, clazz, key);
}
/**
* Creates an address for a singleton instance on the specified host.
*/
public static <T extends NexusObject & Singleton> Address<T> create (
String host, Class<T> clazz) {
return new OfSingleton<T>(host, clazz);
}
/**
* Creates an address for an anonymous object on the specified host.
*/
public static Address<NexusObject> create (String host, int id) {
return new OfAnonymous(host, id);
}
/** The hostname of the server on which this object resides. */
public final String host;
@Override public String toString () {
return host;
}
@Override public int hashCode () {
return host.hashCode();
}
@Override public boolean equals (Object other) {
if (other.getClass() != getClass()) return false;
Address<?> oaddr = (Address<?>)other;
return oaddr.host.equals(host);
}
protected Address (String host) {
if (host == null || host.length() == 0) {
throw new IllegalArgumentException("Host must be non-blank.");
}
this.host = host;
}
/** An address of an object with a type. */
protected static class OfTyped<T extends NexusObject> extends Address<T> {
/** The type of this object. */
public final Class<T> clazz;
public OfTyped (String host, Class<T> clazz) {
super(host);
this.clazz = clazz;
}
@Override public String toString () {
return super.toString() + ":" + clazz.getName();
}
@Override public int hashCode () {
return clazz.hashCode() ^ super.hashCode();
}
@Override public boolean equals (Object other) {
if (other.getClass() != getClass()) return false;
OfTyped<?> oaddr = (OfTyped<?>)other;
return oaddr.clazz.equals(clazz) && super.equals(oaddr);
}
}
} |
package jlibs.core.nio.channels;
import jlibs.core.lang.ByteSequence;
import jlibs.core.lang.Bytes;
import jlibs.core.nio.AttachmentSupport;
import jlibs.core.nio.ClientChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.Iterator;
/**
* @author Santhosh Kumar
*/
public abstract class InputChannel extends AttachmentSupport implements ReadableByteChannel{
protected final ClientChannel client;
protected InputChannel(ClientChannel client){
this.client = client;
IOChannelHandler handler = client.attachment() instanceof IOChannelHandler ? (IOChannelHandler)client.attachment() : null;
if(handler==null)
client.attach(handler=new IOChannelHandler());
handler.input = this;
}
public final ClientChannel client(){
return client;
}
public final void addInterest() throws IOException{
if(activateInterest())
client.addInterest(ClientChannel.OP_READ);
else if(handler!=null)
handler.onRead(this);
}
protected boolean activateInterest(){
return unread==null;
}
public void removeInterest() throws IOException{
client.removeInterest(ClientChannel.OP_READ);
}
protected InputHandler handler;
public void setHandler(InputHandler handler){
this.handler = handler;
}
private boolean eof;
@Override
public final int read(ByteBuffer dst) throws IOException{
int pos = dst.position();
if(unread!=null){
Iterator<ByteSequence> sequences = unread.iterator();
while(sequences.hasNext()){
ByteSequence seq = sequences.next();
int remaining = Math.min(dst.remaining(), seq.length());
System.arraycopy(seq.buffer(), seq.offset(), dst.array(), dst.arrayOffset() + dst.position(), remaining);
dst.position(dst.position()+remaining);
if(remaining==seq.length())
sequences.remove();
else{
unread.remove(remaining);
return dst.position()-pos;
}
}
if(unread.isEmpty())
unread = null;
}
int read = 0;
if(dst.hasRemaining())
read = doRead(dst);
int result = dst.position() == pos && read == -1 ? -1 : dst.position() - pos;
eof = result==-1;
return result;
}
protected abstract int doRead(ByteBuffer dst) throws IOException;
public boolean isEOF(){
return eof;
}
protected Bytes unread;
public final void unread(byte buff[], int offset, int length, boolean clone){
if(length==0)
return;
eof = false;
if(unread==null)
unread = new Bytes();
if(clone){
buff = Arrays.copyOfRange(buff, offset, offset + length);
offset = 0;
}
unread.prepend(new ByteSequence(buff, offset, length));
}
public long pending(){
return unread==null ? 0 : unread.size();
}
private boolean closed;
@Override
public final boolean isOpen(){
return !closed;
}
@Override
public final void close() throws IOException{
closed = true;
unread = null;
}
} |
package org.jboss.gwt.elemento.core;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.events.EventListener;
import elemental.html.InputElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Helper methods for working with {@link Element}s.
*
* @author Harald Pehl
*/
public final class Elements {
// this is a static helper class which must never be instantiated!
private Elements() {}
private static class ElementInfo {
int level;
Element element;
boolean container;
public ElementInfo(final Element element, final boolean container, final int level) {
this.container = container;
this.element = element;
this.level = level;
}
@Override
public String toString() {
return (container ? "container" : "simple") + " @ " + level + ": " + element.getTagName();
}
}
/**
* Builder to create a hierarchy of {@link Element}s. Supports convenience methods to create common elements
* and attributes. Uses a fluent API to create and append elements on the fly.
* <p>
* The builder distinguishes between elements which can contain nested elements (container) and simple element w/o
* children. The former must be closed using {@link #end()}.
* <p>
* In order to create this form,
* <pre>
* <form method="get" action="search" class="form form-horizontal">
* <div class="form-group">
* <label class="col-md-3 control-label" for="name">Name</label>
* <div class="col-md-9">
* <input type="text" id="name" class="form-control" placeholder="Enter your name"/>
* </div>
* </div>
* <div class="form-group">
* <label class="col-md-3 control-label" for="age">Age</label>
* <div class="col-md-9">
* <input type="number" id="age" class="form-control" placeholder="How old are you?"/>
* </div>
* </div>
* <div class="form-group">
* <label class="col-md-3 control-label" for="hobbies">Hobbies</label>
* <div class="col-md-9">
* <textarea rows="3" id="hobbies" class="form-control"></textarea>
* <span class="help-block textarea">One item per line</span>
* </div>
* </div>
* <div class="form-group">
* <label class="col-md-3 control-label" for="choose">Choose</label>
* <div class="col-md-9">
* <select id="choose" class="form-control selectpicker">
* <option>Lorem</option>
* <option>ipsum</option>
* </select>
* </div>
* </div>
* <div class="form-group">
* <div class="col-md-offset-3 col-md-9">
* <div class="pull-right form-buttons">
* <button type="button" class="btn btn-default btn-form">Cancel</button>
* <button type="button" class="btn btn-primary btn-form">Save</button>
* </div>
* </div>
* </div>
* </form>
* </pre>
* <p>
* use the following builder code:
* <pre>
* Element form = new Elements.Builder().
* .form().attr("method", "get").attr("action", "search").css("form form-horizontal")
* .div().css("form-group")
* .label().css("col-md-3 control-label").attr("for", "name").innerText("Name").end()
* .div().css("col-md-9")
* .input(text).id("name").css("form-control").attr("placeholder", "Enter your name")
* .end()
* .end()
* .div().css("form-group")
* .label().css("col-md-3 control-label").attr("for", "age").innerText("Age").end()
* .div().css("col-md-9")
* .input(number).id("age").css("form-control").attr("placeholder", "How old are you?")
* .end()
* .end()
* .div().css("form-group")
* .label().css("col-md-3 control-label").attr("for", "hobbies").innerText("Hobbies").end()
* .div().css("col-md-9")
* .textarea().attr("rows", "3").id("hobbies").css("form-control").end()
* .span().css("help-block textarea").innerText("One item per line").end()
* .end()
* .end()
* .div().css("form-group")
* .label().css("col-md-3 control-label").attr("for", "choose").innerText("Choose").end()
* .div().css("col-md-9")
* .select().id("choose").css("form-control selectpicker")
* .option().innerText("Lorem").end()
* .option().innerText("ipsum").end()
* .end()
* .end()
* .end()
* .div().css("form-group")
* .div().css("col-md-offset-3 col-md-9")
* .div().css("pull-right form-buttons")
* .button().css("btn btn-default btn-form").innerText("Cancel").end()
* .button().css("btn btn-primary btn-form").innerText("Save").end()
* .end()
* .end()
* .end()
* .end()
* .build();
* </pre>
*
* @author Harald Pehl
*/
public static final class Builder {
private final Document document;
private final Stack<ElementInfo> elements;
private final Map<String, Element> references;
private int level;
public Builder() {
this(Browser.getDocument());
}
protected Builder(Document document) {
this.document = document;
this.elements = new Stack<>();
this.references = new HashMap<>();
}
/**
* Starts a new {@code <header>} container. The element must be closed with {@link #end()}.
*/
public Builder header() {
return start("header");
}
/**
* Starts a new {@code <h&>} container. The element must be closed with {@link #end()}.
*/
public Builder h(int ordinal) {
return start("h" + ordinal);
}
/**
* Starts a new {@code <section>} container. The element must be closed with {@link #end()}.
*/
public Builder section() {
return start(document.createElement("section"));
}
/**
* Starts a new {@code <aside>} container. The element must be closed with {@link #end()}.
*/
public Builder aside() {
return start(document.createElement("aside"));
}
/**
* Starts a new {@code <footer>} container. The element must be closed with {@link #end()}.
*/
public Builder footer() {
return start(document.createElement("footer"));
}
/**
* Starts a new {@code <p>} container. The element must be closed with {@link #end()}.
*/
public Builder p() {
return start(document.createElement("p"));
}
/**
* Starts a new {@code <ol>} container. The element must be closed with {@link #end()}.
*/
public Builder ol() {
return start(document.createElement("ol"));
}
/**
* Starts a new {@code <ul>} container. The element must be closed with {@link #end()}.
*/
public Builder ul() {
return start(document.createElement("ul"));
}
/**
* Starts a new {@code <li>} container. The element must be closed with {@link #end()}.
*/
public Builder li() {
return start(document.createLIElement());
}
/**
* Starts a new {@code <a>} container. The element must be closed with {@link #end()}.
*/
public Builder a() {
return start(document.createElement("a"));
}
/**
* Starts a new {@code <div>} container. The element must be closed with {@link #end()}.
*/
public Builder div() {
return start(document.createDivElement());
}
/**
* Starts a new {@code <span>} container. The element must be closed with {@link #end()}.
*/
public Builder span() {
return start(document.createSpanElement());
}
/**
* Starts the named container. The element must be closed with {@link #end()}.
*/
public Builder start(String tag) {
return start(document.createElement(tag));
}
/**
* Adds the given element as new container. The element must be closed with {@link #end()}.
*/
public Builder start(Element element) {
elements.push(new ElementInfo(element, true, level));
level++;
return this;
}
public Builder end() {
assertCurrent();
if (level == 0) {
throw new IllegalStateException("Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
List<ElementInfo> children = new ArrayList<>();
while (elements.peek().level == level) {
children.add(elements.pop());
}
Collections.reverse(children);
if (!elements.peek().container) {
throw new IllegalStateException("Closing element " + elements.peek().element + " is no container");
}
Element closingElement = elements.peek().element;
for (ElementInfo child : children) {
closingElement.appendChild(child.element);
}
level
return this;
}
private String dumpElements() {
return elements.toString();
}
/**
* Starts a new form. The element must be closed with {@link #end()}.
*/
public Builder form() {
return start(document.createFormElement());
}
/**
* Starts a new form label. The element must be closed with {@link #end()}.
*/
public Builder label() {
return start(document.createLabelElement());
}
/**
* Starts a new button. The element must be closed with {@link #end()}.
*/
public Builder button() {
return input(InputType.button);
}
/**
* Starts a new select box. The element must be closed with {@link #end()}.
*/
public Builder select() {
return input(InputType.select);
}
/**
* Starts an option to be used inside a select box. The element must be closed with {@link #end()}.
*/
public Builder option() {
return start(document.createOptionElement());
}
/**
* Starts a new textarea. The element must be closed with {@link #end()}.
*/
public Builder textarea() {
return input(InputType.textarea);
}
/**
* Creates the given input field. See {@link InputType} for details
* whether a container or simple element is created.
*/
public Builder input(InputType type) {
switch (type) {
case button:
start(document.createButtonElement());
break;
case color:
case checkbox:
case date:
case datetime:
case email:
case file:
case hidden:
case image:
case month:
case number:
case password:
case radio:
case range:
case reset:
case search:
case tel:
case text:
case time:
case url:
case week:
InputElement inputElement = document.createInputElement();
inputElement.setType(type.name());
add(inputElement);
break;
case select:
start(document.createSelectElement());
break;
case textarea:
start(document.createTextAreaElement());
break;
}
return this;
}
/**
* Creates and adds the named element. The element must not be closed using {@link #end()}.
*/
public Builder add(String tag) {
return add(document.createElement(tag));
}
/**
* Adds the given element. The element must not be closed using {@link #end()}.
*/
public Builder add(Element element) {
assertCurrent();
elements.push(new ElementInfo(element, false, level));
return this;
}
/**
* Sets the id of the last added element.
*/
public Builder id(String id) {
assertCurrent();
elements.peek().element.setId(id);
return this;
}
/**
* Sets the title of the last added element.
*/
public Builder title(String title) {
assertCurrent();
elements.peek().element.setTitle(title);
return this;
}
/**
* Sets the css classes for the last added element.
*/
public Builder css(String classes) {
assertCurrent();
elements.peek().element.setClassName(classes);
return this;
}
/**
* Sets the css style for the last added element.
*/
public Builder style(String style) {
assertCurrent();
elements.peek().element.getStyle().setCssText(style);
return this;
}
/**
* Adds an attribute to the last added element.
*/
public Builder attr(String name, String value) {
assertCurrent();
elements.peek().element.setAttribute(name, value);
return this;
}
/**
* Adds a {@code data-} attribute to the last added element.
*
* @param name The name of the data attribute w/o the {@code data-} prefix. However it won't be added if it's
* already present.
*/
public Builder data(String name, String value) {
String safeName = name.startsWith("data-") ? name : "data-" + name;
return attr(safeName, value);
}
/**
* Adds an {@code aria-} attribute to the last added element.
*
* @param name The name of the aria attribute w/o the {@code aria-} prefix. However it won't be added if it's
* already present.
*/
public Builder aria(String name, String value) {
String safeName = name.startsWith("aria-") ? name : "aria-" + name;
return attr(safeName, value);
}
/**
* Sets the inner HTML on the last added element.
*/
public Builder innerHtml(SafeHtml html) {
assertCurrent();
elements.peek().element.setInnerHTML(html.asString());
return this;
}
/**
* Sets the inner text on the last added element using {@link Element#setTextContent(String)}.
*/
public Builder innerText(String text) {
assertCurrent();
elements.peek().element.setTextContent(text);
return this;
}
private void assertCurrent() {
if (elements.isEmpty()) {
throw new IllegalStateException("No current element");
}
}
/**
* Adds the given event listener to the the last added element.
*/
public Builder on(EventType type, EventListener listener) {
assertCurrent();
Element element = elements.peek().element;
type.register(element, listener);
return this;
}
/**
* Stores a named reference for the last added element. The element can be retrieved later on using
* {@link #referenceFor(String)}.
*/
public Builder rememberAs(String id) {
assertCurrent();
references.put(id, elements.peek().element);
return this;
}
/**
* Returns the element which was stored using {@link #rememberAs(String)}.
*
* @throws NoSuchElementException if no element was stored under that id.
*/
@SuppressWarnings("unchecked")
public <T extends Element> T referenceFor(String id) {
if (!references.containsKey(id)) {
throw new NoSuchElementException("No element reference found for '" + id + "'");
}
return (T) references.get(id);
}
@SuppressWarnings("unchecked")
public <T extends Element> T build() {
if (level != 0 && elements.size() != 1) {
throw new IllegalStateException("Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
return (T) elements.pop().element;
}
}
public static Iterator<Element> iterator(Element parent) {
return parent != null ? new ChildrenIterator(parent) : Collections.<Element>emptyList().iterator();
}
public static Iterable<Element> children(Element parent) {
return () -> iterator(parent);
}
public static void innerHtml(Element element, SafeHtml html) {
if (element != null) {
element.setInnerHTML(html.asString());
}
}
/**
* Removes all child elements from {@code element}
*/
public static void removeChildrenFrom(final Element element) {
if (element != null) {
while (element.getFirstChild() != null) {
element.removeChild(element.getFirstChild());
}
}
}
/**
* Looks for an element in the document using the CSS selector {@code [data-element=<name>]}.
*/
public static Element dataElement(String name) {
return Browser.getDocument().querySelector("[data-element=" + name + "]");
}
/**
* Looks for an element below {@code context} using the CSS selector {@code [data-element=<name>]}
*/
public static Element dataElement(Element context, String name) {
return context != null ? context.querySelector("[data-element=" + name + "]") : null;
}
public static boolean isVisible(Element element) {
return element != null && !"none".equals(element.getStyle().getDisplay());
}
public static void setVisible(Element element, boolean visible) {
if (element != null) {
element.getStyle().setDisplay(visible ? "" : "none");
}
}
private static class ElementWidget extends Widget {
ElementWidget(final Element element) {
setElement(com.google.gwt.dom.client.Element.as((JavaScriptObject) element));
}
}
public static Widget asWidget(IsElement element) {
return asWidget(element.asElement());
}
public static Widget asWidget(Element element) {
return new ElementWidget(element);
}
public static Element asElement(IsWidget widget) {
return asElement(widget.asWidget());
}
public static Element asElement(Widget widget) {
return asElement(widget.getElement());
}
public static Element asElement(com.google.gwt.dom.client.Element element) {
return element.cast();
}
} |
package org.zstack.core.cloudbus;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.jmx.JmxFacade;
import org.zstack.header.Component;
import org.zstack.header.apimediator.ApiMediatorConstant;
import org.zstack.header.message.*;
import org.zstack.utils.BeanUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import javax.management.MXBean;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@MXBean
public class CloudBusJMX implements Component, BeforeSendMessageInterceptor,
BeforeDeliveryMessageInterceptor, BeforePublishEventInterceptor, CloudBusMXBean {
private Map<String, MessageStatistic> statistics = new HashMap<>();
private static final CLogger logger = Utils.getLogger(CloudBusJMX.class);
@Autowired
private CloudBus bus;
@Autowired
private JmxFacade jmxf;
class Bundle {
Long startTime;
MessageStatistic statistic;
Message msg;
}
private Cache<String, Bundle> messageStartTime = CacheBuilder.newBuilder()
.maximumSize(30000)
.build();
@Override
public boolean start() {
BeanUtils.reflections.getSubTypesOf(NeedReplyMessage.class).stream().filter(clz -> !Modifier.isAbstract(clz.getModifiers()))
.forEach(clz -> {
MessageStatistic stat = new MessageStatistic();
stat.setMessageClassName(clz.getName());
statistics.put(clz.getName(), stat);
});
bus.installBeforeDeliveryMessageInterceptor(this);
bus.installBeforePublishEventInterceptor(this);
bus.installBeforeSendMessageInterceptor(this);
CloudBusGlobalConfig.STATISTICS_ON.installUpdateExtension((oldConfig, newConfig) -> {
if (!newConfig.value(Boolean.class)) {
messageStartTime.invalidateAll();
}
});
jmxf.registerBean("CloudBus", this);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public int orderOfBeforeDeliveryMessageInterceptor() {
return 0;
}
private void collectStats(Message msg) {
if (!CloudBusGlobalConfig.STATISTICS_ON.value(Boolean.class)) {
return;
}
String msgId;
if (msg instanceof MessageReply) {
msgId = msg.getHeaderEntry(CloudBus.HEADER_CORRELATION_ID);
} else {
msgId = ((APIEvent) msg).getApiId();
}
Bundle bundle = messageStartTime.getIfPresent(msgId);
if (bundle == null) {
logger.warn(String.format("cannot find bundle for message[id:%s]", msg.getId()));
return;
}
long cost = System.currentTimeMillis() - bundle.startTime;
bundle.statistic.count(cost);
messageStartTime.invalidate(msgId);
}
@Override
public void beforeDeliveryMessage(Message msg) {
if (msg instanceof MessageReply) {
collectStats(msg);
}
}
@Override
public int orderOfBeforePublishEventInterceptor() {
return 0;
}
@Override
public void beforePublishEvent(Event evt) {
if (evt instanceof APIEvent) {
collectStats(evt);
}
}
@Override
public int orderOfBeforeSendMessageInterceptor() {
return 0;
}
@Override
public void beforeSendMessage(Message msg) {
if (!CloudBusGlobalConfig.STATISTICS_ON.value(Boolean.class)) {
return;
}
if (msg.getServiceId().equals(ApiMediatorConstant.SERVICE_ID)) {
// the API message will be routed by ApiMediator,
// filter out this message to avoid reporting the same
// API message twice
return;
}
Bundle bundle = new Bundle();
bundle.startTime = System.currentTimeMillis();
bundle.msg = msg;
bundle.statistic = statistics.get(msg.getClass().getName());
messageStartTime.put(msg.getId(), bundle);
}
public Map<String, MessageStatistic> getStatistics() {
return statistics;
}
@Override
public List<WaitingReplyMessageStatistic> getWaitingReplyMessageStatistic() {
List<WaitingReplyMessageStatistic> ret = new ArrayList<WaitingReplyMessageStatistic>();
long currentTime = System.currentTimeMillis();
messageStartTime.asMap().values().forEach(bundle -> {
Message msg = bundle.msg;
WaitingReplyMessageStatistic statistic = new WaitingReplyMessageStatistic(
msg.getClass().getName(),
currentTime - msg.getCreatedTime(),
msg.getId(),
msg.getServiceId()
);
ret.add(statistic);
});
return ret;
}
@Override
public WaitingMessageSummaryStatistic getWaitingReplyMessageSummaryStatistic() {
List<WaitingReplyMessageStatistic> ret = getWaitingReplyMessageStatistic();
String mostWaitingMsgName = null;
String longestWaitingMsgName = null;
long most = 0;
long longest = 0;
Map<String, Integer> countMap = new HashMap<String, Integer>();
for (WaitingReplyMessageStatistic s : ret) {
if (s.getWaitingTime() > longest) {
longest = s.getWaitingTime();
longestWaitingMsgName = s.getMessageName();
}
Integer count = countMap.get(s.getMessageName());
count = count == null ? 1 : ++ count;
countMap.put(s.getMessageName(), count);
if (count > most) {
most = count;
mostWaitingMsgName = s.getMessageName();
}
}
return new WaitingMessageSummaryStatistic(
ret.size(),
countMap,
mostWaitingMsgName,
most,
longestWaitingMsgName,
longest
);
}
} |
package roart.evaluation;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import roart.aggregate.Aggregator;
import roart.aggregate.MLIndicator;
import roart.aggregate.MLMACD;
import roart.calculate.CalcNodeUtils;
import roart.category.Category;
import roart.category.CategoryConstants;
import roart.config.ConfigConstants;
import roart.config.MyConfig;
import roart.config.MyMyConfig;
import roart.evolution.Individual;
import roart.ml.NNConfig;
import roart.ml.NNConfigs;
import roart.pipeline.Pipeline;
import roart.pipeline.PipelineConstants;
import roart.queue.MyExecutors;
import roart.service.ControlService;
import roart.util.Constants;
public class NeuralNetEvaluation extends Evaluation {
private Logger log = LoggerFactory.getLogger(this.getClass());
private MyMyConfig conf;
private String ml;
private Pipeline[] dataReaders;
private Category[] categories;
private String key;
private NNConfig nnConfig;
public NeuralNetEvaluation(MyMyConfig conf, String ml, Pipeline[] dataReaders, Category[] categories, String key, NNConfig nnConfig) {
this.conf = conf.copy();
this.ml = ml;
this.dataReaders = dataReaders;
this.categories = categories;
this.key = key;
this.nnConfig = nnConfig;
}
public MyMyConfig getConf() {
return conf;
}
public void setConf(MyMyConfig conf) {
this.conf = conf;
}
public NNConfig getNnConfig() {
return nnConfig;
}
public void setNnConfig(NNConfig nnConfig) {
this.nnConfig = nnConfig;
}
@Override
public double getEvaluations(int j) throws JsonParseException, JsonMappingException, IOException {
return 0;
}
@Override
public void mutate() {
nnConfig.mutate();
}
@Override
public void getRandom()
throws JsonParseException, JsonMappingException, IOException {
nnConfig.randomize();
}
@Override
public void transformToNode()
throws JsonParseException, JsonMappingException, IOException {
}
@Override
public void normalize() {
}
@Override
public void transformFromNode()
throws JsonParseException, JsonMappingException, IOException {
}
@Override
public double getFitness()
throws JsonParseException, JsonMappingException, IOException {
Aggregator aggregate = null;
/*
MyCallable callable = new MyCallable(conf, ml, dataReaders, categories);
Future<Aggregator> future = MyExecutors.run(callable);
aggregate = future.get();
*/
try {
aggregate = new MyFactory().myfactory(conf, ml, dataReaders, categories);
} catch (Exception e) {
log.info(Constants.EXCEPTION, e);
}
Map<String, Object> map = (Map<String, Object>) aggregate.getLocalResultMap().get(PipelineConstants.PROBABILITY);
double fitness = 0;
for (Entry<String, Object> entry : map.entrySet()) {
Double value = (Double) entry.getValue();
fitness += value;
}
return fitness;
}
class MyFactory {
public Aggregator myfactory(MyMyConfig conf, String ml, Pipeline[] dataReaders, Category[] categories) throws Exception {
NNConfigs nnConfigs = new NNConfigs();
nnConfigs.set(key, nnConfig);
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(nnConfigs);
Aggregator aggregate = null;
if (ml.equals(PipelineConstants.MLMACD)) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSMLMACDMLCONFIG, value);
aggregate = new MLMACD(conf, Constants.PRICE, null, null, CategoryConstants.PRICE, 0, categories);
}
if (ml.equals(PipelineConstants.MLINDICATOR)) {
conf.getConfigValueMap().put(ConfigConstants.AGGREGATORSINDICATORMLCONFIG, value);
aggregate = new MLIndicator(conf, Constants.PRICE, null, null, CategoryConstants.PRICE, 0, categories, dataReaders);
}
return aggregate;
}
}
class MyCallable implements Callable {
private MyMyConfig conf;
private String ml;
private Pipeline[] dataReaders;
private Category[] categories;
public MyCallable(MyMyConfig conf, String ml, Pipeline[] dataReaders, Category[] categories) {
this.conf = conf;
this.ml = ml;
this.dataReaders = dataReaders;
this.categories = categories;
}
@Override
public Aggregator call() throws Exception {
return new MyFactory().myfactory(conf, ml, dataReaders, categories);
}
}
@Override
public Individual crossover(Evaluation evaluation) {
NNConfig newNNConfig = nnConfig.crossover(((NeuralNetEvaluation) evaluation).nnConfig);
NeuralNetEvaluation eval = new NeuralNetEvaluation(conf, ml, dataReaders, categories, key, newNNConfig);
return new Individual(eval);
}
@Override
public Evaluation copy() {
NNConfig newNNConfig = null;
if (nnConfig != null) {
newNNConfig = (NNConfig) (nnConfig.copy());
}
return new NeuralNetEvaluation(conf, ml, dataReaders, categories, key, newNNConfig);
}
@Override
public boolean isEmpty() {
return nnConfig == null || nnConfig.empty();
}
@Override
public String toString() {
return key + " " + nnConfig;
}
} |
/* 4.1 Implement a function to check if a binary tree is balanced. For the
* purposes of this question, a balanced tree is defined to be a tree such
* that the heights of the two subtrees of any node never differ by more than
* one.
*/
public class P0401 {
private class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
}
}
public boolean isBalanced(Node root) {
if (root == null) return true;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
boolean isRootBalanced = Math.abs(leftHeight - rightHeight) <= 1;
if (isRootBalanced)
return isBalanced(root.left) && isBalanced(root.right);
else
return false;
// return isRootBalanced && isBalanced(root.left) && isBalanced(root.right);
}
public int height(Node x) {
if (x == null) return 0;
return 1 + Math.max(height(x.left), height(x.right));
}
// an improved solution:
// every time we calculate height, the heights of subtrees (subtrees of
// subtrees) are repeatedly calculated, we coudl avaoid this redundancy by
// adding extra variables to record the heights of subtrees at each level.
public boolean isBalanced2(Node root, int[] height) {
if (root == null) {
height[0] = 0;
return true;
}
int[] leftHeight = new int[1];
int[] rightHeight = new int[1];
boolean isLeftBalanced = isBalanced2(root.left, leftHeight);
boolean isRightBalanced = isBalanced2(root.right, rightHeight);
if (isLeftBalanced && isRightBalanced) {
if (Math.abs(leftHeight[0] - rightHeight[0]) <= 1) {
int tmp = (leftHeight[0] > rightHeight[0]) ? leftHeight[0] : rightHeight[0];
height[0] = height[0] + tmp + 1;
System.out.println(height[0]);
return true;
}
}
return false;
}
public Node buildTree() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.left.left.left = new Node(7);
root.left.left.left.left = new Node(8);
return root;
}
public static void main(String[] args) {
P0401 p0401 = new P0401();
Node root = p0401.buildTree();
int[] height = new int[1];
System.out.println(p0401.isBalanced2(root, height));
System.out.println(p0401.isBalanced(root));
}
} |
package com.psddev.dari.db;
import com.psddev.dari.util.CodeUtils;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PeriodicCache;
import com.psddev.dari.util.PullThroughValue;
import com.psddev.dari.util.Task;
import com.psddev.dari.util.TypeDefinition;
import java.util.ArrayList;
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 java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseEnvironment implements ObjectStruct {
public static final String GLOBAL_FIELDS_FIELD = "globalFields";
public static final String GLOBAL_INDEXES_FIELD = "globalIndexes";
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseEnvironment.class);
private final Database database;
private final boolean initializeClasses;
{
CodeUtils.addRedefineClassesListener(new CodeUtils.RedefineClassesListener() {
@Override
public void redefined(Set<Class<?>> classes) {
for (Class<?> c : classes) {
if (Recordable.class.isAssignableFrom(c)) {
TypeDefinition.Static.invalidateAll();
refreshTypes();
break;
}
}
}
});
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database, boolean initializeClasses) {
this.database = database;
this.initializeClasses = initializeClasses;
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database) {
this(database, true);
}
/** Returns the backing database. */
public Database getDatabase() {
return database;
}
/** Globals are stored at FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF. */
private static final UUID GLOBALS_ID = new UUID(-1L, -1L);
/** Field where the root type is stored within the globals. */
private static final String ROOT_TYPE_FIELD = "rootType";
private volatile State globals;
private volatile Date lastGlobalsUpdate;
private volatile Date lastTypesUpdate;
private volatile TypesCache permanentTypes = new TypesCache();
private final ThreadLocal<TypesCache> temporaryTypesLocal = new ThreadLocal<TypesCache>();
/** Aggregate of all maps used to cache type information. */
private static class TypesCache {
public final Map<String, ObjectType> byClassName = new HashMap<String, ObjectType>();
public final Map<UUID, ObjectType> byId = new HashMap<UUID, ObjectType>();
public final Map<String, ObjectType> byName = new HashMap<String, ObjectType>();
public final Map<String, Set<ObjectType>> byGroup = new HashMap<String, Set<ObjectType>>();
public final Set<UUID> changed = new HashSet<UUID>();
/** Adds the given {@code type} to all type cache maps. */
public void add(ObjectType type) {
String className = type.getObjectClassName();
if (!ObjectUtils.isBlank(className)) {
byClassName.put(className, type);
}
byId.put(type.getId(), type);
String internalName = type.getInternalName();
if (!ObjectUtils.isBlank(internalName)) {
byName.put(internalName, type);
}
for (String group : type.getGroups()) {
Set<ObjectType> groupTypes = byGroup.get(group);
if (groupTypes == null) {
groupTypes = new HashSet<ObjectType>();
byGroup.put(group, groupTypes);
}
groupTypes.remove(type);
groupTypes.add(type);
}
}
}
private final AtomicBoolean bootstrapDone = new AtomicBoolean();
private final AtomicReference<Thread> bootstrapThread = new AtomicReference<Thread>();
// Bootstraps the globals and types for the first time. Most methods
// in this class should call this before performing any action.
private void bootstrap() {
if (bootstrapDone.get()) {
return;
}
Thread currentThread = Thread.currentThread();
while (true) {
if (currentThread.equals(bootstrapThread.get())) {
return;
} else if (bootstrapThread.compareAndSet(null, currentThread)) {
break;
} else {
synchronized (bootstrapThread) {
while (bootstrapThread.get() != null) {
try {
bootstrapThread.wait();
} catch (InterruptedException ex) {
return;
}
}
}
}
}
try {
// Fetch the globals, which includes a reference to the root
// type. References to other objects can't be resolved,
// because the type definitions haven't been loaded yet.
refreshGlobals();
ObjectType rootType = getRootType();
if (rootType != null) {
// This isn't cleared later, because that's done within
// {@link refreshTypes} anyway.
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
temporaryTypes.add(rootType);
LOGGER.info(
"Root type ID for [{}] is [{}]",
getDatabase().getName(),
rootType.getId());
}
// Load all other types based on the root type. Then globals
// again in case they reference other typed objects. Then
// types again using the information from the fully resolved
// globals.
refreshTypes();
refreshGlobals();
refreshTypes();
refresher.schedule(5.0, 5.0);
bootstrapDone.set(true);
} finally {
bootstrapThread.set(null);
synchronized (bootstrapThread) {
bootstrapThread.notifyAll();
}
}
}
/** Task for updating the globals and the types periodically. */
private final Task refresher = new Task(PeriodicCache.TASK_EXECUTOR_NAME, null) {
@Override
public void doTask() {
Database database = getDatabase();
Date newGlobalsUpdate = Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
lastUpdate();
if (newGlobalsUpdate != null &&
(lastGlobalsUpdate == null ||
newGlobalsUpdate.after(lastGlobalsUpdate))) {
refreshGlobals();
}
Date newTypesUpdate = Query.
from(ObjectType.class).
using(database).
lastUpdate();
if (newTypesUpdate != null &&
(lastTypesUpdate == null ||
newTypesUpdate.after(lastTypesUpdate))) {
refreshTypes();
}
}
};
/** Immediately refreshes all globals using the backing database. */
public synchronized void refreshGlobals() {
bootstrap();
Database database = getDatabase();
LOGGER.info("Loading globals from [{}]", database.getName());
State newGlobals = State.getInstance(Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
first());
if (newGlobals == null) {
newGlobals = new State();
newGlobals.setDatabase(database);
newGlobals.setId(GLOBALS_ID);
newGlobals.save();
}
globals = newGlobals;
lastGlobalsUpdate = new Date();
fieldsCache.invalidate();
indexesCache.invalidate();
}
/** Immediately refreshes all types using the backing database. */
public synchronized void refreshTypes() {
bootstrap();
Database database = getDatabase();
try {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
List<ObjectType> types = Query.
from(ObjectType.class).
using(database).
selectAll();
int typesSize = types.size();
LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());
// Load all types from the database first.
for (ObjectType type : types) {
type.getFields().size(); // Pre-fetch.
temporaryTypes.add(type);
}
if (initializeClasses) {
// Make sure that the root type exists.
ObjectType rootType = getRootType();
State rootTypeState;
if (rootType != null) {
rootTypeState = rootType.getState();
} else {
rootType = new ObjectType();
rootTypeState = rootType.getState();
rootTypeState.setDatabase(database);
}
Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
UUID rootTypeId = rootTypeState.getId();
rootTypeState.setTypeId(rootTypeId);
rootType.setObjectClassName(ObjectType.class.getName());
rootType.initialize();
temporaryTypes.add(rootType);
try {
database.beginWrites();
// Make the new root type available to other types.
temporaryTypes.add(rootType);
if (rootTypeState.isNew()) {
putGlobal(ROOT_TYPE_FIELD, rootType);
} else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
temporaryTypes.changed.add(rootTypeId);
}
Set<Class<? extends Recordable>> objectClasses = ObjectUtils.findClasses(Recordable.class);
for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
Class<? extends Recordable> objectClass = i.next();
if (objectClass.isAnonymousClass()) {
i.remove();
}
}
Set<Class<?>> globalModifications = new HashSet<Class<?>>();
Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>();
// Make sure all types are accessible to the rest of the
// system as soon as possible, so that references can be
// resolved properly later.
for (Class<?> objectClass : objectClasses) {
ObjectType type = getTypeByClass(objectClass);
if (type == null) {
type = new ObjectType();
type.getState().setDatabase(database);
type.setObjectClassName(objectClass.getName());
}
typeModifications.put(type, new ArrayList<Class<?>>());
temporaryTypes.add(type);
}
// Separate out all modifications from regular types.
for (Class<?> objectClass : objectClasses) {
if (!Modification.class.isAssignableFrom(objectClass)) {
continue;
}
@SuppressWarnings("unchecked")
Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass);
if (modifiedClasses.contains(Object.class)) {
globalModifications.add(objectClass);
continue;
}
for (Class<?> modifiedClass : modifiedClasses) {
List<Class<?>> assignableClasses = new ArrayList<Class<?>>();
for (Class<?> c : objectClasses) {
if (modifiedClass.isAssignableFrom(c)) {
assignableClasses.add(c);
}
}
for (Class<?> assignableClass : assignableClasses) {
ObjectType type = getTypeByClass(assignableClass);
if (type != null) {
List<Class<?>> modifications = typeModifications.get(type);
if (modifications == null) {
modifications = new ArrayList<Class<?>>();
typeModifications.put(type, modifications);
}
modifications.add(objectClass);
}
}
}
}
// Apply global modifications.
for (Class<?> modification : globalModifications) {
ObjectType.modifyAll(database, modification);
}
// Initialize all types.
List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
initializeAndModify(temporaryTypes, rootType, rootTypeModifications);
if (rootTypeModifications != null) {
for (Class<?> modification : rootTypeModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
ObjectType fieldType = getTypeByClass(ObjectField.class);
List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
initializeAndModify(temporaryTypes, fieldType, fieldModifications);
if (fieldModifications != null) {
for (Class<?> modification : fieldModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
}
database.commitWrites();
} finally {
database.endWrites();
}
}
// Merge temporary types into new permanent types.
TypesCache newPermanentTypes = new TypesCache();
for (ObjectType type : permanentTypes.byId.values()) {
newPermanentTypes.add(type);
}
for (ObjectType type : temporaryTypes.byId.values()) {
newPermanentTypes.add(type);
}
newPermanentTypes.changed.addAll(temporaryTypes.changed);
newPermanentTypes.changed.addAll(permanentTypes.changed);
permanentTypes = newPermanentTypes;
lastTypesUpdate = new Date();
} finally {
temporaryTypesLocal.remove();
}
}
private static void initializeAndModify(TypesCache temporaryTypes, ObjectType type, List<Class<?>> modifications) {
State typeState = type.getState();
Map<String, Object> typeOriginals = typeState.getSimpleValues();
try {
type.initialize();
temporaryTypes.add(type);
// Apply type-specific modifications.
if (modifications != null) {
for (Class<?> modification : modifications) {
type.modify(modification);
}
}
} catch (IncompatibleClassChangeError ex) {
LOGGER.info(
"Skipped initializing [{}] because its class is in an inconsistent state! ([{}])",
type.getInternalName(),
ex.getMessage());
}
if (typeState.isNew()) {
type.save();
} else if (!typeState.getSimpleValues().equals(typeOriginals)) {
temporaryTypes.changed.add(type.getId());
}
}
/** Returns the global value at the given {@code key}. */
public Object getGlobal(String key) {
bootstrap();
return globals != null ? globals.getValue(key) : null;
}
/** Returns the root type from the globals. */
private ObjectType getRootType() {
Object rootType = getGlobal(ROOT_TYPE_FIELD);
return ObjectUtils.to(ObjectType.class, rootType != null ?
rootType :
getGlobal("rootRecordType"));
}
/** Puts the given global {@code value} at the given {@code key}. */
public void putGlobal(String key, Object value) {
bootstrap();
globals.putValue(key, value);
globals.save();
}
@Override
public DatabaseEnvironment getEnvironment() {
return this;
}
@Override
public List<ObjectField> getFields() {
return new ArrayList<ObjectField>(fieldsCache.get().values());
}
private final PullThroughValue<Map<String, ObjectField>> fieldsCache = new PullThroughValue<Map<String, ObjectField>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectField> produce() {
Object definitions = getGlobal(GLOBAL_FIELDS_FIELD);
return ObjectField.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectField getField(String name) {
return fieldsCache.get().get(name);
}
@Override
public void setFields(List<ObjectField> fields) {
putGlobal(GLOBAL_FIELDS_FIELD, ObjectField.Static.convertInstancesToDefinitions(fields));
fieldsCache.invalidate();
}
@Override
public List<ObjectIndex> getIndexes() {
return new ArrayList<ObjectIndex>(indexesCache.get().values());
}
private final PullThroughValue<Map<String, ObjectIndex>> indexesCache = new PullThroughValue<Map<String, ObjectIndex>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectIndex> produce() {
Object definitions = getGlobal(GLOBAL_INDEXES_FIELD);
return ObjectIndex.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectIndex getIndex(String name) {
return indexesCache.get().get(name);
}
@Override
public void setIndexes(List<ObjectIndex> indexes) {
putGlobal(GLOBAL_INDEXES_FIELD, ObjectIndex.Static.convertInstancesToDefinitions(indexes));
indexesCache.invalidate();
}
/**
* Initializes the given {@code objectClasses} so that they are
* usable as {@linkplain ObjectType types}.
*/
public void initializeTypes(Iterable<Class<?>> objectClasses) {
bootstrap();
Set<String> classNames = new HashSet<String>();
for (Class<?> objectClass : objectClasses) {
classNames.add(objectClass.getName());
}
for (ObjectType type : getTypes()) {
UUID id = type.getId();
if (classNames.contains(type.getObjectClassName())) {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if ((temporaryTypes != null &&
temporaryTypesLocal.get().changed.contains(id)) ||
permanentTypes.changed.contains(id)) {
type.save();
}
}
}
}
/**
* Returns all types.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypes() {
bootstrap();
Set<ObjectType> types = new HashSet<ObjectType>();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
types.addAll(temporaryTypes.byId.values());
}
types.addAll(permanentTypes.byId.values());
return types;
}
/**
* Returns the type associated with the given {@code id}.
* @return May be {@code null}.
*/
public ObjectType getTypeById(UUID id) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byId.get(id);
if (type != null) {
return type;
}
}
return permanentTypes.byId.get(id);
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByName(String name) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byName.get(name);
if (type != null) {
return type;
}
}
return permanentTypes.byName.get(name);
}
/**
* Returns a set of types associated with the given {@code group}.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypesByGroup(String group) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
Set<ObjectType> tTypes;
if (temporaryTypes != null) {
tTypes = temporaryTypes.byGroup.get(group);
} else {
tTypes = null;
}
Set<ObjectType> pTypes = permanentTypes.byGroup.get(group);
if (tTypes == null) {
return pTypes == null ?
new HashSet<ObjectType>() :
new HashSet<ObjectType>(pTypes);
} else {
tTypes = new HashSet<ObjectType>(tTypes);
if (pTypes != null) {
tTypes.addAll(pTypes);
}
return tTypes;
}
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByClass(Class<?> objectClass) {
bootstrap();
String className = objectClass.getName();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byClassName.get(className);
if (type != null) {
return type;
}
}
return permanentTypes.byClassName.get(className);
}
/**
* Creates an object represented by the given {@code typeId} and
* {@code id}.
*/
public Object createObject(UUID typeId, UUID id) {
bootstrap();
Class<?> objectClass = null;
ObjectType type = null;
if (typeId != null && !GLOBALS_ID.equals(id)) {
if (typeId.equals(id)) {
objectClass = ObjectType.class;
} else {
type = getTypeById(typeId);
if (type != null) {
objectClass = type.isAbstract() ?
Record.class :
type.getObjectClass();
}
}
}
boolean hasClass = true;
if (objectClass == null) {
objectClass = Record.class;
hasClass = false;
}
Object object = TypeDefinition.getInstance(objectClass).newInstance();
State state = State.getInstance(object);
state.setDatabase(getDatabase());
state.setId(id);
state.setTypeId(typeId);
if (type != null && !hasClass) {
for (ObjectField field : type.getFields()) {
Object defaultValue = field.getDefaultValue();
if (defaultValue != null) {
state.put(field.getInternalName(), defaultValue);
}
}
}
return object;
}
} |
package nl.mpi.kinnate.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeContainer;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.data.ArbilTreeHelper;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.BugCatcherManager;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.entityindexer.EntityService;
import nl.mpi.kinnate.entityindexer.EntityServiceException;
import nl.mpi.kinnate.entityindexer.ProcessAbortException;
import nl.mpi.kinnate.entityindexer.QueryParser;
import nl.mpi.kinnate.gedcomimport.ImportException;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.kindata.VisiblePanelSetting;
import nl.mpi.kinnate.kindata.VisiblePanelSetting.PanelType;
import nl.mpi.kinnate.kindocument.ProfileManager;
import nl.mpi.kinnate.kintypestrings.ImportRequiredException;
import nl.mpi.kinnate.kintypestrings.KinTermCalculator;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter;
import nl.mpi.kinnate.svg.DataStoreSvg.DiagramMode;
import nl.mpi.kinnate.svg.GraphPanel;
import nl.mpi.kinnate.svg.MouseListenerSvg;
import nl.mpi.kinnate.ui.entityprofiles.CmdiProfileSelectionPanel;
import nl.mpi.kinnate.ui.kintypeeditor.KinTypeDefinitions;
import nl.mpi.kinnate.ui.menu.DocumentNewMenu.DocumentType;
import nl.mpi.kinnate.ui.relationsettings.RelationSettingsPanel;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer {
private EntityCollection entityCollection;
private KinTypeStringInput kinTypeStringInput;
private ArrayList<KinTypeStringProvider> kinTypeStringProviders;
private GraphPanel graphPanel;
private EgoSelectionPanel egoSelectionPanel;
private ProjectTreePanel projectTree = null;
private ArchiveEntityLinkerPanel archiveEntityLinkerPanelRemote;
private ArchiveEntityLinkerPanel archiveEntityLinkerPanelLocal;
private ArchiveEntityLinkerPanel archiveEntityLinkerPanelMpiRemote;
private HidePane kinTermHidePane;
private HidePane kinTypeHidePane;
private EntityService entityIndex;
private JProgressBar progressBar;
static private File defaultDiagramTemplate;
private HashMap<ArbilDataNode, UniqueIdentifier> registeredArbilDataNode;
private HashMap<ArbilNode, Boolean> arbilDataNodesChangedStatus;
// private ArrayList<ArbilTree> treeLoadQueue = new ArrayList<ArbilTree>();
private SessionStorage sessionStorage;
private ArbilWindowManager dialogHandler;
private ArbilDataNodeLoader dataNodeLoader;
private ArbilTreeHelper treeHelper;
private KinDragTransferHandler dragTransferHandler;
private AbstractDiagramManager diagramWindowManager;
public KinDiagramPanel(URI existingFile, boolean savableType, SessionStorage sessionStorage, ArbilWindowManager dialogHandler, ArbilDataNodeLoader dataNodeLoader, ArbilTreeHelper treeHelper, EntityCollection entityCollection, AbstractDiagramManager diagramWindowManager) {
this.sessionStorage = sessionStorage;
this.dialogHandler = dialogHandler;
this.dataNodeLoader = dataNodeLoader;
this.treeHelper = treeHelper;
this.entityCollection = entityCollection;
this.diagramWindowManager = diagramWindowManager;
initKinDiagramPanel(existingFile, null, savableType);
}
public KinDiagramPanel(DocumentType documentType, SessionStorage sessionStorage, ArbilWindowManager dialogHandler, ArbilDataNodeLoader dataNodeLoader, ArbilTreeHelper treeHelper, EntityCollection entityCollection, AbstractDiagramManager diagramWindowManager) {
this.sessionStorage = sessionStorage;
this.dialogHandler = dialogHandler;
this.dataNodeLoader = dataNodeLoader;
this.treeHelper = treeHelper;
this.entityCollection = entityCollection;
this.diagramWindowManager = diagramWindowManager;
initKinDiagramPanel(null, documentType, false);
}
private void initKinDiagramPanel(URI existingFile, DocumentType documentType, boolean savableType) {
progressBar = new JProgressBar();
graphPanel = new GraphPanel(this, dialogHandler, sessionStorage, entityCollection, dataNodeLoader);
kinTypeStringInput = new KinTypeStringInput(graphPanel.dataStoreSvg);
boolean showKinTerms = false;
boolean showArchiveLinker = false;
boolean showDiagramTree = false;
boolean showEntitySearch = false;
boolean showIndexerSettings = false;
boolean showKinTypeStrings = false;
boolean showExportPanel = false;
boolean showMetaData = false;
if (existingFile != null) {
graphPanel.readSvg(existingFile, savableType);
String kinTermContents = null;
for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) {
if (currentKinTypeString.trim().length() > 0) {
if (kinTermContents == null) {
kinTermContents = "";
} else {
kinTermContents = kinTermContents + "\n";
}
kinTermContents = kinTermContents + currentKinTypeString.trim();
}
}
kinTypeStringInput.setText(kinTermContents);
} else {
kinTypeStringInput.setDefaultText();
if (documentType == null) {
// this is the default document that users see when they run the application for the first time
documentType = DocumentType.Simple;
}
switch (documentType) {
case ArchiveLinker:
showMetaData = true;
showDiagramTree = true;
showArchiveLinker = true;
graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
break;
// case CustomQuery:
// showMetaData = true;
// showKinTypeStrings = true;
// showDiagramTree = true;
// showIndexerSettings = true;
// graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
// break;
// case EntitySearch:
// showMetaData = true;
// showEntitySearch = true;
// showDiagramTree = true;
// graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
// break;
case KinTerms:
showKinTerms = true;
graphPanel.addKinTermGroup();
graphPanel.dataStoreSvg.diagramMode = DiagramMode.FreeForm;
break;
case Freeform:
// showDiagramTree = true;
showKinTypeStrings = true;
graphPanel.dataStoreSvg.diagramMode = DiagramMode.FreeForm;
break;
case Simple:
showMetaData = true;
showDiagramTree = true;
showEntitySearch = true;
graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
break;
case Query:
showMetaData = true;
showDiagramTree = true;
showKinTypeStrings = true;
graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
default:
break;
}
graphPanel.generateDefaultSvg();
}
this.setLayout(new BorderLayout());
progressBar.setVisible(false);
graphPanel.add(progressBar, BorderLayout.PAGE_START);
registeredArbilDataNode = new HashMap<ArbilDataNode, UniqueIdentifier>();
arbilDataNodesChangedStatus = new HashMap<ArbilNode, Boolean>();
egoSelectionPanel = new EgoSelectionPanel(this, graphPanel, dialogHandler, entityCollection, dataNodeLoader);
// kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups());
// kinTypeStringInput.setText(defaultString);
JPanel kinGraphPanel = new JPanel(new BorderLayout());
kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0);
HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 150);
dragTransferHandler = new KinDragTransferHandler(this, sessionStorage, entityCollection);
graphPanel.setTransferHandler(dragTransferHandler);
egoSelectionPanel.setTransferHandler(dragTransferHandler);
if (graphPanel.dataStoreSvg.diagramMode == DiagramMode.KinTypeQuery) {
projectTree = new ProjectTreePanel(entityCollection, "Project Tree", this, graphPanel, dialogHandler, dataNodeLoader);
projectTree.setTransferHandler(dragTransferHandler);
}
EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, this, graphPanel, dialogHandler, dataNodeLoader);
entitySearchPanel.setTransferHandler(dragTransferHandler);
HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0);
kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0);
TableCellDragHandler tableCellDragHandler = new TableCellDragHandler();
graphPanel.setArbilTableModel(new MetadataPanel(graphPanel, tableHidePane, tableCellDragHandler, dataNodeLoader, null)); // todo: pass a ImageBoxRenderer here if you want thumbnails
if (graphPanel.dataStoreSvg.getVisiblePanels() == null) {
// in some older files and non kinoath files these values would not be set, so we make sure that they are here
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTerms, 150, showKinTerms);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ArchiveLinker, 150, showArchiveLinker);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.DiagramTree, 150, showDiagramTree);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.EntitySearch, 150, showEntitySearch);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.IndexerSettings, 150, showIndexerSettings);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTypeStrings, 150, showKinTypeStrings);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ExportPanel, 150, showExportPanel);
// graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.MetaData, 150, showMetaData);
}
final ProfileManager profileManager = new ProfileManager(sessionStorage, dialogHandler);
final CmdiProfileSelectionPanel cmdiProfileSelectionPanel = new CmdiProfileSelectionPanel("Entity Profiles", profileManager, graphPanel);
profileManager.loadProfiles(false, cmdiProfileSelectionPanel, graphPanel);
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
if (panelSetting.getPanelType() != null) {
switch (panelSetting.getPanelType()) {
case ArchiveLinker:
panelSetting.setHidePane(kinTermHidePane, "Archive Linker");
archiveEntityLinkerPanelRemote = new ArchiveEntityLinkerPanel(panelSetting, this, graphPanel, dragTransferHandler, ArchiveEntityLinkerPanel.TreeType.RemoteTree, treeHelper, dataNodeLoader);
archiveEntityLinkerPanelLocal = new ArchiveEntityLinkerPanel(panelSetting, this, graphPanel, dragTransferHandler, ArchiveEntityLinkerPanel.TreeType.LocalTree, treeHelper, dataNodeLoader);
archiveEntityLinkerPanelMpiRemote = new ArchiveEntityLinkerPanel(panelSetting, this, graphPanel, dragTransferHandler, ArchiveEntityLinkerPanel.TreeType.MpiTree, treeHelper, dataNodeLoader);
panelSetting.addTargetPanel(archiveEntityLinkerPanelRemote, false);
panelSetting.addTargetPanel(archiveEntityLinkerPanelLocal, false);
panelSetting.addTargetPanel(archiveEntityLinkerPanelMpiRemote, false);
panelSetting.setMenuEnabled(false);
break;
case DiagramTree:
panelSetting.setHidePane(egoSelectionHidePane, "Diagram Tree");
panelSetting.addTargetPanel(egoSelectionPanel, false);
if (projectTree != null) {
panelSetting.addTargetPanel(projectTree, true);
}
panelSetting.setMenuEnabled(true);
break;
case EntitySearch:
panelSetting.setHidePane(egoSelectionHidePane, "Search Entities");
panelSetting.addTargetPanel(entitySearchPanel, false);
panelSetting.setMenuEnabled(graphPanel.dataStoreSvg.diagramMode != DiagramMode.FreeForm);
break;
case IndexerSettings:
panelSetting.setHidePane(kinTypeHidePane, "Diagram Settings");
graphPanel.getIndexParameters().symbolFieldsFields.setParent(graphPanel.getIndexParameters());
graphPanel.getIndexParameters().labelFields.setParent(graphPanel.getIndexParameters());
final JScrollPane symbolFieldsPanel = new JScrollPane(new FieldSelectionList(this, graphPanel.getIndexParameters().symbolFieldsFields, tableCellDragHandler));
final JScrollPane labelFieldsPanel = new JScrollPane(new FieldSelectionList(this, graphPanel.getIndexParameters().labelFields, tableCellDragHandler));
// todo: Ticket #1115 add overlay fields as paramters
symbolFieldsPanel.setName("Symbol Fields");
labelFieldsPanel.setName("Label Fields");
panelSetting.addTargetPanel(new KinTypeDefinitions("Kin Type Definitions", this, graphPanel.dataStoreSvg), false);
panelSetting.addTargetPanel(new RelationSettingsPanel("Relation Type Definitions", this, graphPanel.dataStoreSvg, dialogHandler), false);
if (graphPanel.dataStoreSvg.diagramMode != DiagramMode.FreeForm) {
// hide some of the settings panels from freeform diagrams
panelSetting.addTargetPanel(symbolFieldsPanel, false);
panelSetting.addTargetPanel(labelFieldsPanel, false);
panelSetting.addTargetPanel(cmdiProfileSelectionPanel, false);
}
panelSetting.setMenuEnabled(true);
break;
case KinTerms:
panelSetting.setHidePane(kinTermHidePane, "Kin Terms");
for (KinTermGroup kinTerms : graphPanel.getkinTermGroups()) {
panelSetting.addTargetPanel(new KinTermPanel(this, kinTerms, dialogHandler), false); // + kinTerms.titleString
}
panelSetting.setMenuEnabled(graphPanel.dataStoreSvg.diagramMode == DiagramMode.FreeForm);
break;
case KinTypeStrings:
panelSetting.setHidePane(kinTypeHidePane, "Kin Type Strings");
panelSetting.addTargetPanel(new JScrollPane(kinTypeStringInput), false);
panelSetting.setMenuEnabled(true);
break;
case ExportPanel:
panelSetting.setHidePane(kinTypeHidePane, "Export Data");
panelSetting.addTargetPanel(new ExportPanel(), false);
panelSetting.setMenuEnabled(false);
break;
// case MetaData:
// panelSetting.setTargetPanel(tableHidePane, tableScrollPane, "Metadata");
// break;
}
}
}
tableHidePane.setVisible(false);
// tableHidePane.toggleHiddenState(); // put the metadata table plane into the closed state
kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START);
kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START);
kinGraphPanel.add(graphPanel, BorderLayout.CENTER);
kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END);
kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END);
this.add(kinGraphPanel);
EntityData[] svgDataNodes;
if (graphPanel.dataStoreSvg.graphData != null) {
svgDataNodes = graphPanel.dataStoreSvg.graphData.getDataNodes();
} else {
// if the data has not been loaded from the svg then we do not need to pre load it so we cah just use an empty array
svgDataNodes = new EntityData[]{};
}
entityIndex = new QueryParser(/* graphPanel.getDiagramUniqueIdentifiers(), */entityCollection);
kinTypeStringInput.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
synchronized (e) {
redrawIfKinTermsChanged();
}
}
});
kinTypeStringProviders = new ArrayList<KinTypeStringProvider>();
kinTypeStringProviders.add(kinTypeStringInput);
kinTypeStringProviders.add(entitySearchPanel);
kinTypeStringProviders.addAll(Arrays.asList(graphPanel.getkinTermGroups()));
// graphPanel.svgUpdateHandler.updateEntities();
}
static public File getDefaultDiagramFile(SessionStorage sessionStorage) {
if (defaultDiagramTemplate == null) {
defaultDiagramTemplate = new File(sessionStorage.getStorageDirectory(), "DefaultKinDiagram.svg");
}
return defaultDiagramTemplate;
}
public void redrawIfKinTermsChanged() {
if (kinTypeStringInput.hasChanges()) {
graphPanel.setKinTypeStrigs(kinTypeStringInput.getCurrentStrings());
drawGraph();
}
}
boolean graphThreadRunning = false;
boolean graphUpdateRequired = false;
public synchronized void drawGraph() {
drawGraph(null);
}
public synchronized void drawGraph(final UniqueIdentifier[] uniqueIdentifiers) {
graphUpdateRequired = true;
entityIndex.requestAbortProcess();
if (!graphThreadRunning) {
graphThreadRunning = true;
new Thread() {
@Override
public void run() {
while (graphUpdateRequired) {
try {
graphUpdateRequired = false;
entityIndex.clearAbortRequest();
try {
String[] kinTypeStrings = graphPanel.getKinTypeStrigs();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setValue(0);
progressBar.setVisible(true);
}
});
if (graphPanel.dataStoreSvg.diagramMode == DiagramMode.Undefined) {
graphPanel.dataStoreSvg.diagramMode = DiagramMode.FreeForm;
if (!graphPanel.dataStoreSvg.egoEntities.isEmpty() || !graphPanel.dataStoreSvg.requiredEntities.isEmpty()) {
graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
} else {
for (String currentLine : kinTypeStrings) {
if (currentLine.contains("[")) {
graphPanel.dataStoreSvg.diagramMode = DiagramMode.KinTypeQuery;
break;
}
}
}
}
if (graphPanel.dataStoreSvg.diagramMode == DiagramMode.KinTypeQuery) {
// diagramMode = DiagramMode.KinTypeQuery;
final EntityData[] graphNodes = entityIndex.processKinTypeStrings(kinTypeStringProviders, graphPanel.getIndexParameters(), graphPanel.dataStoreSvg, progressBar);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(true);
}
});
if (graphPanel.dataStoreSvg.graphData == null) {
// this will only be null when the diagram has been opened but not recalculated yet
graphPanel.dataStoreSvg.graphData = new GraphSorter();
}
graphPanel.dataStoreSvg.graphData.setEntitys(graphNodes);
// register interest Arbil updates and update the graph when data is edited in the table
// registerCurrentNodes(graphSorter.getDataNodes());
graphPanel.drawNodes(graphPanel.dataStoreSvg.graphData);
egoSelectionPanel.setTreeNodes(graphPanel);
new KinTermCalculator().insertKinTerms(graphPanel.dataStoreSvg.graphData.getDataNodes(), graphPanel.getkinTermGroups());
} else {
// diagramMode = DiagramMode.FreeForm;
KinTypeStringConverter graphData = new KinTypeStringConverter(graphPanel.dataStoreSvg);
graphData.readKinTypes(kinTypeStringProviders, graphPanel.dataStoreSvg);
graphPanel.drawNodes(graphData);
egoSelectionPanel.setTreeNodes(graphPanel);
// KinDiagramPanel.this.doLayout();
new KinTermCalculator().insertKinTerms(graphData.getDataNodes(), graphPanel.getkinTermGroups());
}
// kinTypeStrings = graphPanel.getKinTypeStrigs();
} catch (EntityServiceException exception) {
BugCatcherManager.getBugCatcher().logError(exception);
dialogHandler.addMessageDialogToQueue("Failed to load all entities required", "Draw Graph");
}
} catch (ProcessAbortException exception) {
// if the process has been aborted then it should be safe to let the next thread loop take over from here
System.out.println("draw graph process has been aborted, it should be safe to let the next thread loop take over from here");
} catch (ImportRequiredException exception) {
if (exception.getImportURI() != null) {
final String[] optionStrings = new String[]{"Import", "Cancel"};
int userOption = dialogHandler.showDialogBox(exception.getMessageString() + "\nDo you want to import this data now?\n" + exception.getImportURI().toASCIIString(), "Import Required", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, optionStrings, optionStrings[0]);
// ask the user if they want to import the required file and start the import on yes
if (userOption == 0) {
try {
if ("jar".equals(exception.getImportURI().getScheme())) {
diagramWindowManager.openJarImportPanel(exception.getImportURI().getPath(), KinDiagramPanel.this);
} else {
diagramWindowManager.openImportPanel(exception.getImportURI().toASCIIString(), KinDiagramPanel.this);
}
} catch (ImportException exception1) {
dialogHandler.addMessageDialogToQueue(exception1.getMessage() + "\n" + exception.getImportURI().toASCIIString(), "Import Required Data");
}
}
} else {
dialogHandler.addMessageDialogToQueue(exception.getMessageString(), "Draw Graph");
}
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setVisible(false);
}
});
graphThreadRunning = false;
if (uniqueIdentifiers != null) {
graphPanel.setSelectedIds(uniqueIdentifiers);
}
}
}.start();
}
}
// @Deprecated
// public void setDisplayNodes(String typeString, String[] egoIdentifierArray) {
// // todo: should this be replaced by the required nodes?
// if (kinTypeStringInput.getText().equals(defaultString)) {
// kinTypeStringInput.setText("");
// String kinTermContents = kinTypeStringInput.getText();
// for (String currentId : egoIdentifierArray) {
// kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n";
// kinTypeStringInput.setText(kinTermContents);
// graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n"));
//// kinTypeStrings = graphPanel.getKinTypeStrigs();
// drawGraph();
public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addNodeCollection(UniqueIdentifier[] entityIdentifiers, String nodeSetTitle) {
// todo:. consider if this should be added to the panels menu also as us done for addKinTermGroup
EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, this, graphPanel, dialogHandler, dataNodeLoader, nodeSetTitle, entityIdentifiers);
entitySearchPanel.setTransferHandler(dragTransferHandler);
kinTermHidePane.addTab(nodeSetTitle, entitySearchPanel);
kinTermHidePane.setHiddeState();
kinTypeStringProviders.add(entitySearchPanel);
}
public void addKinTermGroup() {
final KinTermGroup kinTermGroup = graphPanel.addKinTermGroup();
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
if (panelSetting.getPanelType() == PanelType.KinTerms) {
panelSetting.addTargetPanel(new KinTermPanel(this, kinTermGroup, dialogHandler), true);
}
}
kinTypeStringProviders.add(kinTermGroup);
}
public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void loadAllTrees() {
egoSelectionPanel.setTreeNodes(graphPanel); // init the trees in the side panel
archiveEntityLinkerPanelRemote.loadTreeNodes();
archiveEntityLinkerPanelLocal.loadTreeNodes();
archiveEntityLinkerPanelMpiRemote.loadTreeNodes();
if (projectTree != null) {
projectTree.loadProjectTree();
entityCollection.addDatabaseUpdateListener(projectTree);
}
}
public void showProgressBar() {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setIndeterminate(true);
progressBar.setVisible(true);
KinDiagramPanel.this.revalidate();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(true);
progressBar.setVisible(true);
KinDiagramPanel.this.revalidate();
}
});
}
}
public void clearProgressBar() {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
KinDiagramPanel.this.revalidate();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
KinDiagramPanel.this.revalidate();
}
});
}
}
public boolean hasSaveFileName() {
return (graphPanel.hasSaveFileName());
}
public File getFileName() {
return graphPanel.getFileName();
}
public boolean requiresSave() {
return graphPanel.requiresSave();
}
public void setRequiresSave() {
graphPanel.setRequiresSave();
}
public void saveToFile() {
graphPanel.saveToFile();
}
public void saveToFile(File saveFile) {
graphPanel.saveToFile(saveFile);
}
public void updateGraph() {
this.drawGraph();
}
public void doActionCommand(MouseListenerSvg.ActionCode actionCode) {
graphPanel.mouseListenerSvg.performMenuAction(actionCode);
}
public GraphPanel getGraphPanel() {
return graphPanel;
}
public void exportKinTerms() {
Component tabComponent = kinTermHidePane.getSelectedComponent();
if (tabComponent instanceof KinTermPanel) {
((KinTermPanel) tabComponent).exportKinTerms();
}
}
// public void hideShow() {
// kinTermHidePane.toggleHiddenState();
public void importKinTerms() {
Component tabComponent = kinTermHidePane.getSelectedComponent();
if (tabComponent instanceof KinTermPanel) {
((KinTermPanel) tabComponent).importKinTerms();
}
}
public int getKinTermGroupCount() {
return graphPanel.getkinTermGroups().length;
}
public VisiblePanelSetting[] getVisiblePanels() {
return graphPanel.dataStoreSvg.getVisiblePanels();
}
public void setPanelState(PanelType panelType, boolean panelVisible) {
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
if (panelSetting.getPanelType() == panelType) {
panelSetting.setPanelShown(panelVisible);
}
}
}
public boolean getPanelState(PanelType panelType) {
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
if (panelSetting.getPanelType() == panelType) {
return panelSetting.isPanelShown();
}
}
return false;
}
public void setSelectedKinTypeSting(String kinTypeStrings) {
for (Component tabComponent : kinTermHidePane.getComponents()) {
if (tabComponent instanceof KinTermPanel) {
KinTermPanel kinTermPanel = (KinTermPanel) tabComponent;
kinTermPanel.setDefaultKinType(kinTypeStrings);
}
}
}
// public boolean isHidden() {
// return kinTermHidePane.isHidden();
public EntityData[] getGraphEntities() {
return graphPanel.dataStoreSvg.graphData.getDataNodes();
}
public void registerArbilNode(UniqueIdentifier uniqueIdentifier, ArbilDataNode arbilDataNode) {
// todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex
// todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur
// todo: replace the data node registering process.
// for (EntityData entityData : currentEntities) {
// ArbilDataNode arbilDataNode = null;
if (!registeredArbilDataNode.containsKey(arbilDataNode)) {
arbilDataNode.registerContainer(this);
registeredArbilDataNode.put(arbilDataNode, uniqueIdentifier);
}
// try {
// String metadataPath = entityData.getEntityPath();
// if (metadataPath != null) {
// // todo: this should not load the arbil node only register an interest
//// and this needs to be tested
// arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath));
// registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode);
// arbilDataNode.registerContainer(this);
// // todo: keep track of registered nodes and remove the unrequired ones here
// } else {
// GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0]));
// } catch (URISyntaxException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
// } else {
// arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier());
// if (arbilDataNode != null) {
// entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false);
}
public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) {
// this method does not need to update the database because the link changing process has already done that
// remove the stored graph locations of the selected ids
graphPanel.clearEntityLocations(selectedIdentifiers);
graphPanel.getIndexParameters().valuesChanged = true;
drawGraph();
}
public void dataNodeIconCleared(ArbilNode arbilNode) {
if (arbilDataNodesChangedStatus.containsKey(arbilNode)) {
boolean dataBaseRequiresUpdate = false;
boolean redrawRequired = false;
if (arbilNode instanceof ArbilDataNode) {
ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode;
boolean currentlyNeedsSave = arbilDataNode.getNeedsSaveToDisk(false);
if (currentlyNeedsSave != arbilDataNodesChangedStatus.get(arbilNode)) {
arbilDataNodesChangedStatus.put(arbilNode, currentlyNeedsSave);
UniqueIdentifier uniqueIdentifier = registeredArbilDataNode.get(arbilDataNode);
// find the entity data for this arbil data node
for (EntityData entityData : graphPanel.dataStoreSvg.graphData.getDataNodes()) {
if (entityData.getUniqueIdentifier().equals(uniqueIdentifier)) {
// clear or set the needs save flag
entityData.metadataRequiresSave = currentlyNeedsSave;
}
}
dataBaseRequiresUpdate = !currentlyNeedsSave; // if there was a change that has been saved then an db update is required
redrawRequired = true;
}
if (dataBaseRequiresUpdate) {
entityCollection.updateDatabase(arbilDataNode.getURI());
graphPanel.getIndexParameters().valuesChanged = true;
}
}
if (redrawRequired) {
drawGraph();
}
} else {
// this will occur in the initial loading process, hence this does not perform db updates nor graph redraws
arbilDataNodesChangedStatus.put(arbilNode, false);
}
}
public void dataNodeChildAdded(ArbilNode destination, ArbilNode newChildNode) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void dataNodeRemoved(ArbilNode adn) {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean isFullyLoadedNodeRequired() {
throw new UnsupportedOperationException("Not supported yet.");
}
} |
package duro.runtime;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
public class DictionaryProcess extends Process implements Iterable<Object> {
private static final long serialVersionUID = 1L;
@Override
public void replay(List<Instruction> commands) {
// Does is make sense to have this method here?
}
@Override
public void resume(List<Instruction> playedInstructions) {
// Does is make sense to have this method here?
}
private Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
@Override
public CallFrameInfo getInstructions(Object key) {
return (CallFrameInfo)properties.get(key);
}
@Override
public void define(Object key, Object value) {
properties.put(key, value);
}
@Override
public Object lookup(Object key) {
return properties.get(key);
}
@Override
public Iterator<Object> iterator() {
return properties.keySet().iterator();
}
@Override
public String toString() {
return properties.toString();
}
} |
import junit.framework.TestCase;
public class TravisTestTest extends TestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
}
public void test_case() {
assertEquals(true, false);
}
} |
package statix.cli;
import java.io.IOException;
import java.io.PrintStream;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.Callable;
import org.apache.commons.vfs2.FileObject;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.MetaborgRuntimeException;
import org.metaborg.core.action.EndNamedGoal;
import org.metaborg.core.action.ITransformGoal;
import org.metaborg.core.action.TransformActionContrib;
import org.metaborg.core.context.IContext;
import org.metaborg.core.language.ILanguage;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.messages.IMessagePrinter;
import org.metaborg.core.messages.Message;
import org.metaborg.core.messages.MessageSeverity;
import org.metaborg.core.messages.MessageType;
import org.metaborg.core.messages.WithLocationStreamMessagePrinter;
import org.metaborg.core.project.IProject;
import org.metaborg.core.transform.ITransformConfig;
import org.metaborg.core.transform.TransformConfig;
import org.metaborg.spoofax.core.Spoofax;
import org.metaborg.spoofax.core.shell.CLIUtils;
import org.metaborg.spoofax.core.syntax.JSGLRParserConfiguration;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxInputUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxTransformUnit;
import org.metaborg.util.concurrent.IClosableLock;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import com.google.common.collect.Iterables;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.RunLast;
import picocli.CommandLine.Spec;
@Command(name = "java -jar statix.jar", description = "Type check and evaluate Statix files.", separator = "=")
public class Statix implements Callable<Void> {
private static final ILogger logger = LoggerUtils.logger(Statix.class);
@Spec private CommandSpec spec;
@Option(names = { "-h", "--help" }, description = "show usage help", usageHelp = true) private boolean usageHelp;
@Option(names = { "-i", "--interactive" }, description = "interactive mode") private boolean interactive;
@Parameters(paramLabel = "FILE", description = "files to check and evaluate") private String file;
private Spoofax S;
private CLIUtils cli;
private ILanguageImpl lang;
private IProject project;
private IContext context;
private IMessagePrinter messagePrinter;
private TransformActionContrib evalAction;
@Override public Void call() throws MetaborgException, IOException {
S = new Spoofax();
cli = new CLIUtils(S);
lang = loadLanguage();
project = cli.getOrCreateCWDProject();
if(!S.contextService.available(lang)) {
throw new MetaborgException("Cannot create project context.");
}
context = S.contextService.get(project.location(), project, lang);
final PrintStream msgStream = System.out;
messagePrinter = new WithLocationStreamMessagePrinter(S.sourceTextService, S.projectService, msgStream);
evalAction = getAction("Evaluate Test", lang);
final Optional<ISpoofaxAnalyzeUnit> maybeAnalysisUnit = loadFile(file);
if(!maybeAnalysisUnit.isPresent()) {
return null;
}
final ISpoofaxAnalyzeUnit analysisUnit = maybeAnalysisUnit.get();
final IStrategoTerm ast = analysisUnit.ast();
if(ast != null && Tools.isTermAppl(ast) && Tools.hasConstructor((IStrategoAppl) analysisUnit.ast(), "Test")) {
messagePrinter.print(new Message("Evaluating test.", MessageSeverity.NOTE, MessageType.INTERNAL,
analysisUnit.source(), null, null), false);
final String typing = transform(analysisUnit, evalAction);
msgStream.println(typing);
}
if(interactive) {
repl();
}
return null;
}
private ILanguageImpl loadLanguage() throws MetaborgException {
ILanguageImpl lang;
// try loading from path
cli.loadLanguagesFromPath();
ILanguage L = S.languageService.getLanguage("StatixLang");
lang = L != null ? L.activeImpl() : null;
if(lang != null) {
return lang;
}
// try loading from resources
final FileObject langResource;
try {
langResource = S.resourceService.resolve("res:statix.lang.spoofax-language");
} catch(MetaborgRuntimeException ex) {
throw new MetaborgException("Failed to load language.", ex);
}
lang = cli.loadLanguage(langResource);
if(lang != null) {
return lang;
}
throw new MetaborgException("Failed to load language from path or resources.");
}
private Optional<ISpoofaxAnalyzeUnit> loadFile(String file) throws MetaborgException {
final FileObject resource = S.resourceService.resolve(file);
final String text;
try {
text = S.sourceTextService.text(resource);
} catch(IOException e) {
throw new MetaborgException("Cannot find " + file, e);
}
final ISpoofaxInputUnit inputUnit = S.unitService.inputUnit(resource, text, lang, null);
final Optional<ISpoofaxParseUnit> parseUnit = parse(inputUnit);
if(!parseUnit.isPresent()) {
return Optional.empty();
}
final Optional<ISpoofaxAnalyzeUnit> analysisUnit = analyze(parseUnit.get());
return analysisUnit;
}
private Optional<ISpoofaxParseUnit> parse(ISpoofaxInputUnit inputUnit) throws MetaborgException {
final ILanguageImpl lang = context.language();
if(!S.syntaxService.available(lang)) {
throw new MetaborgException("Parsing not available.");
}
final ISpoofaxParseUnit parseUnit = S.syntaxService.parse(inputUnit);
for(IMessage message : parseUnit.messages()) {
messagePrinter.print(message, false);
}
if(!parseUnit.valid()) {
throw new MetaborgException("Parsing failed.");
}
if(!parseUnit.success()) {
logger.info("{} has syntax errors", inputUnit.source());
return Optional.empty();
}
return Optional.of(parseUnit);
}
private Optional<ISpoofaxAnalyzeUnit> analyze(ISpoofaxParseUnit parseUnit) throws MetaborgException {
if(!S.analysisService.available(lang) || !S.contextService.available(lang)) {
throw new MetaborgException("Analysis not available.");
}
final ISpoofaxAnalyzeUnit analysisUnit;
try(IClosableLock lock = context.write()) {
analysisUnit = S.analysisService.analyze(parseUnit, context).result();
}
for(IMessage message : analysisUnit.messages()) {
messagePrinter.print(message, false);
}
if(!analysisUnit.valid()) {
throw new MetaborgException("Analysis failed.");
}
if(!analysisUnit.success()) {
logger.info("{} has type errors.", parseUnit.source());
}
return Optional.of(analysisUnit);
}
private TransformActionContrib getAction(String name, ILanguageImpl lang) throws MetaborgException {
final ITransformGoal goal = new EndNamedGoal(name);
if(!S.actionService.available(lang, goal)) {
throw new MetaborgException("Cannot find transformation " + name);
}
final TransformActionContrib action;
try {
action = Iterables.getOnlyElement(S.actionService.actionContributions(lang, goal));
} catch(NoSuchElementException ex) {
throw new MetaborgException("Transformation " + name + " not a singleton.");
}
return action;
}
private String transform(ISpoofaxAnalyzeUnit analysisUnit, TransformActionContrib action) throws MetaborgException {
final ITransformConfig config = new TransformConfig(true);
final ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit> transformUnit =
S.transformService.transform(analysisUnit, context, action, config);
for(IMessage message : transformUnit.messages()) {
messagePrinter.print(message, false);
}
if(!transformUnit.valid()) {
throw new MetaborgException("Failed to transform " + analysisUnit.source());
}
final String details = S.strategoCommon.toString(transformUnit.ast());
return details;
}
private void repl() throws IOException, MetaborgException {
final Terminal terminal = TerminalBuilder.builder().build();
final LineReader reader =
LineReaderBuilder.builder().terminal(terminal).option(LineReader.Option.AUTO_FRESH_LINE, true).build();
final ILanguageImpl lang = context.language();
final JSGLRParserConfiguration config = new JSGLRParserConfiguration("CommandLine");
while(true) {
final String line;
try {
line = reader.readLine("> ");
} catch(UserInterruptException e) {
continue;
} catch(EndOfFileException e) {
return;
}
final ISpoofaxInputUnit inputUnit = S.unitService.inputUnit(line, lang, null, config);
final Optional<ISpoofaxParseUnit> maybeParseUnit = parse(inputUnit);
if(!maybeParseUnit.isPresent()) {
continue;
}
final ISpoofaxParseUnit parseUnit = maybeParseUnit.get();
terminal.writer().println(S.strategoCommon.toString(parseUnit.ast()));
final Optional<ISpoofaxAnalyzeUnit> maybeAnalysisUnit = analyze(parseUnit);
if(!maybeAnalysisUnit.isPresent()) {
continue;
}
final ISpoofaxAnalyzeUnit analysisUnit = maybeAnalysisUnit.get();
final String typing = transform(analysisUnit, evalAction);
terminal.writer().println(typing);
}
}
public static void main(String... args) {
final CommandLine cmd = new CommandLine(new Statix());
cmd.parseWithHandlers(new RunLast().andExit(0), CommandLine.defaultExceptionHandler().andExit(1), args);
}
} |
// 2015 competition robot code.
// Cleaned up and reorganized in preparation for 2016. No changes to
// functionality other than adding support for xbox controller and
// demonstration code for gyro and internal accelerometer.
// Test version for git training.
package Team4450.Robot8;
import java.io.IOException;
import java.util.Properties;
import Team4450.Lib.*;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.vision.AxisCamera;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends SampleRobot
{
static final String PROGRAM_NAME = "RAC8T-11.18.15-01";
// robotdrive(front-left, rear-left, front-right, rear-right)
final RobotDrive robotDrive = new RobotDrive(0,1,2,3);
final Joystick utilityStick = new Joystick(2); // 0 old ds configuration
final Joystick leftStick = new Joystick(0);
final Joystick rightStick = new Joystick(1);
final Joystick launchPad = new Joystick(3);
final Joystick gamePad = new Joystick(4);
final Compressor compressor = new Compressor(0);
final Gyro gyro = new Gyro(0);
public Properties robotProperties;
AxisCamera camera = null;
CameraServer usbCameraServer = null;
DriverStation ds = null;
DriverStation.Alliance alliance;
int location;
Thread monitorBatteryThread, monitorDistanceThread, monitorCompressorThread;
public CameraFeed cameraThread;
static final String CAMERA_IP = "10.44.50.11";
static final int USB_CAMERA = 2;
static final int IP_CAMERA = 3;
public Robot() throws IOException
{
// Set up our custom logger.
try
{
Util.CustomLogger.setup();
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
try
{
Util.consoleLog(PROGRAM_NAME);
robotDrive.stopMotor();
robotDrive.setExpiration(0.1);
ds = DriverStation.getInstance();
// IP Camera object used for vision processing.
//camera = AxisCamera.getInstance(CAMERA_IP);
robotDrive.setInvertedMotor(RobotDrive.MotorType.kFrontLeft, true);
robotDrive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, true);
robotDrive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true);
robotDrive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true);
Util.consoleLog("%s %s", PROGRAM_NAME, "end");
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
}
public void robotInit()
{
try
{
Util.consoleLog();
LCD.clearAll();
LCD.printLine(1, "Mode: RobotInit");
// Read properties file from RoboRio "disk".
robotProperties = Util.readProperties();
SmartDashboard.putString("Program", PROGRAM_NAME);
//SmartDashboard.putBoolean("CompressorEnabled", false);
SmartDashboard.putBoolean("CompressorEnabled", Boolean.parseBoolean(robotProperties.getProperty("CompressorEnabledByDefault")));
// Reset PDB sticky faults.
PowerDistributionPanel PDP = new PowerDistributionPanel();
PDP.clearStickyFaults();
// Set starting camera feed on driver station to USB-HW.
SmartDashboard.putNumber("CameraSelect", USB_CAMERA);
// Start usb camera feed server on roboRIO. usb camera name is set by roboRIO.
// If camera feed stops working, check roboRIO name assignment.
// Note this is not used if we do dual usb cameras, which are handled by the
// cameraFeed class. The function below is the standard WpiLib server which
// can be used for a single usb camera.
//StartUSBCameraServer("cam0");
// Start the battery, compressor, camera feed and distance monitoring Tasks.
monitorBatteryThread = new MonitorBattery(ds);
monitorBatteryThread.start();
monitorCompressorThread = new MonitorCompressor();
monitorCompressorThread.start();
// Start camera server using our class for dual usb cameras.
cameraThread = new CameraFeed(this);
cameraThread.start();
// Start thread to monitor distance sensor.
monitorDistanceThread = new MonitorDistanceMBX(this);
monitorDistanceThread.start();
Util.consoleLog("end");
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
}
public void disabled()
{
try
{
Util.consoleLog();
LCD.printLine(1, "Mode: Disabled");
// Reset driver station LEDs.
SmartDashboard.putBoolean("Disabled", true);
SmartDashboard.putBoolean("Auto Mode", false);
SmartDashboard.putBoolean("Teleop Mode", false);
SmartDashboard.putBoolean("FMS", ds.isFMSAttached());
Util.consoleLog("end");
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
}
public void autonomous()
{
try
{
Util.consoleLog();
LCD.clearAll();
LCD.printLine(1, "Mode: Autonomous");
SmartDashboard.putBoolean("Disabled", false);
SmartDashboard.putBoolean("Auto Mode", true);
// Make available the alliance (red/blue) and staring position as
// set on the driver station or FMS.
alliance = ds.getAlliance();
location = ds.getLocation();
// This code turns off the automatic compressor management if requested by DS.
compressor.setClosedLoopControl(SmartDashboard.getBoolean("CompressorEnabled", true));
// Start autonomous process contained in the MyAutonomous class.
Autonomous autonomous = new Autonomous(this);
autonomous.execute();
autonomous.dispose();
SmartDashboard.putBoolean("Auto Mode", false);
Util.consoleLog("end");
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
}
public void operatorControl()
{
try
{
Util.consoleLog();
LCD.clearAll();
LCD.printLine(1, "Mode: Teleop");
SmartDashboard.putBoolean("Disabled", false);
SmartDashboard.putBoolean("Teleop Mode", true);
alliance = ds.getAlliance();
location = ds.getLocation();
Util.consoleLog("Alliance=%s, Location=%d, FMS=%b", alliance.name(), location, ds.isFMSAttached());
// This code turns off the automatic compressor management if requested by DS.
compressor.setClosedLoopControl(SmartDashboard.getBoolean("CompressorEnabled", true));
// Start operator control process contained in the MyTeleop class.
Teleop teleOp = new Teleop(this);
teleOp.OperatorControl();
teleOp.dispose();
Util.consoleLog("end");
}
catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
}
public void test()
{
}
// Start WpiLib usb camera server for single selected camera.
public void StartUSBCameraServer(String cameraName)
{
Util.consoleLog(cameraName);
usbCameraServer = CameraServer.getInstance();
usbCameraServer.setQuality(30);
usbCameraServer.startAutomaticCapture(cameraName);
}
} |
package com.wilutions.com.reg;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import com.wilutions.com.CoClass;
import com.wilutions.com.ComEnum;
import com.wilutions.com.ComException;
import com.wilutions.com.DispatchImpl;
/**
* This class helps to store and load the state of UI controls.
*/
public class Registry {
private final String regKey;
private static final int OPT_ONLY_ANNOTATED_FIELDS = 1;
private static final int OPT_ALL_FIELDS = 0;
/**
* Initialize the registry destination path.
* @param manufacturerName Manufacturer name
* @param appName Application name
*/
public Registry(String manufacturerName, String appName) {
this.regKey = "HKCU\\Software\\" + manufacturerName + "\\" + appName;
}
/**
* Initialize the registry destination path.
* The path is computed as HKEY_CURRENT_USER\Software\{program ID of coclass}
* @param coclass COM class annotated with {@link CoClass}
*/
public Registry(Class<? extends DispatchImpl> coclass) {
CoClass co = coclass.getAnnotation(CoClass.class);
this.regKey = "HKCU\\Software\\" + co.progId();
}
/**
* Store all fields annotated by {@link DeclRegistryValue}.
* @param obj Store fields of this object.
*/
public void writeFields(Object obj) {
if (obj == null) throw new IllegalArgumentException("obj must not be null");
String subKey = regKey + "\\" + obj.getClass().getName();
writeObject(subKey, obj, OPT_ONLY_ANNOTATED_FIELDS);
}
/**
* Read all fields annotated by {@link DeclRegistryValue}.
* @param obj Read annotated fields of this object.
*/
public void readFields(Object obj) {
String subKey = regKey + "\\" + obj.getClass().getName();
readFields(subKey, obj, OPT_ONLY_ANNOTATED_FIELDS);
}
/**
* Read an object or primitive value at the given sub-key.
* This function reads all fields - not only annotated fields.
* @param subKey Sub-key
* @return Object or primitive value
*/
public Object read(String subKey) {
return readObject(regKey + "\\" + subKey);
}
/**
* Write object or primitive value at the given sub-key.
* This function writes all fields - not only annotated fields.
* @param subKey Sub-key
* @param obj Object to be written.
*/
public void write(String subKey, Object obj) {
writeObject(regKey + "\\" + subKey, obj, OPT_ALL_FIELDS);
}
private static void readFields(String key, Object obj, int opts) {
Class<?> clazz = obj.getClass();
while (clazz != null && clazz != Object.class) {
for (Field field : clazz.getDeclaredFields()) {
String fieldName = field.getName();
int mods = field.getModifiers();
if (Modifier.isStatic(mods))
continue;
if (Modifier.isFinal(mods))
continue;
if (Modifier.isTransient(mods))
continue;
if ((opts & OPT_ONLY_ANNOTATED_FIELDS) != 0) {
DeclRegistryValue regValueAnno = field.getAnnotation(DeclRegistryValue.class);
if (regValueAnno == null) continue;
String s = regValueAnno.value();
if (s != null && s.length() != 0) {
fieldName = s;
}
}
if (!Modifier.isPublic(mods)) {
field.setAccessible(true);
}
try {
Object fieldValue = getFieldValue(key, fieldName, field.getType());
if (fieldValue != null) {
field.set(obj, fieldValue);
}
} catch (Throwable ignored) {
}
}
clazz = clazz.getSuperclass();
}
}
private static Object readObject(String key) {
String className = (String) RegUtil.getRegistryValue(key, "", "");
if (className == null || className.length() == 0)
return null;
Object ret = null;
try {
Class<?> clazz = Class.forName(className);
ret = clazz.newInstance();
readFields(key, ret, OPT_ALL_FIELDS);
} catch (Throwable ignored) {
}
return ret;
}
private static Object getFieldValueArray(String key, String fieldName, Class<?> arrayType)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String arrayKey = key + "\\" + fieldName;
Class<?> elementType = arrayType.getComponentType();
int length = Integer.valueOf((String) RegUtil.getRegistryValue(arrayKey, "length", "0"));
Object fieldValue = Array.newInstance(elementType, length);
for (int i = 0; i < length; i++) {
Object elementValue = getFieldValue(arrayKey, Integer.toString(i), elementType);
Array.set(fieldValue, i, elementValue);
}
return fieldValue;
}
private static void setFieldValueArray(String key, String fieldName, Object arrayValue) throws ComException {
String arrayKey = key + "\\" + fieldName;
int length = Array.getLength(arrayValue);
RegUtil.setRegistryValue(arrayKey, "length", length);
for (int i = 0; i < length; i++) {
Object elementValue = Array.get(arrayValue, i);
if (elementValue == null)
continue;
setFieldValue(arrayKey, Integer.toString(i), elementValue);
}
}
private static Object getFieldValueList(String key, String fieldName, Class<?> listType)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String listKey = key + "\\" + fieldName;
int length = Integer.valueOf((String) RegUtil.getRegistryValue(listKey, "length", "0"));
Object fieldValue = listType.newInstance();
if (length != 0) {
String elementTypeName = (String) RegUtil.getRegistryValue(listKey, "elementClass", "");
Class<?> elementType = Class.forName(elementTypeName);
for (int i = 0; i < length; i++) {
Object elementValue = getFieldValue(listKey, Integer.toString(i), elementType);
Array.set(fieldValue, i, elementValue);
}
}
return fieldValue;
}
@SuppressWarnings("rawtypes")
private static void setFieldValueList(String key, String fieldName, Object listValue) throws ComException {
String listKey = key + "\\" + fieldName;
List list = (List) listValue;
int length = list.size();
RegUtil.setRegistryValue(listKey, "length", length);
int i = 0;
boolean classWritten = false;
for (Object elementValue : list) {
if (!classWritten && elementValue != null) {
RegUtil.setRegistryValue(listKey, "elementClass", elementValue.getClass().getName());
classWritten = true;
}
setFieldValue(listKey, Integer.toString(i++), elementValue);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object getFieldValueMap(String key, String fieldName, Class<?> mapType)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String mapKey = key + "\\" + fieldName;
int length = Integer.valueOf((String) RegUtil.getRegistryValue(mapKey, "length", "0"));
Map fieldValue = (Map) mapType.newInstance();
if (length != 0) {
String keyTypeName = (String) RegUtil.getRegistryValue(mapKey, "keyClass", "");
String valueTypeName = (String) RegUtil.getRegistryValue(mapKey, "valueClass", "");
Class<?> keyType = Class.forName(keyTypeName);
Class<?> valueType = Class.forName(valueTypeName);
for (int i = 0; i < length; i++) {
String elementKey = mapKey + "\\" + i;
Object keyValue = getFieldValue(elementKey, "key", keyType);
Object valueValue = getFieldValue(elementKey, "value", valueType);
fieldValue.put(keyValue, valueValue);
}
}
return fieldValue;
}
@SuppressWarnings("rawtypes")
private static void setFieldValueMap(String key, String fieldName, Object mapValue) throws ComException {
String mapKey = key + "\\" + fieldName;
Map map = (Map) mapValue;
int length = map.size();
RegUtil.setRegistryValue(mapKey, "length", length);
boolean keyClassWritten = false, valueClassWritten = false;
int i = 0;
for (Object e : map.entrySet()) {
String elementKey = mapKey + "\\" + (i++);
Map.Entry mapEntry = (Map.Entry) e;
Object keyValue = mapEntry.getKey();
Object valueValue = mapEntry.getValue();
if (!keyClassWritten && keyValue != null) {
RegUtil.setRegistryValue(mapKey, "keyClass", keyValue.getClass().getName());
}
if (!valueClassWritten && valueValue != null) {
RegUtil.setRegistryValue(mapKey, "valueClass", valueValue.getClass().getName());
}
setFieldValue(elementKey, "key", keyValue);
setFieldValue(elementKey, "value", valueValue);
}
}
private static Object getFieldValue(String key, String fieldName, Class<?> fieldType)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Object ret = null;
if (fieldType.isArray()) {
ret = getFieldValueArray(key, fieldName, fieldType);
} else if (fieldType == String.class) {
ret = RegUtil.getRegistryValue(key, fieldName, "");
} else if (fieldType == Integer.class || fieldType == int.class) {
Object regValue = RegUtil.getRegistryValue(key, fieldName, Integer.valueOf(0));
ret = (Integer) regValue;
} else if (fieldType == Long.class || fieldType == long.class) {
Object regValue = RegUtil.getRegistryValue(key, fieldName, "0");
ret = Long.valueOf((String) regValue);
} else if (fieldType == Double.class || fieldType == double.class) {
Object regValue = RegUtil.getRegistryValue(key, fieldName, "0");
ret = Double.valueOf((String) regValue);
} else if (fieldType == Float.class || fieldType == float.class) {
Object regValue = RegUtil.getRegistryValue(key, fieldName, "0.f");
ret = Float.valueOf((String) regValue);
} else if (fieldType == Boolean.class || fieldType == boolean.class) {
Object regValue = RegUtil.getRegistryValue(key, fieldName, Boolean.FALSE.toString());
ret = Boolean.valueOf((String) regValue);
} else if (fieldType.isEnum()) {
String enumValueStr = (String)RegUtil.getRegistryValue(key, fieldName, "");
for (Object e : fieldType.getEnumConstants()) {
if (e.toString().equals(enumValueStr)) {
ret = e;
break;
}
}
} else if (ComEnum.class.isAssignableFrom(fieldType)) {
String enumValueStr = (String)RegUtil.getRegistryValue(key, fieldName, "");
if (!enumValueStr.isEmpty()) {
try {
int enumValue = Integer.parseInt(enumValueStr);
Method m = fieldType.getDeclaredMethod("valueOf", int.class);
ret = m.invoke(null, enumValue);
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (List.class.isAssignableFrom(fieldType)) {
ret = getFieldValueList(key, fieldName, fieldType);
} else if (Map.class.isAssignableFrom(fieldType)) {
ret = getFieldValueMap(key, fieldName, fieldType);
} else {
ret = readObject(key + "\\" + fieldName);
}
return ret;
}
private static void setFieldValue(String key, String fieldName, Object value) throws ComException {
if (value == null) {
RegUtil.deleteRegistryValue(key, fieldName);
} else {
Class<?> fieldType = value.getClass();
if (fieldType.isArray()) {
setFieldValueArray(key, fieldName, value);
} else if (fieldType == String.class) {
RegUtil.setRegistryValue(key, fieldName, (String) value);
} else if (fieldType == Integer.class) {
RegUtil.setRegistryValue(key, fieldName, (Integer) value);
} else if (fieldType == Long.class) {
RegUtil.setRegistryValue(key, fieldName, value.toString());
} else if (fieldType == Double.class) {
RegUtil.setRegistryValue(key, fieldName, value.toString());
} else if (fieldType == Float.class) {
RegUtil.setRegistryValue(key, fieldName, value.toString());
} else if (fieldType == Boolean.class) {
RegUtil.setRegistryValue(key, fieldName, value.toString());
} else if (fieldType.isEnum()) {
RegUtil.setRegistryValue(key, fieldName, value.toString());
} else if (ComEnum.class.isAssignableFrom(fieldType)) {
try {
Field f = fieldType.getDeclaredField("value");
String enumValueStr = Integer.toString((int)f.get(value));
RegUtil.setRegistryValue(key, fieldName, enumValueStr);
} catch (Exception e) {
e.printStackTrace();
}
} else if (List.class.isAssignableFrom(fieldType)) {
setFieldValueList(key, fieldName, value);
} else if (Map.class.isAssignableFrom(fieldType)) {
setFieldValueMap(key, fieldName, value);
} else {
writeObject(key + "\\" + fieldName, value, OPT_ALL_FIELDS);
}
}
}
private static void writeObject(String key, Object obj, int opts) {
String className = obj != null ? obj.getClass().getName() : "";
try {
RegUtil.purgeRegistryKey(key);
RegUtil.setRegistryValue(key, "", className);
if (className == null || className.length() == 0)
return;
Class<?> clazz = obj.getClass();
while (clazz != null && clazz != Object.class) {
for (Field field : clazz.getDeclaredFields()) {
String fieldName = field.getName();
int mods = field.getModifiers();
if (Modifier.isStatic(mods))
continue;
if (Modifier.isFinal(mods))
continue;
if (Modifier.isTransient(mods))
continue;
if ((opts & OPT_ONLY_ANNOTATED_FIELDS) != 0) {
DeclRegistryValue regValueAnno = field.getAnnotation(DeclRegistryValue.class);
if (regValueAnno == null) continue;
String s = regValueAnno.value();
if (s != null && s.length() != 0) {
fieldName = s;
}
}
if (!Modifier.isPublic(mods)) {
field.setAccessible(true);
}
try {
Object fieldValue = field.get(obj);
setFieldValue(key, fieldName, fieldValue);
} catch (Throwable e) {
e.printStackTrace();
}
}
clazz = clazz.getSuperclass();
}
} catch (Throwable e) {
}
}
} |
package ru.job4j.model;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
import static org.junit.Assert.assertThat;
/**Testing Item.*/
public class ItemTest {
/**Testing setName(String name) and getName().*/
@Test
public void whenSetNameThenName() {
Item item = new Item();
String name = "Task";
item.setName(name);
assertThat(item.getName(), is(name));
}
/**Testing setDescription(String desc) and getDescription().*/
@Test
public void whenSetDescrThenDescr() {
Item item = new Item();
String desc = "Description";
item.setDescription(desc);
assertThat(item.getDescription(), is(desc));
}
/**Testing addComment(String text, String auth) and getComments().*/
@Test
public void whenAddCommentThenCommentInArray() {
Item item = new Item();
String name = "name";
String text = "text";
final int maxSizeOfCommentsList = 30;
final int firstComment = 0;
final long currentTimeInMillis = 1485959504531L;
Comment com = new Comment();
com.setAuthor(name);
com.setText(text);
com.setCreate(currentTimeInMillis);
item.addComment(text, name, currentTimeInMillis);
assertThat(item.getComments()[firstComment], samePropertyValuesAs(com));
}
/**Testing setCreate(long millis) and getCreate().*/
@Test
public void whenSetCreateThenName() {
Item item = new Item();
final long timeInMillis = 1485959504531L;
item.setCreate(timeInMillis);
assertThat(item.getCreate(), is("17:31 1/2/2017"));
}
/**Testing generateId() and getId().*/
@Test
public void whenGenerateIdThenUniqueId() {
Item item = new Item();
String idOfFirstItem = "1";
item.generateId();
assertThat(item.getId(), is(idOfFirstItem));
}
} |
package com.wilutions.joa;
public enum LoadBehavior {
/**
* The Addin is not loaded.
*/
DoNotLoad(0),
/**
* The Addin is loaded on startup.
* Outlook loads the Adding during startup. This is shown in the splash screen.
* The method {@link IDTExtensibiltiy2#onConnection(com.wilutions.com.Dispatch, int, com.wilutions.com.Dispatch, com.wilutions.com.ByRef)}
* is called with {@link ext_ConnectMode#ext_cm_Startup}.
* If the Addin loads slowly, Outlook might decide to set the load state to {@link #DoNotLoad}.
*/
LoadOnStart(3),
/**
* The Addin is loaded on startup by the JOA Util Addin.
* With this option, the Addin is loaded in the onStartupComplete of the JAO Util Addin.
* Outlook does not track the load time under this mode and it does not disable the Addin,
* if it requires a long time to load.
*/
LoadByJoaUtil(4),
/**
* The Addin is loaded on demand.
* Outlook loads the Addin after it has created its main window.
* The method {@link IDTExtensibiltiy2#onConnection(com.wilutions.com.Dispatch, int, com.wilutions.com.Dispatch, com.wilutions.com.ByRef)}
* is called with {@link ext_ConnectMode#ext_cm_AfterStartup}.
*/
LoadOnDemand(8),
/**
* Addin is loaded on startup only once.
* If Outlook reads this value, it loads the Addin on startup.
* Then, Outlook switches the value (under HKEY_CURRENT_USER...) to 9,
* which includes bit LoadOnDemand.
* The Addin should add any controls to the user interface of Outlook (e.g. Ribbon tab),
* otherwise it might never be loaded.
* This value is the default for Addins registered with JOA, see {@link DeclAddin#loadBehavior()}.
*/
LoadOnStartFirstTime(16);
public final int value;
private LoadBehavior(int value) { this.value = value; }
} |
package org.ccnx.ccn.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Level;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
/**
* Table of Interests, holding an arbitrary value for any
* Interest or ContentName. This is conceptually like a Map<Interest, V> except it supports
* duplicate entries and has operations for access based on CCN
* matching. An InterestTable may be used to hold real Interests, or merely
* ContentNames only, though mixing the two in the same instance of InterestTable
* is not recommended. InterestTables are synchronized using _contents as a synchronization
* object
*
* Since interests can be reexpressed we could end up with duplicate
* interests in the table. To avoid that an LRU algorithm is
* optionally implemented to keep the table from growing without
* bounds.
*/
public class InterestTable<V> {
public interface Entry<T> {
/**
* Get the ContentName of this entry. All table entries have non-null
* ContentName.
* @return
*/
public ContentName name();
/**
* Get the Interest of this entry. If a name is entered in the table
* then the Interest will be null.
* @return Interest if present, null otherwise
*/
public Interest interest();
/**
* Get the value of this entry. A value may be null.
* @return
*/
public T value();
}
protected final static class LongestFirstComparator implements Comparator<ContentName>{
public int compare(ContentName o1, ContentName o2) {
if (o1 == o2)
return 0;
int thisCount = o1.count();
int oCount = o2.count();
if (thisCount == oCount)
return o1.compareTo(o2);
return (oCount - thisCount);
}
}
protected SortedMap<ContentName,List<Holder<V>>> _contents = new TreeMap<ContentName,List<Holder<V>>>(new LongestFirstComparator()) {
private static final long serialVersionUID = -2774858588706066528L;
@Override
public String toString() {
StringBuffer s = new StringBuffer();
for(ContentName n : keySet() )
s.append(n.toString() + " ");
return s.toString();
}
};
protected List<ContentName> _contentNamesLRU = null;
protected Integer _capacity = null; // For LRU size control - default is none
protected abstract class Holder<T> implements Entry<T> {
protected T value;
public Holder(T v) {
value= v;
}
public T value() {
return value;
}
}
protected class NameHolder<T> extends Holder<T> {
protected ContentName name;
public NameHolder(ContentName n, T v) {
super(v);
name = n;
}
public ContentName name() {
return name;
}
public Interest interest() {
return null;
}
}
protected class InterestHolder<T> extends Holder<T> {
protected Interest interest;
public InterestHolder(Interest i, T v) {
super(v);
interest = i;
}
public ContentName name() {
return interest.name();
}
public Interest interest() {
return interest;
}
}
/**
* Set capacity for LRU size control. Defaults to
* no size control
*
* @param capacity
*/
public void setCapacity(int capacity) {
synchronized (_contents) {
_capacity = capacity;
_contentNamesLRU = new LinkedList<ContentName>();
}
}
/**
* Gets the current capacity for LRU size control
* @return the capacity. null if not set
*/
public Integer getCapacity() {
synchronized (_contents) {
return _capacity;
}
}
/**
* Add a value associated with an interest to the table
*
* @param interest the interest
* @param value associated object
*/
public void add(Interest interest, V value) {
if (null == interest) {
throw new NullPointerException("InterestTable may not contain null Interest");
}
if (null == interest.name()) {
throw new NullPointerException("InterestTable may not contain Interest with null name");
}
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "adding interest {0}", interest);
Holder<V> holder = new InterestHolder<V>(interest, value);
add(holder);
}
/**
* Add a value associated with content to the table
*
* @param name name of the content
* @param value associated object
*/
public void add(ContentName name, V value) {
if (null == name) {
throw new NullPointerException("InterestTable may not contain null name");
}
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "adding name {0}", name);
Holder<V> holder = new NameHolder<V>(name, value);
add(holder);
}
/**
* Add a value holder - could be interest or content
*
* @param holder
*/
protected void add(Holder<V> holder) {
ContentName name = holder.name();
synchronized (_contents) {
if (_contents.containsKey(name)) {
List<Holder<V>> list = _contents.get(name);
list.add(holder);
if (null != _capacity) {
// Have to update our LRUness
_contentNamesLRU.remove(name);
_contentNamesLRU.add(name);
}
} else {
ArrayList<Holder<V>> list = new ArrayList<Holder<V>>(1);
list.add(holder);
if (null != _capacity) {
if ( _contents.size() >= _capacity) {
// The LRU is the first key in the LRU list. So remove the contents
// corresponding to that one.
// XXX - should we care about whether the key has multiple
// interests attached?
if (Log.isLoggable(Log.FAC_ENCODING, Level.INFO)) {
Log.info(Log.FAC_ENCODING, "removing entry associated with name {0}", _contentNamesLRU.get(0));
}
_contents.remove(_contentNamesLRU.get(0));
_contentNamesLRU.remove(0);
}
_contentNamesLRU.add(name);
}
_contents.put(name, list);
}
}
}
protected Holder<V> getMatchByName(ContentName name, ContentObject target) {
List<Holder<V>> list;
synchronized (_contents) {
list = _contents.get(name);
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "name: {0} target: {1} possible matches: {2}", name, target.name(), ((null == list) ? 0 : list.size()));
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
return holder;
}
}
}
}
}
return null;
}
/**
* Internal: return all the entries having exactly the specified name,
* useful once you have found the matching names to collect entries from them
*
* @param name
* @param target
* @return
*/
protected List<Holder<V>> getAllMatchByName(ContentName name, ContentObject target) {
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "name: {0} target: {1}", name, target.name());
List<Holder<V>> matches = new ArrayList<Holder<V>>();
List<Holder<V>> list;
synchronized (_contents) {
list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
matches.add(holder);
}
}
}
}
}
return matches;
}
protected Holder<V> removeMatchByName(ContentName name, ContentObject target) {
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "name: {0} target: {1}", name, target.name());
synchronized (_contents) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
holdIt.remove();
if (list.size() == 0) {
_contents.remove(name);
}
return holder;
}
}
}
}
}
return null;
}
/**
* Remove first exact match entry (both name and value match).
*
* @param name ContentName of name
* @param value associated value
*
* @return the matching entry or null if none found
*/
public Entry<V> remove(ContentName name, V value) {
Holder<V> result = null;
synchronized (_contents) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null == holder.value()) {
if (null == value) {
holdIt.remove();
result = holder;
}
} else {
if (holder.value().equals(value)) {
holdIt.remove();
result = holder;
}
}
}
if (list.size() == 0) {
synchronized (_contents) {
_contents.remove(name);
}
}
}
}
return result;
}
/**
* Remove first exact match entry (both interest and value match)
*
* @param interest Interest to match
* @param value associated value
* @return the matching entry or null if none found
*/
public Entry<V> remove(Interest interest, V value) {
Holder<V> result = null;
ContentName name = interest.name();
synchronized (_contents) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (interest.equals(holder.interest())) {
if (null == holder.value()) {
if (null == value) {
holdIt.remove();
result = holder;
}
} else {
if (holder.value().equals(value)) {
holdIt.remove();
result = holder;
}
}
}
}
if (list.size() == 0) {
_contents.remove(name);
}
}
}
return result;
}
protected List<Holder<V>> removeAllMatchByName(ContentName name, ContentObject target) {
List<Holder<V>> matches = new ArrayList<Holder<V>>();
synchronized (_contents) {
List<Holder<V>> list = _contents.get(name);
if (null != list) {
for (Iterator<Holder<V>> holdIt = list.iterator(); holdIt.hasNext(); ) {
Holder<V> holder = holdIt.next();
if (null != holder.interest()) {
if (holder.interest().matches(target)) {
holdIt.remove();
matches.add(holder);
}
}
}
if (list.size() == 0) {
_contents.remove(name);
}
}
}
return matches;
}
/**
* Get value of longest matching Interest for a ContentObject, where longest is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation. If there are multiple matches, first is returned.
*
* @param target - desired ContentObject
* @return Entry of longest match if any, null if no match
*/
public V getValue(ContentObject target) {
Entry<V> match = getMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Get longest matching Interest for a ContentObject. This is the same as
* getValue() except that the Entry is returned so the matching item
* may be retrieved and null value may be detected. The Entry returned will have a
* non-null interest because this method matches only Interests in the table.
*
* @param target - desired ContentObject
* @return Entry of longest match if any, null if no match
*/
public Entry<V> getMatch(ContentObject target) {
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target.name());
Entry<V> match = null;
Set<ContentName> names;
synchronized (_contents) {
names = _contents.keySet();
for (ContentName name : names) {
match = getMatchByName(name, target);
if (null != match)
break;
}
}
return match;
}
/**
* Get values of all matching Interests for a ContentObject.
* Any ContentName entries in the table will be
* ignored by this operation and any null values will be ignored.
*
* @param target target ContentObject
* @return list of all matching values
*/
public List<V> getValues(ContentObject target) {
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target.name());
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = getMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Get all matching Interests for a ContentObject.
* Any ContentName entries in the table will be
* ignored by this operation, so every Entry returned will have a
* non-null interest. This is the same as getValues() except that
* Entry objects are returned.
*
* @param target - desired ContentObject
* @return List of matches, empty if no match
*/
public List<Entry<V>> getMatches(ContentObject target) {
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target object name: {0}", target.name());
List<Entry<V>> matches = new ArrayList<Entry<V>>();
if (null != target) {
synchronized (_contents) {
for (ContentName name : _contents.keySet()) {
// Name match - is there an interest match here?
matches.addAll(getAllMatchByName(name, target));
}
}
}
return matches;
}
/**
* Get value of longest matching Interest for a ContentName, where longest is defined
* as longest ContentName. If there are multiple matches, first is returned.
* This will return a mix of ContentName and Interest entries if they exist
* (and match) in the table, i.e. the Interest of an Entry may be null in some cases.
*
* @param target desired ContentName
* @return Entry of longest match if any, null if no match
*/
public V getValue(ContentName target) {
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target);
Entry<V> match = getMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Get longest matching Interest. This method is the same as getValue()
* except that the Entry is returned so the matching item may be retrieved
* and null value may be detected.
*
* @param target desired ContentName
* @return longest matching entry or null if none found
*/
public Entry<V> getMatch(ContentName target) {
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target);
Entry<V> match = null;
synchronized (_contents) {
for (ContentName name : _contents.keySet()) {
if (name.isPrefixOf(target)) {
match = _contents.get(name).get(0);
break;
}
}
}
return match;
}
/**
* Get values matching a target ContentName
*
* @param target the desired ContentName
* @return list of values associated with this ContentName
*/
public List<V> getValues(ContentName target) {
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target);
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = getMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Get all matching entries for a ContentName.
* This will return a mix of ContentName and Interest entries if they exist
* (and match) in the table, i.e. the Interest of an Entry may be null in some cases.
*
* @param target desired ContentName
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<Entry<V>> getMatches(ContentName target) {
if (Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "target: {0}", target);
List<Entry<V>> matches = new ArrayList<Entry<V>>();
synchronized (_contents) {
for (ContentName name : _contents.keySet()) {
if (name.isPrefixOf(target)) {
matches.addAll(_contents.get(name));
}
}
}
return matches;
}
/**
* Get all entries. This will return a mix of ContentName and Interest entries
* if they exist in the table, i.e. the Interest of an Entry may be null in some cases.
*
* @return Collection of entries in arbitrary order
*/
public Collection<Entry<V>> values() {
List<Entry<V>> results = new ArrayList<Entry<V>>();
synchronized (_contents) {
for (Iterator<ContentName> keyIt = _contents.keySet().iterator(); keyIt.hasNext();) {
ContentName name = keyIt.next();
List<Holder<V>> list = _contents.get(name);
results.addAll(list);
}
}
return results;
}
/**
* Remove and return value of the longest matching Interest for a ContentObject, where best is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation, as will null values.
*
* @param target - desired ContentObject
* @return value of longest match if any, null if no match
*/
public V removeValue(ContentObject target) {
Entry<V> match = removeMatch(target);
if (null != match) {
return match.value();
} else {
return null;
}
}
/**
* Remove and return the longest matching Interest for a ContentObject, where best is defined
* as longest ContentName. Any ContentName entries in the table will be
* ignored by this operation, so the Entry returned will have a
* non-null interest.
*
* @param target - desired ContentObject
* @return Entry of longest match if any, null if no match
*/
public Entry<V> removeMatch(ContentObject target) {
Entry<V> match = null;
if (null != target) {
ContentName matchName = null;
if(Log.isLoggable(Log.FAC_ENCODING, Level.FINEST))
Log.finest(Log.FAC_ENCODING, "removeMatch: looking for match to target {0} among {1} possibilities.", target.name(), _contents.keySet().size());
Set<ContentName> names;
synchronized (_contents) {
names = _contents.keySet();
for (ContentName name : names) {
match = getMatchByName(name, target);
if (null != match) {
matchName = name;
break;
}
// Do not remove here -- need to find best match and avoid disturbing iterator
}
if (null != match) {
return removeMatchByName(matchName, target);
}
}
}
return match;
}
/**
* Remove and return values for all matching Interests for a ContentObject.
* Any ContentName entries in the table will be
* ignored by this operation. Null values will not be represented in returned
* list though their Interests will have been removed if any.
*
* @param target - desired ContentObject
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<V> removeValues(ContentObject target) {
List<V> result = new ArrayList<V>();
List<Entry<V>> matches = removeMatches(target);
for (Entry<V> entry : matches) {
if (null != entry.value()) {
result.add(entry.value());
}
}
return result;
}
/**
* Remove and return all matching Interests for a ContentObject.
* Any ContentName entries in the table will be
* ignored by this operation, so every Entry returned will have a
* non-null interest.
*
* @param target - desired ContentObject
* @return List of matches ordered from longest match to shortest, empty if no match
*/
public List<Entry<V>> removeMatches(ContentObject target) {
List<Entry<V>> matches = new ArrayList<Entry<V>>();
List<ContentName> names = new ArrayList<ContentName>();
Set<ContentName> LFCnames;
synchronized (_contents) {
LFCnames = _contents.keySet();
for (ContentName name : LFCnames) {
if (name.isPrefixOf(target.name())) {
// Name match - is there an interest match here?
matches.addAll(getAllMatchByName(name, target));
names.add(name);
}
}
if (matches.size() != 0) {
for (ContentName contentName : names) {
removeAllMatchByName(contentName, target);
}
}
}
return matches;
}
/**
* Get the number of distinct entries in the table. Note that duplicate entries
* are fully supported, so the number of entries may be much larger than the
* number of ContentNames (sizeNames()).
*
* @return the number of entries in the table
*/
public int size() {
int result = 0;
synchronized (_contents) {
for (Iterator<ContentName> nameIt = _contents.keySet().iterator(); nameIt.hasNext();) {
ContentName name = nameIt.next();
List<Holder<V>> list = _contents.get(name);
result += list.size();
}
}
return result;
}
/**
* Get the number of distinct ContentNames in the table. Note that duplicate
* entries are fully supported, so the number of ContentNames may be much smaller
* than the number of entries (size()).
*
* @return the number of ContentNames in the table
*/
public int sizeNames() {
synchronized (_contents) {
return _contents.size();
}
}
/**
* Clear the table
*/
public void clear() {
synchronized (_contents) {
_contents.clear();
}
}
} |
package org.ccnx.ccn.utils;
import java.io.IOException;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.Header.HeaderObject;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.metadata.MetadataProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
public class updateheader {
public static void usage() {
System.out.println("usage: updateheader [-log level] <ccnname> [<ccnname>*>]\n Assumes content is in a repository.");
System.exit(1);
}
public static void moveHeader(String ccnxName, CCNHandle handle) throws MalformedContentNameStringException, IOException {
ContentName fileName = ContentName.parse(ccnxName);
// Want a versioned name, either this version or latest version
ContentName fileVersionedName = null;
if (VersioningProfile.hasTerminalVersion(fileName)) {
fileVersionedName = fileName;
} else {
ContentObject fileObject = VersioningProfile.getLatestVersion(fileName, null, SystemConfiguration.getDefaultTimeout(), null, handle);
if (null == fileObject) {
System.out.println("Cannot find file " + fileName + " to update. Skipping.");
return;
}
fileVersionedName = fileObject.name().subname(0, fileName.count() + 1);
}
// Should only update content in repositories -- makes no sense to bother with other
// content, really.
HeaderObject newHeader = new HeaderObject(MetadataProfile.headerName(fileVersionedName), null, handle);
newHeader.updateInBackground();
HeaderObject oldHeader = new HeaderObject(MetadataProfile.oldHeaderName(fileVersionedName), null, handle);
oldHeader.updateInBackground();
oldHeader.waitForData(SystemConfiguration.getDefaultTimeout());
if (!oldHeader.available()) {
System.out.println("No old-style header found. Skipping " + ccnxName);
oldHeader.cancelInterest();
newHeader.cancelInterest();
return;
}
// if we get here, the initial background update should have completed for oldHeader
if (newHeader.available()) {
System.out.println("Already have a new header: " + newHeader.getVersionedName() + ", skipping file " + ccnxName);
} else {
newHeader.cancelInterest();
newHeader.setupSave(SaveType.REPOSITORY);
newHeader.save(oldHeader.header());
newHeader.close();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int arg = 0;
if (args.length == 0)
usage();
if ((args.length > 2) && (args[0].equals("-log"))) {
Log.setDefaultLevel(Level.parse(args[1]));
arg += 2;
}
CCNHandle handle = CCNHandle.getHandle();
for (int i=arg; i < args.length; ++i) {
try {
moveHeader(args[i], handle);
} catch (Exception e) {
System.out.println("Exception processing file " + args[i] + ": " + e);
e.printStackTrace();
}
}
handle.close();
KeyManager.closeDefaultKeyManager();
}
} |
package org.jpos.iso;
/**
* BcdPrefixer constructs a prefix storing the length in BCD.
*
* @author joconnor
* @version $Revision$ $Date$
*/
@SuppressWarnings("unused")
public class BcdPrefixer implements Prefixer
{
/**
* A length prefixer for upto 9 chars. The length is encoded with 1 ASCII
* char representing 1 decimal digit.
*/
public static final BcdPrefixer L = new BcdPrefixer(1);
/**
* A length prefixer for upto 99 chars. The length is encoded with 2 ASCII
* chars representing 2 decimal digits.
*/
public static final BcdPrefixer LL = new BcdPrefixer(2);
/**
* A length prefixer for upto 999 chars. The length is encoded with 3 ASCII
* chars representing 3 decimal digits.
*/
public static final BcdPrefixer LLL = new BcdPrefixer(3);
/**
* A length prefixer for upto 9999 chars. The length is encoded with 4
* ASCII chars representing 4 decimal digits.
*/
public static final BcdPrefixer LLLL = new BcdPrefixer(4);
/**
* A length prefixer for upto 99999 chars. The length is encoded with 5
* ASCII chars representing 5 decimal digits.
*/
public static final BcdPrefixer LLLLL = new BcdPrefixer(5);
/** The number of digits allowed to express the length */
private int nDigits;
public BcdPrefixer(int nDigits)
{
this.nDigits = nDigits;
}
/**
* @see org.jpos.iso.Prefixer#encodeLength(int, byte[])
*/
public void encodeLength(int length, byte[] b)
{
for (int i = getPackedLength() - 1; i >= 0; i
int twoDigits = length % 100;
length /= 100;
b[i] = (byte)(((twoDigits / 10) << 4) + twoDigits % 10);
}
}
/**
* @see org.jpos.iso.Prefixer#decodeLength(byte[], int)
*/
public int decodeLength(byte[] b, int offset)
{
int len = 0;
for (int i = 0; i < (nDigits + 1) / 2; i++)
{
len = 100 * len + ((b[offset + i] & 0xF0) >> 4) * 10 + ((b[offset + i] & 0x0F));
}
return len;
}
/*
* (non-Javadoc)
*
* @see org.jpos.iso.Prefixer#getLengthInBytes()
*/
public int getPackedLength()
{
return (nDigits + 1) >> 1;
}
} |
package me.lockate.plugins;
import java.io.BufferedReader;
import java.io.IOException;
public class LineReader {
private BufferedReader br;
public LineReader(BufferedReader _br){
br = _br;
}
public String readExactLine() throws IOException{
StringBuilder sb = new StringBuilder();
boolean testNewLine = false;
int i; //Current char code
while ((i == br.read) >= 0){
sb.append((char)i);
if (i == '\n') break;
if (testNewLine){ //If this code is reached and exectued, that means it \r wasn't followed by \n. Return current string
sb.setLength(sb.length() - 1); //Truncate the last char
br.reset(); //Go one char back
break; //Effectively returning the current line
}
if (i == '\r'){
br.mark(1);
testNewLine = true; //Prepare to see if the \r is followed by \n
}
}
return sb.length() == 0 ? null : sb.toString();
}
} |
package antoniotoro.practica2.cliente;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalExclusionType;
import java.awt.EventQueue;
import java.awt.FlowLayout;
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.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import antoniotoro.practica2.listacorreos.Usuario;
public class Cliente extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JPanel panelContenido;
private JTable table;
private JScrollPane scroll;
private JToolBar toolBar;
private JButton btnToolbarAniadirUsuario;
private JPanel panelAniadir;
private JLabel lblNombre;
private JTextField tfNombre;
private JLabel lblApellido;
private JTextField tfApellido;
private JLabel lblEmail;
private JTextField tfEmail;
private JPanel botonera;
private JButton btnAniadir;
private JButton btnCancelar;
private static final String EXPR_REG_EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
final Pattern pattern = Pattern.compile(EXPR_REG_EMAIL);
public static String urlString = "http://localhost:8080/antoniotoro.practica2/ListaCorreosServlet";
private ModeloTablaUsuarios modeloTablaUsuarios;
/**
* Se lanza la aplicacion.
*/
public static void main(String[] args) {
try { // Para que no se vea con el look normal de Swing sino con el del sistema
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e)
{ System.err.println("Unable to load System look and feel"); }
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Cliente frame = new Cliente();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Se crea la ventana.
*/
public Cliente() {
setTitle("Pr\u00E1ctica 2 - Antonio Toro");
setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 300);
setLocationRelativeTo(null);
panelContenido = new JPanel();
panelContenido.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(panelContenido);
panelContenido.setLayout(new BorderLayout(0, 0));
List<Usuario> listaUsuarios = obtenerListaUsuarios();
modeloTablaUsuarios = new ModeloTablaUsuarios(listaUsuarios);
table = new JTable(modeloTablaUsuarios) {
private static final long serialVersionUID = 1L;
@Override
public void editingStopped(ChangeEvent e) {
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
Usuario usuario = new Usuario(modeloTablaUsuarios.getUsuarioAt(editingRow));
if (editingColumn < 2) {
switch (editingColumn) {
case 0:
usuario.setNombre((String) value);
break;
case 1:
usuario.setApellido((String) value);
break;
default:
break;
}
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "actualizarUsuario");
parametros.put("nombre", usuario.getNombre());
parametros.put("apellido", usuario.getApellido());
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
// System.out.println(codigo);
// System.out.println(mensaje);
switch (codigo) {
case 0:
setValueAt(value, editingRow, editingColumn);
break;
default:
JOptionPane.showMessageDialog(Cliente.this,
mensaje,
"Error",
JOptionPane.ERROR_MESSAGE);
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
removeEditor();
}
}
};
/*
* Accion empleada en los botones de la tabla que permite que ese usuario/fila
* sea eliminado.
*/
Action borrarFila = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
int modelRow = Integer.valueOf( e.getActionCommand() );
Usuario usuario = modeloTablaUsuarios.getUsuarioAt(modelRow);
int resultadoDialogo = JOptionPane.showConfirmDialog(
Cliente.this,
"Ests seguro de que quieres elinimar el usuario <"+usuario.getEmail()+">?",
"Eliminar usuario",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (resultadoDialogo == JOptionPane.YES_OPTION) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "eliminarUsuario");
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
// System.out.println(codigo);
// System.out.println(mensaje);
switch (codigo) {
case 0:
modeloTablaUsuarios.removeRow(modelRow);
break;
default:
JOptionPane.showMessageDialog(Cliente.this,
mensaje,
"Error",
JOptionPane.ERROR_MESSAGE);
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
};
// Hacemos que la cuarta columna sea el boton cuya accion la de borrarFila
new ButtonColumn(table, borrarFila, 3);
table.putClientProperty("terminateEditOnFocusLost", true);
scroll = new JScrollPane(table);
panelContenido.add(scroll, BorderLayout.CENTER);
toolBar = new JToolBar();
toolBar.setFloatable(false);
panelContenido.add(toolBar, BorderLayout.NORTH);
btnToolbarAniadirUsuario = new JButton("A\u00F1adir Usuario");
btnToolbarAniadirUsuario.setActionCommand("ADDUSER");
btnToolbarAniadirUsuario.addActionListener(this);
toolBar.add(btnToolbarAniadirUsuario);
panelAniadir = new JPanel();
panelAniadir.setVisible(false);
panelContenido.add(panelAniadir, BorderLayout.EAST);
GridBagLayout gbl_panelAniadir = new GridBagLayout();
gbl_panelAniadir.columnWidths = new int[]{0, 0, 0, 0};
gbl_panelAniadir.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelAniadir.columnWeights = new double[]{1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panelAniadir.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
panelAniadir.setLayout(gbl_panelAniadir);
lblNombre = new JLabel("Nombre: ");
lblNombre.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblNombre = new GridBagConstraints();
gbc_lblNombre.insets = new Insets(0, 0, 5, 5);
gbc_lblNombre.anchor = GridBagConstraints.EAST;
gbc_lblNombre.gridx = 0;
gbc_lblNombre.gridy = 0;
panelAniadir.add(lblNombre, gbc_lblNombre);
tfNombre = new JTextField();
GridBagConstraints gbc_tfNombre = new GridBagConstraints();
gbc_tfNombre.insets = new Insets(0, 0, 5, 5);
gbc_tfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_tfNombre.gridx = 1;
gbc_tfNombre.gridy = 0;
panelAniadir.add(tfNombre, gbc_tfNombre);
tfNombre.setColumns(10);
lblApellido = new JLabel("Apellido: ");
lblApellido.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblApellido = new GridBagConstraints();
gbc_lblApellido.anchor = GridBagConstraints.EAST;
gbc_lblApellido.insets = new Insets(0, 0, 5, 5);
gbc_lblApellido.gridx = 0;
gbc_lblApellido.gridy = 1;
panelAniadir.add(lblApellido, gbc_lblApellido);
tfApellido = new JTextField();
GridBagConstraints gbc_tfApellido = new GridBagConstraints();
gbc_tfApellido.insets = new Insets(0, 0, 5, 5);
gbc_tfApellido.fill = GridBagConstraints.HORIZONTAL;
gbc_tfApellido.gridx = 1;
gbc_tfApellido.gridy = 1;
panelAniadir.add(tfApellido, gbc_tfApellido);
tfApellido.setColumns(10);
lblEmail = new JLabel("Email: ");
lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblEmail = new GridBagConstraints();
gbc_lblEmail.anchor = GridBagConstraints.EAST;
gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
gbc_lblEmail.gridx = 0;
gbc_lblEmail.gridy = 2;
panelAniadir.add(lblEmail, gbc_lblEmail);
tfEmail = new JTextField();
GridBagConstraints gbc_tfEmail = new GridBagConstraints();
gbc_tfEmail.insets = new Insets(0, 0, 5, 5);
gbc_tfEmail.fill = GridBagConstraints.HORIZONTAL;
gbc_tfEmail.gridx = 1;
gbc_tfEmail.gridy = 2;
panelAniadir.add(tfEmail, gbc_tfEmail);
tfEmail.setColumns(10);
tfEmail.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btnAniadir.doClick();
}
});
botonera = new JPanel();
GridBagConstraints gbc_botonera = new GridBagConstraints();
gbc_botonera.gridwidth = 2;
gbc_botonera.insets = new Insets(0, 0, 0, 5);
gbc_botonera.fill = GridBagConstraints.BOTH;
gbc_botonera.gridx = 0;
gbc_botonera.gridy = 7;
panelAniadir.add(botonera, gbc_botonera);
botonera.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnAniadir = new JButton("A\u00F1adir");
btnAniadir.setActionCommand("EXEC_ANIADIR");
btnAniadir.addActionListener(this);
botonera.add(btnAniadir);
btnCancelar = new JButton("Cancelar");
btnCancelar.setActionCommand("CANCELAR");
btnCancelar.addActionListener(this);
botonera.add(btnCancelar);
}
/**
* Obtiene la lista de usuarios del servlet.
* @return Lista con los usuarios
*/
@SuppressWarnings("unchecked")
private List<Usuario> obtenerListaUsuarios() {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "listarUsuarios");
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
List<Usuario> listaUsuarios = (List<Usuario>) respuesta.readObject();
return listaUsuarios;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADDUSER")) {
panelAniadir.setVisible(true);
}
else if (e.getActionCommand().equals("EXEC_ANIADIR")) {
Matcher matcher = pattern.matcher(tfEmail.getText());
String nombre = tfNombre.getText(),
apellido = tfApellido.getText(),
email = tfEmail.getText();
String fraseError = "";
boolean error = false;
if (nombre.equals("")) {
error = true;
fraseError += "\n Debe introducir un nombre";
}
if (apellido.equals("")) {
error = true;
fraseError += "\n Debe introducir un apellido";
}
if (!matcher.matches()) {
error = true;
fraseError += "\n Correo electr\u00F3nico no v\u00E1lido.";
}
if (!error) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "aniadirUsuario");
parametros.put("nombre", nombre);
parametros.put("apellido", apellido);
parametros.put("email", email);
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
// System.out.println(codigo);
// System.out.println(mensaje);
switch (codigo) {
case 0:
Usuario usuario = new Usuario();
usuario.setNombre(tfNombre.getText());
usuario.setApellido(tfApellido.getText());
usuario.setEmail(tfEmail.getText());
modeloTablaUsuarios.add(usuario);
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
break;
default:
JOptionPane.showMessageDialog(Cliente.this,
mensaje,
"Error",
JOptionPane.ERROR_MESSAGE);
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(Cliente.this,
fraseError,
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("CANCELAR")) {
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
panelAniadir.setVisible(false);
}
}
/**
* Realiza una peticin POST a una URL con los parametros provistos.
* @param urlString Direccion a la que se desea realizar a peticion
* @param parametros Parametros de la peticion
* @return Respuesta obtenida o <tt>null</tt> en caso de fallo
*/
@SuppressWarnings("deprecation")
public InputStream realizarPeticionPost(String urlString, Map<String,String> parametros) {
String cadenaParametros = "";
boolean primerPar = true;
for (Map.Entry<String, String> entry : parametros.entrySet()) {
if (!primerPar) {
cadenaParametros += "&";
} else {
primerPar = false;
}
String parDeParametro = String.format("%s=%s",
URLEncoder.encode(entry.getKey()),
URLEncoder.encode(entry.getValue()));
cadenaParametros += parDeParametro;
}
try {
URL url = new URL(urlString);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setUseCaches(false);
conexion.setRequestMethod("POST");
conexion.setDoOutput(true);
OutputStream output = conexion.getOutputStream();
output.write(cadenaParametros.getBytes());
output.flush();
output.close();
return conexion.getInputStream();
} catch (MalformedURLException | ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
} |
package com.algorithm;
public class Main {
public static void main(String[] args) {
// test
int a[] = { 10,9,8,7,6,5,4,3,2,1,0,2};
print_Array(a);
Merge_sort(a,0,a.length-1);
print_Array(a);
}
public static void merge(int a[], int start, int middle, int end){
int start_pos = start;
int tmp[] = new int[a.length];
int left_pos = start;// use for sort
int tmp_pos = start;//use for tmp replacing a
int right_pos = middle + 1;
while( (left_pos <= middle)&&(right_pos <= end)){
//add smaller one to tmp
if(a[left_pos] <= a[right_pos])
tmp[start_pos++] = a[left_pos++];
else tmp[start_pos++] = a[right_pos++];
}
//add rest number to tmp
while( left_pos <= middle )
tmp[start_pos++] = a[left_pos++];//add rest of left
while( right_pos <= end)
tmp[start_pos++] = a[right_pos++];//add rest of right
while( tmp_pos <= end){
//add elements of tmp to a
a[tmp_pos] = tmp[tmp_pos];
tmp_pos++;
}
}
public static void Merge_sort(int a[], int start, int end){
int middle;
if(start < end){
middle = (start + end)/2;
Merge_sort(a, start, middle);//merge sort left
Merge_sort(a, middle + 1, end);
merge(a, start, middle, end);
}
else return;
}
public static void print_Array(int a[]){
//print array
for (int element:a
) {
System.out.print(element + " ");
}
System.out.println("fuck youuuuuuuuu");
}
} |
package be.ibridge.kettle.trans.step;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.w3c.dom.Node;
import be.ibridge.kettle.cluster.ClusterSchema;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.GUIPositionInterface;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.SharedObjectBase;
import be.ibridge.kettle.core.SharedObjectInterface;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepLoaderException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
/**
* This class contains everything that is needed to define a step.
*
* @since 27-mei-2003
* @author Matt
*
*/
public class StepMeta extends SharedObjectBase implements Cloneable, Comparable, GUIPositionInterface, SharedObjectInterface
{
public static final String XML_TAG = "step";
private String stepid; // --> StepPlugin.id
private String stepname;
private StepMetaInterface stepMetaInterface;
private boolean selected;
private boolean distributes;
private int copies;
private Point location;
private boolean drawstep;
private String description;
private boolean terminator;
private StepPartitioningMeta stepPartitioningMeta;
private ClusterSchema clusterSchema;
private String clusterSchemaName; // temporary to resolve later.
private StepErrorMeta stepErrorMeta;
// private LogWriter log;
private long id;
/**
* @param stepid The ID of the step: this is derived information, you can also use the constructor without stepid.
* This constructor will be deprecated soon.
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepname, stepMetaInterface);
if (this.stepid==null) this.stepid = stepid;
}
/**
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepname, StepMetaInterface stepMetaInterface)
{
if (stepMetaInterface!=null)
{
this.stepid = StepLoader.getInstance().getStepPluginID(stepMetaInterface);
}
this.stepname = stepname;
this.stepMetaInterface = stepMetaInterface;
selected = false;
distributes = true;
copies = 1;
location = new Point(0,0);
drawstep = false;
description = null;
stepPartitioningMeta = new StepPartitioningMeta();
clusterSchema = null; // non selected by default.
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param stepid
* @param stepname
* @param stepMetaInterface
*/
public StepMeta(LogWriter log, String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepid, stepname, stepMetaInterface);
}
public StepMeta()
{
this((String)null, (String)null, (StepMetaInterface)null);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
*/
public StepMeta(LogWriter log)
{
this();
}
public String getXML()
{
StringBuffer retval=new StringBuffer(200); //$NON-NLS-1$
retval.append(" <").append(XML_TAG).append('>').append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("name", getName()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("type", getStepID()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("description", description) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("distribute", distributes) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("copies", copies) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append( stepPartitioningMeta.getXML() );
retval.append( stepMetaInterface.getXML() );
retval.append(" ").append(XMLHandler.addTagValue("cluster_schema", clusterSchema==null?"":clusterSchema.getName()));
retval.append(" <GUI>").append(Const.CR); //$NON-NLS-1$
retval.append(" <xloc>").append(location.x).append("</xloc>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <yloc>").append(location.y).append("</yloc>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <draw>").append((drawstep?"Y":"N")).append("</draw>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
retval.append(" </GUI>").append(Const.CR); //$NON-NLS-1$
retval.append(" </"+XML_TAG+">").append(Const.CR).append(Const.CR); //$NON-NLS-1$
return retval.toString();
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(LogWriter log, Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this(stepnode, databases, counters);
}
/**
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this();
LogWriter log = LogWriter.getInstance();
StepLoader steploader = StepLoader.getInstance();
try
{
stepname = XMLHandler.getTagValue(stepnode, "name"); //$NON-NLS-1$
stepid = XMLHandler.getTagValue(stepnode, "type"); //$NON-NLS-1$
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.LookingForTheRightStepNode",stepname)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// Create a new StepMetaInterface object...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
// Load the specifics from XML...
if (stepMetaInterface!=null)
{
stepMetaInterface.loadXML(stepnode, databases, counters);
}
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.SpecificLoadedStep",stepname)); //$NON-NLS-1$ //$NON-NLS-2$
/* Handle info general to all step types...*/
description = XMLHandler.getTagValue(stepnode, "description"); //$NON-NLS-1$
copies = Const.toInt(XMLHandler.getTagValue(stepnode, "copies"), 1); //$NON-NLS-1$
String sdistri = XMLHandler.getTagValue(stepnode, "distribute"); //$NON-NLS-1$
distributes = "Y".equalsIgnoreCase(sdistri); //$NON-NLS-1$
if (sdistri==null) distributes=true; // default=distribute
// Handle GUI information: location & drawstep?
String xloc, yloc;
int x,y;
xloc=XMLHandler.getTagValue(stepnode, "GUI", "xloc"); //$NON-NLS-1$ //$NON-NLS-2$
yloc=XMLHandler.getTagValue(stepnode, "GUI", "yloc"); //$NON-NLS-1$ //$NON-NLS-2$
try{ x=Integer.parseInt(xloc); } catch(Exception e) { x=0; }
try{ y=Integer.parseInt(yloc); } catch(Exception e) { y=0; }
location=new Point(x,y);
drawstep = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "GUI", "draw")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// The partitioning information?
Node partNode = XMLHandler.getSubNode(stepnode, "partitioning");
stepPartitioningMeta = new StepPartitioningMeta(partNode);
clusterSchemaName = XMLHandler.getTagValue(stepnode, "cluster_schema"); // resolve to clusterSchema later
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.EndOfReadXML")); //$NON-NLS-1$ //$NON-NLS-2$
}
catch(Exception e)
{
throw new KettleXMLException(Messages.getString("StepMeta.Exception.UnableToLoadStepInfo"), e); //$NON-NLS-1$
}
}
/**
* Resolves the name of the cluster loaded from XML/Repository to the correct clusterSchema object
* @param clusterSchemas The list of clusterSchemas to reference.
*/
public void setClusterSchemaAfterLoading(List clusterSchemas)
{
if (clusterSchemaName==null) return;
for (int i=0;i<clusterSchemas.size();i++)
{
ClusterSchema look = (ClusterSchema) clusterSchemas.get(i);
if (look.getName().equals(clusterSchemaName)) clusterSchema=look;
}
}
public long getID()
{
return id;
}
public void setID(long id)
{
this.id = id;
}
/**
* See wether or not the step is drawn on the canvas.
*
* @return True if the step is drawn on the canvas.
*/
public boolean isDrawn()
{
return drawstep;
}
/**
* See wether or not the step is drawn on the canvas.
* Same as isDrawn(), but needed for findMethod(StepMeta, drawstep)
* called by StringSearcher.findMetaData(). Otherwise findMethod() returns
* be.ibridge.kettle.trans.step.StepMeta.drawStep() instead of isDrawn().
* @return True if the step is drawn on the canvas.
*/
public boolean isDrawStep()
{
return drawstep;
}
/**
* Sets the draw attribute of the step so that it will be drawn on the canvas.
*
* @param draw True if you want the step to show itself on the canvas, False if you don't.
*/
public void setDraw(boolean draw)
{
drawstep=draw;
setChanged();
}
/**
* Sets the number of parallel copies that this step will be launched with.
*
* @param c The number of copies.
*/
public void setCopies(int c)
{
if (copies!=c) setChanged();
copies=c;
}
public int getCopies()
{
// If the step is partitioned, that's going to determine the number of copies, nothing else...
if (isPartitioned() && getStepPartitioningMeta().getPartitionSchema()!=null)
{
String[] partitionIDs = getStepPartitioningMeta().getPartitionSchema().getPartitionIDs();
if (partitionIDs!=null && partitionIDs.length>0) // these are the partitions the step can "reach"
{
return partitionIDs.length;
}
}
return copies;
}
public void drawStep()
{
setDraw(true);
setChanged();
}
public void hideStep()
{
setDraw(false);
setChanged();
}
/**
* Two steps are equal if their names are equal.
* @return true if the two steps are equal.
*/
public boolean equals(Object obj)
{
if (obj==null) return false;
StepMeta stepMeta = (StepMeta)obj;
return getName().equalsIgnoreCase(stepMeta.getName());
}
public int hashCode()
{
return stepname.hashCode();
}
public int compareTo(Object o)
{
return toString().compareTo(((StepMeta)o).toString());
}
public boolean hasChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
return bsi!=null?bsi.hasChanged():false;
}
public void setChanged(boolean ch)
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged(ch);
}
public void setChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged();
}
public boolean chosesTargetSteps()
{
if (getStepMetaInterface()!=null)
{
return getStepMetaInterface().getTargetSteps()!=null;
}
return false;
}
public Object clone()
{
StepMeta stepMeta = new StepMeta();
stepMeta.replaceMeta(this);
stepMeta.setID(-1L);
return stepMeta;
}
public void replaceMeta(StepMeta stepMeta)
{
this.stepid = stepMeta.stepid; // --> StepPlugin.id
this.stepname = stepMeta.stepname;
if (stepMeta.stepMetaInterface!=null)
{
this.stepMetaInterface = (StepMetaInterface) stepMeta.stepMetaInterface.clone();
}
else
{
this.stepMetaInterface = null;
}
this.selected = stepMeta.selected;
this.distributes = stepMeta.distributes;
this.copies = stepMeta.copies;
if (stepMeta.location!=null)
{
this.location = new Point(stepMeta.location.x, stepMeta.location.y);
}
else
{
this.location = null;
}
this.drawstep = stepMeta.drawstep;
this.description = stepMeta.description;
this.terminator = stepMeta.terminator;
if (stepMeta.stepPartitioningMeta!=null)
{
this.stepPartitioningMeta = (StepPartitioningMeta) stepMeta.stepPartitioningMeta.clone();
}
else
{
this.stepPartitioningMeta = null;
}
if (stepMeta.clusterSchema!=null)
{
this.clusterSchema = (ClusterSchema) stepMeta.clusterSchema.clone();
}
else
{
this.clusterSchema = null;
}
this.clusterSchemaName = stepMeta.clusterSchemaName; // temporary to resolve later.
// this.setShared(stepMeta.isShared());
this.id = stepMeta.getID();
this.setChanged(true);
}
public StepMetaInterface getStepMetaInterface()
{
return stepMetaInterface;
}
public String getStepID()
{
return stepid;
}
/*
public String getStepTypeDesc()
{
return BaseStep.type_desc[steptype];
}
*/
public String getName()
{
return stepname;
}
public void setName(String sname)
{
stepname=sname;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description=description;
}
public void setSelected(boolean sel)
{
selected=sel;
}
public void flipSelected()
{
selected=!selected;
}
public boolean isSelected()
{
return selected;
}
public void setTerminator()
{
setTerminator(true);
}
public void setTerminator(boolean t)
{
terminator = t;
}
public boolean hasTerminator()
{
return terminator;
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
* @param id_step
*/
public StepMeta(LogWriter log, long id_step)
{
this((String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
public StepMeta(long id_step)
{
this((String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(LogWriter log, Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this(rep, id_step, databases, counters, partitionSchemas);
}
/**
* Create a new step by loading the metadata from the specified repository.
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this();
StepLoader steploader = StepLoader.getInstance();
try
{
Row r = rep.getStep(id_step);
if (r!=null)
{
setID(id_step);
stepname = r.searchValue("NAME").getString(); //$NON-NLS-1$
//System.out.println("stepname = "+stepname);
description = r.searchValue("DESCRIPTION").getString(); //$NON-NLS-1$
//System.out.println("description = "+description);
long id_step_type = r.searchValue("ID_STEP_TYPE").getInteger(); //$NON-NLS-1$
//System.out.println("id_step_type = "+id_step_type);
Row steptyperow = rep.getStepType(id_step_type);
stepid = steptyperow.searchValue("CODE").getString(); //$NON-NLS-1$
distributes = r.searchValue("DISTRIBUTE").getBoolean(); //$NON-NLS-1$
copies = (int)r.searchValue("COPIES").getInteger(); //$NON-NLS-1$
int x = (int)r.searchValue("GUI_LOCATION_X").getInteger(); //$NON-NLS-1$
int y = (int)r.searchValue("GUI_LOCATION_Y").getInteger(); //$NON-NLS-1$
location = new Point(x,y);
drawstep = r.searchValue("GUI_DRAW").getBoolean(); //$NON-NLS-1$
// Generate the appropriate class...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid+Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
if (stepMetaInterface!=null)
{
// Read the step info from the repository!
stepMetaInterface.readRep(rep, getID(), databases, counters);
}
// Get the partitioning as well...
stepPartitioningMeta = new StepPartitioningMeta(rep, getID());
// Get the cluster schema name
clusterSchemaName = rep.getStepAttributeString(id_step, "cluster_schema");
}
else
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepInfoCouldNotBeFound",String.valueOf(id_step))); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepCouldNotBeLoaded",String.valueOf(getID())), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void saveRep(Repository rep, long id_transformation)
throws KettleException
{
LogWriter log = LogWriter.getInstance();
try
{
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveNewStep")); //$NON-NLS-1$
// Insert new Step in repository
setID(rep.insertStep( id_transformation,
getName(),
getDescription(),
getStepID(),
distributes,
copies,
getLocation()==null?-1:getLocation().x,
getLocation()==null?-1:getLocation().y,
isDrawn()
)
);
// Save partitioning selection for the step
stepPartitioningMeta.saveRep(rep, id_transformation, getID());
// The id_step is known, as well as the id_transformation
// This means we can now save the attributes of the step...
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveStepDetails")); //$NON-NLS-1$
stepMetaInterface.saveRep(rep, id_transformation, getID());
// Save the clustering schema that was chosen.
rep.saveStepAttribute(id_transformation, getID(), "cluster_schema", clusterSchema==null?"":clusterSchema.getName());
}
catch(KettleException e)
{
throw new KettleException(Messages.getString("StepMeta.Exception.UnableToSaveStepInfo",String.valueOf(id_transformation)), e); //$NON-NLS-1$
}
}
public void setLocation(int x, int y)
{
int nx = (x>=0?x:0);
int ny = (y>=0?y:0);
Point loc = new Point(nx,ny);
if (!loc.equals(location)) setChanged();
location=loc;
}
public void setLocation(Point loc)
{
if (loc!=null && !loc.equals(location)) setChanged();
location = loc;
}
public Point getLocation()
{
return location;
}
public void check(ArrayList remarks, Row prev, String input[], String output[], Row info)
{
stepMetaInterface.check(remarks, this, prev, input, output, info);
}
public String toString()
{
if (getName()==null) return getClass().getName();
return getName();
}
/**
* @return true is the step is partitioned
*/
public boolean isPartitioned()
{
return stepPartitioningMeta.isPartitioned();
}
/**
* @return the stepPartitioningMeta
*/
public StepPartitioningMeta getStepPartitioningMeta()
{
return stepPartitioningMeta;
}
/**
* @param stepPartitioningMeta the stepPartitioningMeta to set
*/
public void setStepPartitioningMeta(StepPartitioningMeta stepPartitioningMeta)
{
this.stepPartitioningMeta = stepPartitioningMeta;
}
/**
* @return the clusterSchema
*/
public ClusterSchema getClusterSchema()
{
return clusterSchema;
}
/**
* @param clusterSchema the clusterSchema to set
*/
public void setClusterSchema(ClusterSchema clusterSchema)
{
this.clusterSchema = clusterSchema;
}
/**
* @return the distributes
*/
public boolean isDistributes()
{
return distributes;
}
/**
* @param distributes the distributes to set
*/
public void setDistributes(boolean distributes)
{
this.distributes = distributes;
}
/**
* @return the StepErrorMeta error handling metadata for this step
*/
public StepErrorMeta getStepErrorMeta()
{
return stepErrorMeta;
}
/**
* @param stepErrorMeta the error handling metadata for this step
*/
public void setStepErrorMeta(StepErrorMeta stepErrorMeta)
{
this.stepErrorMeta = stepErrorMeta;
}
/**
* Find a step with the ID in a given ArrayList of steps
*
* @param steps The List of steps to search
* @param id The ID of the step
* @return The step if it was found, null if nothing was found
*/
public static final StepMeta findStep(List steps, long id)
{
if (steps == null) return null;
for (int i = 0; i < steps.size(); i++)
{
StepMeta stepMeta = (StepMeta) steps.get(i);
if (stepMeta.getID() == id) return stepMeta;
}
return null;
}
/**
* Find a step with its name in a given ArrayList of steps
*
* @param steps The List of steps to search
* @param stepname The name of the step
* @return The step if it was found, null if nothing was found
*/
public static final StepMeta findStep(List steps, String stepname)
{
if (steps == null) return null;
for (int i = 0; i < steps.size(); i++)
{
StepMeta stepMeta = (StepMeta) steps.get(i);
if (stepMeta.getName().equalsIgnoreCase(stepname)) return stepMeta;
}
return null;
}
public boolean supportsErrorHandling()
{
return stepMetaInterface.supportsErrorHandling();
}
/**
* @return if error handling is supported for this step, if error handling is defined and a target step is set
*/
public boolean isDoingErrorHandling()
{
return stepMetaInterface.supportsErrorHandling() &&
stepErrorMeta!=null &&
stepErrorMeta.getTargetStep()!=null &&
stepErrorMeta.isEnabled()
;
}
public boolean isSendingErrorRowsToStep(StepMeta targetStep)
{
return (isDoingErrorHandling() && stepErrorMeta.getTargetStep().equals(targetStep));
}
} |
/*
* $Log: JtaUtil.java,v $
* Revision 1.8 2006-09-14 11:47:10 europe\L190409
* optimized transactionStateCompatible()
*
* Revision 1.7 2006/08/21 15:14:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* introduction of transaction attribute handling
* configuration of user transaction url in appconstants.properties
*
* Revision 1.6 2005/09/08 15:58:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added logging
*
* Revision 1.5 2004/10/05 09:57:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made version public
*
* Revision 1.4 2004/03/31 15:03:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* fixed javadoc
*
* Revision 1.3 2004/03/26 10:42:38 Johan Verrips <johan.verrips@ibissource.org>
* added @version tag in javadoc
*
* Revision 1.2 2004/03/26 09:50:52 Johan Verrips <johan.verrips@ibissource.org>
* Updated javadoc
*
* Revision 1.1 2004/03/23 17:14:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* initial version
*
*/
package nl.nn.adapterframework.util;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.NotSupportedException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import nl.nn.adapterframework.core.TransactionException;
import org.apache.log4j.Logger;
/**
* Utility functions for JTA
* @version Id
* @author Gerrit van Brakel
* @since 4.1
*/
public class JtaUtil {
public static final String version="$RCSfile: JtaUtil.java,v $ $Revision: 1.8 $ $Date: 2006-09-14 11:47:10 $";
private static Logger log = Logger.getLogger(JtaUtil.class);
private static final String USERTRANSACTION_URL1_KEY="jta.userTransactionUrl1";
private static final String USERTRANSACTION_URL2_KEY="jta.userTransactionUrl2";
public static final int TRANSACTION_ATTRIBUTE_REQUIRED=0;
public static final int TRANSACTION_ATTRIBUTE_REQUIRES_NEW=1;
public static final int TRANSACTION_ATTRIBUTE_MANDATORY=2;
public static final int TRANSACTION_ATTRIBUTE_NOT_SUPPORTED=3;
public static final int TRANSACTION_ATTRIBUTE_SUPPORTS=4;
public static final int TRANSACTION_ATTRIBUTE_NEVER=5;
public static final int TRANSACTION_ATTRIBUTE_DEFAULT=TRANSACTION_ATTRIBUTE_SUPPORTS;
public static final String TRANSACTION_ATTRIBUTE_REQUIRED_STR="Required";
public static final String TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR="RequiresNew";
public static final String TRANSACTION_ATTRIBUTE_MANDATORY_STR="Mandatory";
public static final String TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR="NotSupported";
public static final String TRANSACTION_ATTRIBUTE_SUPPORTS_STR="Supports";
public static final String TRANSACTION_ATTRIBUTE_NEVER_STR="Never";
public static final String transactionAttributes[]=
{
TRANSACTION_ATTRIBUTE_REQUIRED_STR,
TRANSACTION_ATTRIBUTE_REQUIRES_NEW_STR,
TRANSACTION_ATTRIBUTE_MANDATORY_STR,
TRANSACTION_ATTRIBUTE_NOT_SUPPORTED_STR,
TRANSACTION_ATTRIBUTE_SUPPORTS_STR,
TRANSACTION_ATTRIBUTE_NEVER_STR
};
private static UserTransaction utx;
/**
* returns a meaningful string describing the transaction status.
*/
public static String displayTransactionStatus(int status) {
switch (status) {
case Status.STATUS_ACTIVE : return status+"=STATUS_ACTIVE:"+ " A transaction is associated with the target object and it is in the active state.";
case Status.STATUS_COMMITTED : return status+"=STATUS_COMMITTED:"+ " A transaction is associated with the target object and it has been committed.";
case Status.STATUS_COMMITTING : return status+"=STATUS_COMMITTING:"+ " A transaction is associated with the target object and it is in the process of committing.";
case Status.STATUS_MARKED_ROLLBACK : return status+"=STATUS_MARKED_ROLLBACK:"+" A transaction is associated with the target object and it has been marked for rollback, perhaps as a result of a setRollbackOnly operation.";
case Status.STATUS_NO_TRANSACTION : return status+"=STATUS_NO_TRANSACTION:"+ " No transaction is currently associated with the target object.";
case Status.STATUS_PREPARED : return status+"=STATUS_PREPARED:"+ " A transaction is associated with the target object and it has been prepared.";
case Status.STATUS_PREPARING : return status+"=STATUS_PREPARING:"+ " A transaction is associated with the target object and it is in the process of preparing.";
case Status.STATUS_ROLLEDBACK : return status+"=STATUS_ROLLEDBACK:"+ " A transaction is associated with the target object and the outcome has been determined to be rollback.";
case Status.STATUS_ROLLING_BACK : return status+"=STATUS_ROLLING_BACK:"+ " A transaction is associated with the target object and it is in the process of rolling back.";
case Status.STATUS_UNKNOWN : return status+"=STATUS_UNKNOWN:"+ " A transaction is associated with the target object but its current status cannot be determined.";
default : return "unknown transaction status";
}
}
/**
* Convenience function for {@link #displayTransactionStatus(int status)}
*/
public static String displayTransactionStatus(Transaction tx) {
try {
return displayTransactionStatus(tx.getStatus());
} catch (Exception e) {
return "exception obtaining transaction status from transaction ["+tx+"]: "+e.getMessage();
}
}
/**
* Convenience function for {@link #displayTransactionStatus(int status)}
*/
public static String displayTransactionStatus(UserTransaction utx) {
try {
return displayTransactionStatus(utx.getStatus());
} catch (Exception e) {
return "exception obtaining transaction status from transaction ["+utx+"]: "+e.getMessage();
}
}
/**
* Convenience function for {@link #displayTransactionStatus(int status)}
*/
public static String displayTransactionStatus(TransactionManager tm) {
try {
return displayTransactionStatus(tm.getStatus());
} catch (Exception e) {
return "exception obtaining transaction status from transactionmanager ["+tm+"]: "+e.getMessage();
}
}
/**
* Convenience function for {@link #displayTransactionStatus(int status)}
*/
public static String displayTransactionStatus() {
UserTransaction utx;
try {
utx = getUserTransaction();
} catch (Exception e) {
return "exception obtaining user transaction: "+e.getMessage();
}
return displayTransactionStatus(utx);
}
/**
* returns true if the current thread is associated with a transaction
*/
public static boolean inTransaction(UserTransaction utx) throws SystemException {
return utx != null && utx.getStatus() != Status.STATUS_NO_TRANSACTION;
}
/**
* Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions.
*/
public static UserTransaction getUserTransaction(Context ctx, String userTransactionUrl) throws NamingException {
if (utx == null) {
log.debug("looking up UserTransaction ["+userTransactionUrl+"] in context ["+ctx.toString()+"]");
utx = (UserTransaction)ctx.lookup(userTransactionUrl);
}
return utx;
}
/**
* Returns a UserTransaction object, that is used by Receivers and PipeLines to demarcate transactions.
*/
public static UserTransaction getUserTransaction() throws NamingException {
if (utx == null) {
Context ctx= (Context) new InitialContext();
String url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL1_KEY,null);
log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]");
try {
utx = (UserTransaction)ctx.lookup(url);
} catch (Exception e) {
log.debug("Could not lookup UserTransaction from url ["+url+"], will try alternative uri",e);
url = AppConstants.getInstance().getProperty(USERTRANSACTION_URL2_KEY,null);
log.debug("looking up UserTransaction ["+url+"] in context ["+ctx.toString()+"]");
utx = (UserTransaction)ctx.lookup(url);
}
}
return utx;
}
public static int getTransactionAttributeNum(String transactionAttribute) {
int i=transactionAttributes.length-1;
while (i>=0 && !transactionAttributes[i].equalsIgnoreCase(transactionAttribute))
i--; // try next
return i;
}
public static String getTransactionAttributeString(int transactionAttribute) {
if (transactionAttribute<0 || transactionAttribute>=transactionAttributes.length) {
return "UnknownTransactionAttribute:"+transactionAttribute;
}
return transactionAttributes[transactionAttribute];
}
public static boolean transactionStateCompatible(int transactionAttribute) throws SystemException, NamingException {
if (transactionAttribute==TRANSACTION_ATTRIBUTE_NEVER) {
return !inTransaction(getUserTransaction());
} else if (transactionAttribute==TRANSACTION_ATTRIBUTE_MANDATORY) {
return inTransaction(getUserTransaction());
}
return true;
}
public static boolean isolationRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException {
if (transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW &&
transactionAttribute!=TRANSACTION_ATTRIBUTE_NOT_SUPPORTED) {
return false;
}
UserTransaction utx = getUserTransaction();
if (!transactionStateCompatible(transactionAttribute)) {
throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]");
}
return inTransaction(utx) &&
(transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW ||
transactionAttribute==TRANSACTION_ATTRIBUTE_NOT_SUPPORTED);
}
public static boolean newTransactionRequired(int transactionAttribute) throws SystemException, TransactionException, NamingException {
UserTransaction utx = getUserTransaction();
if (!transactionStateCompatible(transactionAttribute)) {
throw new TransactionException("transaction attribute ["+getTransactionAttributeString(transactionAttribute)+"] not compatible with state ["+displayTransactionStatus(utx)+"]");
}
return transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRES_NEW ||
(!inTransaction(utx) && transactionAttribute==TRANSACTION_ATTRIBUTE_REQUIRED);
}
private static boolean stateEvaluationRequired(int transactionAttribute) {
return transactionAttribute>=0 &&
transactionAttribute!=TRANSACTION_ATTRIBUTE_REQUIRES_NEW &&
transactionAttribute!=TRANSACTION_ATTRIBUTE_SUPPORTS;
}
public static void startTransaction() throws NamingException, NotSupportedException, SystemException {
log.debug("starting new transaction");
utx=getUserTransaction();
utx.begin();
}
public static void finishTransaction() throws NamingException, IllegalStateException, SecurityException, SystemException {
finishTransaction(false);
}
public static void finishTransaction(boolean rollbackonly) throws NamingException, IllegalStateException, SecurityException, SystemException {
utx=getUserTransaction();
try {
if (inTransaction(utx) && !rollbackonly) {
log.debug("committing transaction");
utx.commit();
} else {
log.debug("rolling back transaction");
utx.rollback();
}
} catch (Throwable t1) {
try {
log.warn("trying to roll back transaction after exception",t1);
utx.rollback();
} catch (Throwable t2) {
log.warn("exception rolling back transaction",t2);
}
}
}
} |
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.Objects;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ComboBoxModel<String> model = makeComboBoxModel();
JComboBox<String> combo = new JComboBox<>(model);
initComboBoxRenderer(combo);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(makeTitledPanel("Left Clip JComboBox", combo), BorderLayout.NORTH);
add(makeTitledPanel("Default JComboBox", new JComboBox<>(model)), BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
private static JButton getArrowButton(Container box) {
for (Component c: box.getComponents()) {
if (c instanceof JButton) { // && "ComboBox.arrowButton".equals(c.getName())) {
// System.out.println(c.getName());
return (JButton) c;
}
}
return null;
}
private static Component makeTitledPanel(String title, Component c) {
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createTitledBorder(title));
box.add(Box.createVerticalStrut(2));
box.add(c);
return box;
}
private static ComboBoxModel<String> makeComboBoxModel() {
DefaultComboBoxModel<String> m = new DefaultComboBoxModel<>();
m.addElement("1234567890123456789012/3456789012345678901234567890123/456789012345678901234567890.jpg");
m.addElement("aaaa.tif");
m.addElement("\\asdfsadfs\\afsdfasdf\\asdfasdfasd.avi");
m.addElement("aaaabbbcc.pdf");
m.addElement("c:/b12312343245/643667345624523451/324513/41234125/134513451345135125123412341bb1.mpg");
m.addElement("http://localhost/1234567890123456789012/3456789012345678901234567890123/456789012345678901234567890.jpg");
return m;
}
private static void initComboBoxRenderer(JComboBox<String> combo) {
JButton arrowButton = getArrowButton(combo);
combo.setRenderer(new DefaultListCellRenderer() {
@Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
String text = Objects.toString(value, "");
FontMetrics fm = getFontMetrics(getFont());
int width = getAvailableWidth(combo, index);
setText(getLeftClippedText(text, fm, width));
return this;
}
private int getAvailableWidth(JComboBox<String> combo, int index) {
int itb = 0;
int ilr = 0;
Insets insets = getInsets();
itb += insets.top + insets.bottom;
ilr += insets.left + insets.right;
insets = combo.getInsets();
itb += insets.top + insets.bottom;
ilr += insets.left + insets.right;
int availableWidth = combo.getWidth() - ilr;
if (index < 0) {
// @see BasicComboBoxUI#rectangleForCurrentValue
int buttonSize = combo.getHeight() - itb;
if (Objects.nonNull(arrowButton)) {
buttonSize = arrowButton.getWidth();
}
availableWidth -= buttonSize;
JTextField tf = (JTextField) combo.getEditor().getEditorComponent();
insets = tf.getMargin();
// availableWidth -= insets.left;
availableWidth -= insets.left + insets.right;
}
return availableWidth;
}
private String getLeftClippedText(String text, FontMetrics fm, int availableWidth) {
// @title Left Dot Renderer
// @auther Rob Camick
// FontMetrics fm = getFontMetrics(getFont());
// if (fm.stringWidth(text) > availableWidth) {
// String dots = "...";
// int textWidth = fm.stringWidth(dots);
// int nChars = text.length() - 1;
// while (nChars > 0) {
// textWidth += fm.charWidth(text.charAt(nChars));
// if (textWidth > availableWidth) {
// break;
// nChars--;
// setText(dots + text.substring(nChars + 1));
// </blockquote>
if (fm.stringWidth(text) <= availableWidth) {
return text;
}
String dots = "...";
int textWidth = fm.stringWidth(dots);
int len = text.length();
// @see Unicode surrogate programming with the Java language
int[] acp = new int[text.codePointCount(0, len)];
int j = acp.length;
for (int i = len; i > 0; i = text.offsetByCodePoints(i, -1)) {
int cp = text.codePointBefore(i);
textWidth += fm.charWidth(cp);
if (textWidth > availableWidth) {
break;
}
acp[--j] = cp;
}
return dots + new String(acp, j, acp.length - j);
}
});
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGui();
}
});
}
public static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
import java.awt.Dimension;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
import java.awt.Color;
public class GUI {
private ArrayList<Vehicle> availableVehicles = new ArrayList<Vehicle>(); // These variables need to be accessed from different methods...
private ArrayList<Accessory> accessories = new ArrayList<Accessory>();
private Vehicle selectedVehicle;
private String enteredDate;
public GUI() {
final Controller controller = new Controller(); // Initiates link with the controller!
final CardLayout cardLayout = new CardLayout(); // Sets current layout!
/* Creates the frame for the program which has the basic window features.*/
final JFrame frame = new JFrame("CARENTA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Creates a container that contains the panels. */
final Container contentPane = frame.getContentPane();
contentPane.setLayout(cardLayout);
contentPane.setPreferredSize(new Dimension(700, 650));
final JPanel mainPanel = new JPanel(); // Panel...
mainPanel.setLayout(null); // Standard layout...
contentPane.add(mainPanel, "mainPanel"); // Adds the panel mainPanel to the container where "customerPanel" identifies it!
JButton btnCustomer = new JButton("Kund"); // Buttons...
JButton btnOrder = new JButton("Order");
JButton btnVehicle = new JButton("Fordon");
JButton btnAccessory = new JButton("Tillbehör");
btnCustomer.setBounds(200, 100, 300, 75); // Set locations and set sizes...
btnOrder.setBounds(200, 225, 300, 75);
btnVehicle.setBounds(200, 350, 300, 75);
btnAccessory.setBounds(200, 475, 300, 75);
mainPanel.add(btnCustomer); // Add them to the panel...
mainPanel.add(btnOrder);
mainPanel.add(btnVehicle);
mainPanel.add(btnAccessory);
btnCustomer.addActionListener(new ActionListener() { // When clicked, switch to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
btnOrder.addActionListener(new ActionListener() { // When clicked, switch to orderPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "orderPanel");
}
});
btnVehicle.addActionListener(new ActionListener() { // When clicked, switch to vehiclePanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
btnAccessory.addActionListener(new ActionListener() { // When clicked, switch to accessoryPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
final JPanel customerPanel = new JPanel();
customerPanel.setLayout(null);
contentPane.add(customerPanel, "customerPanel");
JButton btnSearchCustomer = new JButton("Sök kund");
JButton btnNewCustomer = new JButton("Registrera kund");
JButton btnBackCustomer = new JButton("Tillbaka");
btnSearchCustomer.setBounds(200, 225, 300, 75);
btnNewCustomer.setBounds(200, 350, 300, 75);
btnBackCustomer.setBounds(10, 10, 150, 35);
customerPanel.add(btnSearchCustomer);
customerPanel.add(btnNewCustomer);
customerPanel.add(btnBackCustomer);
btnSearchCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerSearchPanel");
}
});
btnNewCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newCustomerPanel");
}
});
btnBackCustomer.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
final JPanel customerSearchPanel = new JPanel();
customerSearchPanel.setLayout(null);
contentPane.add(customerSearchPanel, "customerSearchPanel");
JButton btnSearchForCustomer = new JButton("Sök kund");
JButton btnBackSearchCustomer = new JButton("Tillbaka");
btnSearchForCustomer.setBounds(200, 475, 300, 75);
btnBackSearchCustomer.setBounds(10, 10, 150, 35);
customerSearchPanel.add(btnSearchForCustomer);
customerSearchPanel.add(btnBackSearchCustomer);
final JTextField txtEnterCustomerNbr; // Creates search field where you input the customer number...
txtEnterCustomerNbr = new JTextField();
txtEnterCustomerNbr.setText("");
txtEnterCustomerNbr.setBounds(200, 285, 300, 30);
customerSearchPanel.add(txtEnterCustomerNbr);
txtEnterCustomerNbr.setColumns(10);
txtEnterCustomerNbr.setOpaque(false);
JTextArea txtrCustomerNbr = new JTextArea();
txtrCustomerNbr.setBackground(SystemColor.menu);
txtrCustomerNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrCustomerNbr.setText("Kundnummer:");
txtrCustomerNbr.setBounds(103, 207, 100, 16);
customerSearchPanel.add(txtrCustomerNbr);
txtrCustomerNbr.setEditable(false); //Set the JTextArea uneditable.
final JTextField txtEnterPersonalNbr; // Creates search field where you input the personal number...
txtEnterPersonalNbr = new JTextField();
txtEnterPersonalNbr.setText("");
txtEnterPersonalNbr.setBounds(200, 200, 300, 30);
customerSearchPanel.add(txtEnterPersonalNbr);
txtEnterCustomerNbr.setColumns(10);
JTextArea txtrPersonalNbr = new JTextArea(); // Creates the text next to the search field.
txtrPersonalNbr.setEditable(false);
txtrPersonalNbr.setBackground(Color.WHITE);
txtrPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrPersonalNbr.setText("Personnummer:");
txtrPersonalNbr.setBounds(103, 292, 100, 16);
customerSearchPanel.add(txtrPersonalNbr);
/*final JTextPane paneCustomerResult = new JTextPane();
paneCustomerResult.setBounds(125, 50, 250, 275);
customerSearchPanel.add(paneCustomerResult);*/
btnSearchForCustomer.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
String enterdCustomerNbr = txtEnterCustomerNbr.getText(); // Get text from search field...
// String customerResult = controller.findCustomer(enterdCustomerNbr); // ... find the customer...
/* paneCustomerResult.setText(customerResult); // ... and print the text!*/
}
});
btnBackSearchCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
final JPanel newCustomerPanel = new JPanel();
contentPane.add(newCustomerPanel, "newCustomerPanel");
newCustomerPanel.setLayout(null);
JButton btnBackNewCustomer = new JButton("Tillbaka");
JButton btnRegisterNewCustomer = new JButton("Registrera kund");
btnBackNewCustomer.setBounds(10, 10, 150, 35);
btnRegisterNewCustomer.setBounds(200, 515, 300, 75);
newCustomerPanel.add(btnBackNewCustomer);
newCustomerPanel.add(btnRegisterNewCustomer);
JTextArea textPersonNbr = new JTextArea(); // Creates the text next to the input field.
textPersonNbr.setBackground(SystemColor.menu);
textPersonNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
textPersonNbr.setText("Personnummer:");
textPersonNbr.setBounds(90, 102, 113, 16);
newCustomerPanel.add(textPersonNbr);
textPersonNbr.setEditable(false);
JTextArea textFirstName = new JTextArea();
textFirstName.setText("Förnamn:");
textFirstName.setFont(new Font("Tahoma", Font.PLAIN, 13));
textFirstName.setEditable(false);
textFirstName.setBackground(Color.WHITE);
textFirstName.setBounds(90, 152, 113, 16);
newCustomerPanel.add(textFirstName);
JTextArea textLastName = new JTextArea();
textLastName.setText("Efternamn:");
textLastName.setFont(new Font("Tahoma", Font.PLAIN, 13));
textLastName.setEditable(false);
textLastName.setBackground(Color.WHITE);
textLastName.setBounds(90, 202, 113, 16);
newCustomerPanel.add(textLastName);
JTextArea textAdress = new JTextArea();
textAdress.setText("Adress:");
textAdress.setFont(new Font("Tahoma", Font.PLAIN, 13));
textAdress.setEditable(false);
textAdress.setBackground(Color.WHITE);
textAdress.setBounds(90, 252, 113, 16);
newCustomerPanel.add(textAdress);
JTextArea txtrCity = new JTextArea();
txtrCity.setText("Stad:");
txtrCity.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrCity.setEditable(false);
txtrCity.setBackground(Color.WHITE);
txtrCity.setBounds(90, 302, 113, 16);
newCustomerPanel.add(txtrCity);
JTextArea txtrAreaCode = new JTextArea();
txtrAreaCode.setText("Postkod:");
txtrAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAreaCode.setEditable(false);
txtrAreaCode.setBackground(Color.WHITE);
txtrAreaCode.setBounds(90, 352, 113, 16);
newCustomerPanel.add(txtrAreaCode);
JTextArea txtrTelephoneNbr = new JTextArea();
txtrTelephoneNbr.setText("Telefonnummer:");
txtrTelephoneNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrTelephoneNbr.setEditable(false);
txtrTelephoneNbr.setBackground(Color.WHITE);
txtrTelephoneNbr.setBounds(90, 402, 113, 16);
newCustomerPanel.add(txtrTelephoneNbr);
JTextArea txtrMail = new JTextArea();
txtrMail.setText("E-mail-adrress:");
txtrMail.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrMail.setEditable(false);
txtrMail.setBackground(Color.WHITE);
txtrMail.setBounds(90, 452, 113, 16);
newCustomerPanel.add(txtrMail);
final JTextField txtEnterPersonNbr; // Creates search fields where you input the information about the customer...
txtEnterPersonNbr = new JTextField();
txtEnterPersonNbr.setText("");
txtEnterPersonNbr.setBounds(200, 95, 300, 30);
newCustomerPanel.add(txtEnterPersonNbr);
txtEnterPersonNbr.setColumns(10);
final JTextField txtEnterFirstName;
txtEnterFirstName = new JTextField();
txtEnterFirstName.setText("");
txtEnterFirstName.setBounds(200, 145, 300, 30);
newCustomerPanel.add(txtEnterFirstName);
txtEnterFirstName.setColumns(10);
final JTextField txtEnterLastName;
txtEnterLastName= new JTextField();
txtEnterLastName.setText("");
txtEnterLastName.setBounds(200, 195, 300, 30);
newCustomerPanel.add(txtEnterLastName);
txtEnterLastName.setColumns(10);
final JTextField txtEnterAddress;
txtEnterAddress = new JTextField();
txtEnterAddress.setText("");
txtEnterAddress.setBounds(200, 245, 300, 30);
newCustomerPanel.add(txtEnterAddress);
txtEnterPersonNbr.setColumns(10);
final JTextField txtEnterCity;
txtEnterCity = new JTextField();
txtEnterCity.setText("");
txtEnterCity.setBounds(200, 295, 300, 30);
newCustomerPanel.add(txtEnterCity);
txtEnterCity.setColumns(10);
final JTextField txtEnterAreaCode;
txtEnterAreaCode = new JTextField();
txtEnterAreaCode.setText("");
txtEnterAreaCode.setBounds(200, 345, 300, 30);
newCustomerPanel.add(txtEnterAreaCode);
txtEnterAreaCode.setColumns(10);
final JTextField txtEnterTelephoneNbr;
txtEnterTelephoneNbr = new JTextField();
txtEnterTelephoneNbr.setText("");
txtEnterTelephoneNbr.setBounds(200, 395, 300, 30);
newCustomerPanel.add(txtEnterTelephoneNbr);
txtEnterTelephoneNbr.setColumns(10);
final JTextField txtEnterMail;
txtEnterMail = new JTextField();
txtEnterMail.setText("");
txtEnterMail.setBounds(200, 445, 300, 30);
newCustomerPanel.add(txtEnterMail);
txtEnterMail.setColumns(10);
btnBackNewCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
final JPanel orderPanel = new JPanel();
orderPanel.setLayout(null);
contentPane.add(orderPanel, "orderPanel");
JButton btnSearchOrder = new JButton("Sök order");
JButton btnNewOrder = new JButton("Registrera order");
JButton btnBackOrder = new JButton("Tillbaka");
btnSearchOrder.setBounds(200, 225, 300, 75);
btnNewOrder.setBounds(200, 350, 300, 75);
btnBackOrder.setBounds(10, 10, 150, 35);
orderPanel.add(btnSearchOrder);
orderPanel.add(btnNewOrder);
orderPanel.add(btnBackOrder);
btnNewOrder.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newOrderPanel");
}
});
btnSearchOrder.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "searchOrderPanel");
}
});
btnBackOrder.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
final JPanel searchOrderPanel = new JPanel();
searchOrderPanel.setLayout(null);
contentPane.add(searchOrderPanel, "searchOrderPanel");
final JButton btnSearchForOrder = new JButton("Sök order");
final JButton btnBackSearchOrder = new JButton("Tillbaka");
btnSearchForOrder.setBounds(200, 530, 300, 75);
btnBackSearchOrder.setBounds(10, 10, 150, 35);
searchOrderPanel.add(btnSearchForOrder);
searchOrderPanel.add(btnBackSearchOrder);
final JTextField txtEnteredOrder;
txtEnteredOrder = new JTextField();
txtEnteredOrder.setText("");
txtEnteredOrder.setBounds(200, 470, 300, 30);
searchOrderPanel.add(txtEnteredOrder);
txtEnteredOrder.setColumns(10);
String columnsSearchOrder[] = {"Order"};
final DefaultTableModel modelSearchOrder = new DefaultTableModel(columnsSearchOrder,0);
final JTable searchOrderTable = new JTable(modelSearchOrder);
searchOrderTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
searchOrderTable.setFillsViewportHeight(true);
searchOrderTable.setBounds(10, 50, 680, 380);
searchOrderPanel.add(searchOrderTable);
btnSearchForOrder.addActionListener(new ActionListener() { // When clicked, go to new order panel...
public void actionPerformed(ActionEvent e) {
int orderNbr = Integer.parseInt(txtEnteredOrder.getText());
Order order = controller.orderRegistry.getOrder(orderNbr);
modelSearchOrder.addRow(new Object[]{order.getOrderNbr()});
modelSearchOrder.addRow(new Object[]{order.getDiscount()});
modelSearchOrder.addRow(new Object[]{order.getTotalPrice()});
modelSearchOrder.addRow(new Object[]{order.getIsAppropriate()});
modelSearchOrder.addRow(new Object[]{order.getWasSatesfied()});
modelSearchOrder.addRow(new Object[]{order.getLatestUpdate()});
modelSearchOrder.addRow(new Object[]{order.getCustomer()}); // Add everything to the row and then add the row itself!
modelSearchOrder.addRow(new Object[]{order.getLatestUpdate()});
modelSearchOrder.addRow(new Object[]{order.getEmployee()});
modelSearchOrder.addRow(new Object[]{order.getVehicle()});
modelSearchOrder.addRow(new Object[]{order.getAccessories()});
}
});
btnBackSearchOrder.addActionListener(new ActionListener() { // When clicked, go to new order panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "orderPanel");
}
});
final JPanel newOrderPanel = new JPanel();
newOrderPanel.setLayout(null);
contentPane.add(newOrderPanel, "newOrderPanel");
final JButton btnEnteredDate = new JButton("Gå vidare");
final JButton btnChooseVehicle = new JButton("Välj bil");
final JButton btnChooseAccessory = new JButton("Gå vidare");
final JButton btnMoreAccessory = new JButton("Lägg till ytterligare tillbehör");
final JButton btnViewOrder = new JButton("Granska order");
final JButton btnConfirmOrder = new JButton("Slutför order");
final JButton btnBackNewOrder = new JButton("Tillbaka");
btnEnteredDate.setBounds(200, 540, 300, 75);
btnChooseVehicle.setBounds(200, 540, 300, 75);
btnChooseAccessory.setBounds(200, 540, 300, 75);
btnMoreAccessory.setBounds(250, 10, 200, 34);
btnViewOrder.setBounds(200, 540, 300, 75);
btnConfirmOrder.setBounds(200, 540, 300, 75);
btnBackNewOrder.setBounds(10, 10, 150, 35);
newOrderPanel.add(btnEnteredDate);
newOrderPanel.add(btnChooseVehicle);
newOrderPanel.add(btnChooseAccessory);
newOrderPanel.add(btnMoreAccessory);
newOrderPanel.add(btnViewOrder);
newOrderPanel.add(btnConfirmOrder);
newOrderPanel.add(btnBackNewOrder);
btnChooseVehicle.setVisible(false);
btnChooseAccessory.setVisible(false);
btnMoreAccessory.setVisible(false);
btnViewOrder.setVisible(false);
btnConfirmOrder.setVisible(false);
final JTextField txtEnteredDate; // Creates search field where you input text data...
txtEnteredDate = new JTextField();
txtEnteredDate.setText("");
txtEnteredDate.setBounds(200, 100, 300, 30);
newOrderPanel.add(txtEnteredDate);
txtEnteredDate.setColumns(10);
final JTextField txtEnteredCustomer;
txtEnteredCustomer = new JTextField();
txtEnteredCustomer.setText("");
txtEnteredCustomer.setBounds(200, 440, 300, 30);
newOrderPanel.add(txtEnteredCustomer);
txtEnteredCustomer.setColumns(10);
txtEnteredCustomer.setVisible(false);
final JComboBox warehouseSelection = new JComboBox(new String[]{"Lund", "Linköping", "Göteborg"}); // Creates a combobox with selections...
warehouseSelection.setBounds(200, 200, 300, 30);
newOrderPanel.add(warehouseSelection);
final JComboBox typeSelection = new JComboBox(new String[]{"Personbil", "Minibuss", "Lastbil", "Släpvagn"});
typeSelection.setBounds(200, 300, 300, 30);
newOrderPanel.add(typeSelection);
final JComboBox employeeSelection = new JComboBox(new String[]{"Jonas", "Malin", "Swante"});
employeeSelection.setBounds(200, 485, 300, 30);
newOrderPanel.add(employeeSelection);
employeeSelection.setVisible(false);
/* Creates tabular fields... */
String columnsVehicle[] = {"Modell", "Körkortskrav", "Pris", "Har krok"}; // Sets column names...
final DefaultTableModel modelVehicle = new DefaultTableModel(columnsVehicle,0); // Creates the default tabular model...
final JTable vehicleTable = new JTable(modelVehicle); // Creates a JTAble which will display available vehicles...
vehicleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
vehicleTable.setFillsViewportHeight(true);
vehicleTable.setBounds(10, 56, 680, 360);
newOrderPanel.add(vehicleTable);
vehicleTable.setVisible(false);
String columnsAccessory[] = {"Namn", "Information", "Pris", "Produktnummer"};
final DefaultTableModel modelAccessory = new DefaultTableModel(columnsAccessory,0);
final JTable accessoryTable = new JTable(modelAccessory);
accessoryTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
accessoryTable.setFillsViewportHeight(true);
accessoryTable.setBounds(10, 56, 680, 361);
newOrderPanel.add(accessoryTable);
accessoryTable.setVisible(false);
String columnsProducts[] = {"Namn", "Information", "Pris", "Övrigt"};
final DefaultTableModel modelProducts = new DefaultTableModel(columnsProducts,0);
final JTable productsTable = new JTable(modelProducts);
productsTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
productsTable.setFillsViewportHeight(true);
productsTable.setBounds(10, 56, 680, 361);
newOrderPanel.add(productsTable);
productsTable.setVisible(false);
btnEnteredDate.addActionListener(new ActionListener() { // When the date and other info has been entered (button clicked)...
public void actionPerformed(ActionEvent e) {
txtEnteredDate.setVisible(false); // Hides previous data forms...
warehouseSelection.setVisible(false);
typeSelection.setVisible(false);
btnEnteredDate.setVisible(false);
enteredDate = txtEnteredDate.getText(); // Retrieves data from the forms...
String selectedWarehouse = warehouseSelection.getSelectedItem().toString();
String selectedType = typeSelection.getSelectedItem().toString();
availableVehicles = controller.calculateVehicleAvailability(enteredDate, selectedWarehouse, selectedType); // Calculates vehicle availability with input data...
Vehicle vehicle;
String vehicleModel; // Creates temporary variables in which to store information when rendering vehicle information...
String licenseReq;
int price;
String hasHook;
for(int a = 0; a < availableVehicles.size(); a++) { // For each vehicle in the list...
vehicle = availableVehicles.get(a); // Print the information...
vehicleModel = vehicle.getModel();
licenseReq = vehicle.getLicenseReq();
price = vehicle.getPrice();
/* We need to print the hasHook-argument in a more sensible way which is why we do this... */
if(vehicle.hasHook()) {
hasHook = "Ja";
}
else hasHook = "Nej";
modelVehicle.addRow(new Object[]{vehicleModel, licenseReq, price, hasHook}); // Add everything to the row and then add the row itself!
}
vehicleTable.setVisible(true); // Show the new data forms!
btnChooseVehicle.setVisible(true);
}
});
btnChooseVehicle.addActionListener(new ActionListener() { // When the vehicle is chosen (button clicked) ...
public void actionPerformed(ActionEvent e) {
vehicleTable.setVisible(false);
btnChooseVehicle.setVisible(false);
int vehicleNumber = vehicleTable.getSelectedRow(); // Retrieve the vehicle in question...
selectedVehicle = availableVehicles.get(vehicleNumber); // Get it from the available vehicle list...
selectedVehicle.setBooked(enteredDate); // Set it as booked with the entered date!
Accessory accessory;
String name;
String info;
int price;
int accessoryNbr;
for(int a = 0; a < controller.accessoryRegistry.getAccessories().size(); a++) { // Generate available accessories...
accessory = controller.accessoryRegistry.getAccessory(a);
name = accessory.getName();
info = accessory.getInfo();
price = accessory.getPrice();
accessoryNbr = accessory.getProductNbr();
modelAccessory.addRow(new Object[]{name, info, price, accessoryNbr});
}
btnMoreAccessory.setVisible(true);
accessoryTable.setVisible(true);
btnViewOrder.setVisible(true);
}
});
btnMoreAccessory.addActionListener(new ActionListener() { // In order to add more accessories to the purchase...
public void actionPerformed(ActionEvent e) {
int accessoryNumber = accessoryTable.getSelectedRow(); // Get which accessory is selected...
Accessory accessory;
accessory = controller.accessoryRegistry.getAccessory(accessoryNumber); // Retrieve the accessory...
accessories.add(accessory); // Add it to the current list!
}
});
btnViewOrder.addActionListener(new ActionListener() { // When clicked, let's see the whole order...
public void actionPerformed(ActionEvent e) {
btnMoreAccessory.setVisible(false);
accessoryTable.setVisible(false);
btnViewOrder.setVisible(false);
modelProducts.addRow(new Object[]{selectedVehicle.getModel(), selectedVehicle.getLicenseReq(), selectedVehicle.getPrice(), selectedVehicle.hasHook()}); // Add the vehicle to the display table...
Accessory accessory = null;
String name = null;
String info = null;
int price = 0;
int accessoryNbr = 0;
for(int a = 0; a < accessories.size(); a++) { // Add the accessories to the display table...
accessory = accessories.get(a);
name = accessory.getName();
info = accessory.getInfo();
price = accessory.getPrice();
accessoryNbr = accessory.getProductNbr();
modelProducts.addRow(new Object[]{name, info, price, accessoryNbr});
}
productsTable.setVisible(true);
txtEnteredCustomer.setVisible(true);
employeeSelection.setVisible(true);
btnConfirmOrder.setVisible(true);
}
});
btnConfirmOrder.addActionListener(new ActionListener() { // When clicked, create the order!
public void actionPerformed(ActionEvent e) {
productsTable.setVisible(false);
btnConfirmOrder.setVisible(false);
employeeSelection.setVisible(false);
txtEnteredCustomer.setVisible(false);
int customerNbr = Integer.parseInt(txtEnteredCustomer.getText()); // Retrieve more data...
Customer customer = controller.customerRegistry.getCustomer(customerNbr);
String employeeName = employeeSelection.getSelectedItem().toString();
Employee employee;
Employee selectedEmployee = null;
for(int a = 0; a < controller.employeeRegistry.getEmployees().size(); a++) { // Find the employee...
employee = controller.employeeRegistry.getEmployee(a);
if(employeeName.equals(employee.getFirstName())) {
selectedEmployee = employee;
}
}
controller.createOrder(customer, selectedVehicle, accessories, selectedEmployee, enteredDate); // Call the controller and create the order...
txtEnteredDate.setText(""); // Reset what's supposed to show for the next order input...
txtEnteredDate.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
enteredDate = null; // Reset data...
availableVehicles = null;
selectedVehicle = null;
accessories.clear();
modelVehicle.setRowCount(0); // Clear tables!
modelAccessory.setRowCount(0);
modelProducts.setRowCount(0);
cardLayout.show(contentPane, "orderPanel"); // ... and return to the order menu!
JOptionPane.showMessageDialog(null, "Ordern är utförd!"); // Tell the user that the order has been confirmed!
}
});
btnBackNewOrder.addActionListener(new ActionListener() { // When clicked, go back to order panel and...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "orderPanel");
txtEnteredDate.setText(""); // RESET ALL DATA to prevent stupid data problems, if you fail at making an order you'll have to re-do it!
txtEnteredDate.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
vehicleTable.setVisible(false);
accessoryTable.setVisible(false);
productsTable.setVisible(false);
txtEnteredCustomer.setVisible(false);
employeeSelection.setVisible(false);
btnMoreAccessory.setVisible(false);
btnChooseAccessory.setVisible(false);
btnChooseVehicle.setVisible(false);
btnConfirmOrder.setVisible(false);
DefaultTableModel modelVehicle = (DefaultTableModel) vehicleTable.getModel();
modelVehicle.setRowCount(0);
DefaultTableModel modelAccessory = (DefaultTableModel) accessoryTable.getModel();
modelAccessory.setRowCount(0);
DefaultTableModel modelProducts = (DefaultTableModel) vehicleTable.getModel();
modelProducts.setRowCount(0);
enteredDate = null;
selectedVehicle = null;
availableVehicles = null;
accessories.clear();
}
});
final JPanel vehiclePanel = new JPanel();
vehiclePanel.setLayout(null);
contentPane.add(vehiclePanel, "vehiclePanel");
JButton btnSearchVehicle = new JButton("Sök fordon");
JButton btnNewVehicle = new JButton("Registrera fordon");
JButton btnBackVehicle = new JButton("Tillbaka");
btnSearchVehicle.setBounds(200, 225, 300, 75);
btnNewVehicle.setBounds(200, 350, 300, 75);
btnBackVehicle.setBounds(10, 10, 150, 35);
vehiclePanel.add(btnSearchVehicle);
vehiclePanel.add(btnNewVehicle);
vehiclePanel.add(btnBackVehicle);
btnBackVehicle.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
final JPanel accessoryPanel = new JPanel();
accessoryPanel.setLayout(null);
contentPane.add(accessoryPanel, "accessoryPanel");
JButton btnSearchAccessory = new JButton("Sök tillbehör");
JButton btnNewAccessory = new JButton("Registrera tillbehör");
JButton btnBackAccessory = new JButton("Tillbaka");
btnSearchAccessory.setBounds(200, 225, 300, 75);
btnNewAccessory.setBounds(200, 350, 300, 75);
btnBackAccessory.setBounds(10, 10, 150, 35);
accessoryPanel.add(btnSearchAccessory);
accessoryPanel.add(btnNewAccessory);
accessoryPanel.add(btnBackAccessory);
btnBackAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchAccessory.addActionListener(new ActionListener() { // When clicked, go to accessorySearchPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessorySearchPanel");
}
});
btnNewAccessory.addActionListener(new ActionListener() { // When clicked, go to registerNewAccessoryPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewAccessoryPanel");
}
});
final JPanel accessoryPanel = new JPanel();
accessoryPanel.setLayout(null);
contentPane.add(accessoryPanel, "accessoryPanel");
JButton btnSearchAccessory = new JButton("Sök tillbehör");
JButton btnNewAccessory = new JButton("Registrera tillbehör");
JButton btnBackAccessory = new JButton("Tillbaka");
btnSearchAccessory.setBounds(200, 225, 300, 75);
btnNewAccessory.setBounds(200, 350, 300, 75);
btnBackAccessory.setBounds(10, 10, 150, 35);
accessoryPanel.add(btnSearchAccessory);
accessoryPanel.add(btnNewAccessory);
accessoryPanel.add(btnBackAccessory);
btnBackAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchAccessory.addActionListener(new ActionListener() { // When clicked, go to accessorySearchPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessorySearchPanel");
}
});
btnNewAccessory.addActionListener(new ActionListener() { // When clicked, go to registerNewAccessoryPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewAccessoryPanel");
}
});
final JPanel accessorySearchPanel = new JPanel();
accessorySearchPanel.setLayout(null);
contentPane.add(accessorySearchPanel, "accessorySearchPanel");
JButton btnSearchForAccessory = new JButton("Sök tillbehör");
JButton btnBackSearchAccessory = new JButton("Tillbaka");
btnBackSearchAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
btnSearchForAccessory.setBounds(200, 475, 300, 75);
btnBackSearchAccessory.setBounds(10, 10, 150, 35);
accessorySearchPanel.add(btnSearchForAccessory);
accessorySearchPanel.add(btnBackSearchAccessory);
final JTextField txtEnterProductNbr; // Creates search field where you input the product number...
txtEnterProductNbr = new JTextField();
txtEnterProductNbr.setText("");
txtEnterProductNbr.setBounds(200, 420, 300, 30);
accessorySearchPanel.add(txtEnterProductNbr);
txtEnterProductNbr.setColumns(10);
final JTextPane paneAccessoryResult = new JTextPane();
paneAccessoryResult.setBounds(158, 55, 400, 335);
accessorySearchPanel.add(paneAccessoryResult);
JTextPane textPane = new JTextPane();
textPane.setBounds(123, 364, -99, -11);
accessorySearchPanel.add(textPane);
JButton btnChangeAccessory = new JButton("Ändra tillbehör");
btnChangeAccessory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnChangeAccessory.setBounds(200, 569, 300, 75);
accessorySearchPanel.add(btnChangeAccessory);
btnSearchForAccessory.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
int enterdProductNbr = Integer.parseInt(txtEnterProductNbr.getText()); // Get text from search field...
String accessoryResult = controller.findAccessory(enterdProductNbr); // ... find the accessory...
paneAccessoryResult.setText(accessoryResult); // ... and print the text
}
});
final JPanel registerNewAccessoryPanel = new JPanel();
contentPane.add(registerNewAccessoryPanel, "registerNewAccessoryPanel");
registerNewAccessoryPanel.setLayout(null);
JButton btnBackRegisterNewAccessory = new JButton("Tillbaka");
JButton btnRegisterNewAccessory = new JButton("Registrera tillbehör");
btnBackRegisterNewAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
btnBackRegisterNewAccessory.setBounds(10, 10, 150, 35);
btnRegisterNewAccessory.setBounds(200, 485, 300, 75);
registerNewAccessoryPanel.add(btnBackRegisterNewAccessory);
registerNewAccessoryPanel.add(btnRegisterNewAccessory);
final JTextField txtEnterAccessoryName; // Creates search field where you input the information about the customer...
txtEnterAccessoryName = new JTextField();
txtEnterAccessoryName.setText("");
txtEnterAccessoryName.setBounds(225, 74, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryName);
txtEnterAccessoryName.setColumns(10);
JTextArea txtrAccessoryName = new JTextArea();
txtrAccessoryName.setEditable(false);
txtrAccessoryName.setBackground(SystemColor.window);
txtrAccessoryName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryName.setText("Namn");
txtrAccessoryName.setBounds(130, 81, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryName);
final JTextField txtEnterAccessoryProductNbr; // Creates search field where you input the information about the customer...
txtEnterAccessoryProductNbr = new JTextField();
txtEnterAccessoryProductNbr.setText("");
txtEnterAccessoryProductNbr.setBounds(225, 144, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryProductNbr);
txtEnterAccessoryProductNbr.setColumns(10);
JTextArea txtrAccessoryProductNbr = new JTextArea();
txtrAccessoryProductNbr.setEditable(false);
txtrAccessoryProductNbr.setBackground(SystemColor.window);
txtrAccessoryProductNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryProductNbr.setText("Produktnummer");
txtrAccessoryProductNbr.setBounds(130, 151, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryProductNbr);
final JTextField txtEnterNewAccessoryPrice; // Creates search field where you input the information about the customer...
txtEnterNewAccessoryPrice= new JTextField();
txtEnterNewAccessoryPrice.setText("");
txtEnterNewAccessoryPrice.setBounds(225, 210, 250, 30);
registerNewAccessoryPanel.add(txtEnterNewAccessoryPrice);
txtEnterNewAccessoryPrice.setColumns(10);
JTextArea txtrNewAccessoryPrice = new JTextArea(); // Creates the text next to the input field.
txtrNewAccessoryPrice.setEditable(false);
txtrNewAccessoryPrice.setBackground(SystemColor.window);
txtrNewAccessoryPrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewAccessoryPrice.setText("Pris");
txtrNewAccessoryPrice.setBounds(130, 217, 100, 27);
registerNewAccessoryPanel.add(txtrNewAccessoryPrice);
final JTextField txtEnterAccessoryInfo; // Creates search field where you input the information about the customer...
txtEnterAccessoryInfo = new JTextField();
txtEnterAccessoryInfo.setText("");
txtEnterAccessoryInfo.setBounds(225, 276, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryInfo);
txtEnterAccessoryInfo.setColumns(10);
JTextArea txtrAccessoryInfo = new JTextArea(); // Creates the text next to the input field.
txtrAccessoryInfo.setEditable(false);
txtrAccessoryInfo.setBackground(SystemColor.window);
txtrAccessoryInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryInfo.setText("Beskrivning");
txtrAccessoryInfo.setBounds(130, 283, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryInfo);
/*Standard frame settings. */
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
} |
package edu.umd.cs.findbugs;
/**
* A BugCode is an abbreviation that is shared among some number
* of BugPatterns. For example, the code "HE" is shared by
* all of the BugPatterns that represent hashcode/equals
* violations.
*
* @author David Hovemeyer
* @see BugPattern
*/
public class BugCode {
private final String abbrev;
private final String description;
/**
* Constructor.
*
* @param abbrev the abbreviation for the bug code
* @param description a short textual description of the class of bug pattern
* represented by this bug code
*/
public BugCode(String abbrev, String description) {
this.abbrev = abbrev;
this.description = description;
}
/**
* Get the abbreviation for this bug code.
*/
public String getAbbrev() {
return abbrev;
}
/**
* Get the short textual description of the bug code.
*/
public String getDescription() {
return description;
}
/**
* Get the abbreviation fo this bug code.
*/
public String toString() {
return "BugCode[" + abbrev + "]";
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 1;
/**
* Minor version number.
*/
public static final int MINOR = 1;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 3;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number.
* "0" indicates that the version is not a release candidate.
*/
public static final int RELEASE_CANDIDATE = 3;
/**
* Preview release number.
* "0" indicates that the version is not a preview release.
*/
public static final int PREVIEW = 0;
private static final String RELEASE_SUFFIX_WORD =
(RELEASE_CANDIDATE > 0
? "rc" + RELEASE_CANDIDATE
: (PREVIEW > 0 ? "preview" + PREVIEW : "dev"));
/**
* Release version string.
*/
public static final String RELEASE =
MAJOR + "." + MINOR + "." + PATCHLEVEL + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy");
static final SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd");
/**
* Release date.
*/
public static final String DATE = dateFormat.format(new Date());
public static final String ECLIPSE_DATE = eclipseDateFormat.format(new Date()) ;
/**
* Version of Eclipse plugin.
*/
public static final String ECLIPSE_UI_VERSION = // same as RELEASE except .vYYYYMMDD before optional -suffix
MAJOR + "." + MINOR + "." + PATCHLEVEL + "." + ECLIPSE_DATE;
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number=" + RELEASE);
System.out.println("release.date=" + DATE);
System.out.println("eclipse.ui.version=" + ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
}
}
// vim:ts=4 |
public class BooleanReturnsNull {
public Boolean always_null(){
return null;
}
public Boolean sometimes_null(int n){
if (n > 3){
return new Boolean(true);
}
else if(n < 1){
return new Boolean(false);
}
else {
return null;
}
}
public Boolean never_null(int n){
if (n>2){
return new Boolean(true);
}
else{
return new Boolean(false);
}
}
public static void main(String[] args){
//nothing!!
}
} |
//FILE: AcqControlDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS: $Id$
package org.micromanager;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.metadata.MMAcqDataException;
import org.micromanager.metadata.WellAcquisitionData;
import org.micromanager.utils.ChannelSpec;
import org.micromanager.utils.ColorEditor;
import org.micromanager.utils.ColorRenderer;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.DisplayMode;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.MMException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.PositionMode;
import org.micromanager.utils.SliceMode;
import com.swtdesigner.SwingResourceManager;
import org.micromanager.acquisition.ComponentTitledBorder;
import org.micromanager.utils.ReportingUtils;
/**
* Time-lapse, channel and z-stack acquisition setup dialog.
* This dialog specifies all parameters for the Image5D acquisition.
*
*/
public class AcqControlDlg extends JDialog implements PropertyChangeListener {
private static final long serialVersionUID = 1L;
protected JButton listButton_;
private JButton afButton_;
private JSpinner afSkipInterval_;
private JComboBox sliceModeCombo_;
protected JComboBox posModeCombo_;
public static final String NEW_ACQFILE_NAME = "MMAcquistion.xml";
public static final String ACQ_SETTINGS_NODE = "AcquistionSettings";
public static final String COLOR_SETTINGS_NODE = "ColorSettings";
private JComboBox channelGroupCombo_;
private JTextArea commentTextArea_;
private JComboBox zValCombo_;
private JTextField nameField_;
private JTextField rootField_;
private JTextArea summaryTextArea_;
private JComboBox timeUnitCombo_;
private JFormattedTextField interval_;
private JFormattedTextField zStep_;
private JFormattedTextField zTop_;
private JFormattedTextField zBottom_;
private AcquisitionEngine acqEng_;
private JScrollPane channelTablePane_;
private JTable channelTable_;
private JSpinner numFrames_;
private ChannelTableModel model_;
private Preferences prefs_;
private Preferences acqPrefs_;
private Preferences colorPrefs_;
private File acqFile_;
private String acqDir_;
private int zVals_ = 0;
private JButton setBottomButton_;
private JButton setTopButton_;
protected JComboBox displayModeCombo_;
private DeviceControlGUI gui_;
private GUIColors guiColors_;
private NumberFormat numberFormat_;
private JLabel namePrefixLabel_;
private JLabel rootLabel_;
private JLabel commentLabel_;
private JButton browseRootButton_;
private JLabel displayMode_;
private JCheckBox stackKeepShutterOpenCheckBox_;
private JCheckBox chanKeepShutterOpenCheckBox_;
// persistent properties (app settings)
private static final String ACQ_CONTROL_X = "acq_x";
private static final String ACQ_CONTROL_Y = "acq_y";
private static final String ACQ_FILE_DIR = "dir";
private static final String ACQ_INTERVAL = "acqInterval";
private static final String ACQ_TIME_UNIT = "acqTimeInit";
private static final String ACQ_ZBOTTOM = "acqZbottom";
private static final String ACQ_ZTOP = "acqZtop";
private static final String ACQ_ZSTEP = "acqZstep";
private static final String ACQ_ENABLE_SLICE_SETTINGS = "enableSliceSettings";
private static final String ACQ_ENABLE_MULTI_POSITION = "enableMultiPosition";
private static final String ACQ_ENABLE_MULTI_FRAME = "enableMultiFrame";
private static final String ACQ_ENABLE_MULTI_CHANNEL = "enableMultiChannels";
private static final String ACQ_SLICE_MODE = "sliceMode";
private static final String ACQ_POSITION_MODE = "positionMode";
private static final String ACQ_NUMFRAMES = "acqNumframes";
private static final String ACQ_CHANNEL_GROUP = "acqChannelGroup";
private static final String ACQ_NUM_CHANNELS = "acqNumchannels";
private static final String ACQ_CHANNELS_KEEP_SHUTTER_OPEN = "acqChannelsKeepShutterOpen";
private static final String ACQ_STACK_KEEP_SHUTTER_OPEN = "acqStackKeepShutterOpen";
private static final String CHANNEL_NAME_PREFIX = "acqChannelName";
private static final String CHANNEL_EXPOSURE_PREFIX = "acqChannelExp";
private static final String CHANNEL_ZOFFSET_PREFIX = "acqChannelZOffset";
private static final String CHANNEL_DOZSTACK_PREFIX = "acqChannelDoZStack";
private static final String CHANNEL_CONTRAST8_MIN_PREFIX = "acqChannel8ContrastMin";
private static final String CHANNEL_CONTRAST8_MAX_PREFIX = "acqChannel8ContrastMax";
private static final String CHANNEL_CONTRAST16_MIN_PREFIX = "acqChannel16ContrastMin";
private static final String CHANNEL_CONTRAST16_MAX_PREFIX = "acqChannel16ContrastMax";
private static final String CHANNEL_COLOR_R_PREFIX = "acqChannelColorR";
private static final String CHANNEL_COLOR_G_PREFIX = "acqChannelColorG";
private static final String CHANNEL_COLOR_B_PREFIX = "acqChannelColorB";
private static final String CHANNEL_SKIP_PREFIX = "acqSkip";
private static final String ACQ_Z_VALUES = "acqZValues";
private static final String ACQ_DIR_NAME = "acqDirName";
private static final String ACQ_ROOT_NAME = "acqRootName";
private static final String ACQ_SAVE_FILES = "acqSaveFiles";
private static final String ACQ_DISPLAY_MODE = "acqDisplayMode";
private static final String ACQ_AF_ENABLE = "autofocus_enabled";
private static final String ACQ_AF_SKIP_INTERVAL = "autofocusSkipInterval";
private static final String ACQ_COLUMN_WIDTH = "column_width";
private static final String ACQ_COLUMN_ORDER = "column_order";
private static final int ACQ_DEFAULT_COLUMN_WIDTH = 77;
private int columnWidth_[];
private int columnOrder_[];
private CheckBoxPanel framesPanel_;
private CheckBoxPanel channelsPanel_;
private CheckBoxPanel slicesPanel_;
protected CheckBoxPanel positionsPanel_;
private JPanel acquisitionOrderPanel_;
private CheckBoxPanel afPanel_;
private JPanel summaryPanel_;
private CheckBoxPanel savePanel_;
private Border dayBorder_;
private Border nightBorder_;
private Vector<JPanel> panelList_;
private boolean disableGUItoSettings_ = false;
/**
* File filter class for Open/Save file choosers
*/
private class AcqFileFilter extends FileFilter {
final private String EXT_BSH;
final private String DESCRIPTION;
public AcqFileFilter() {
super();
EXT_BSH = new String("xml");
DESCRIPTION = new String("XML files (*.xml)");
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
if (EXT_BSH.equals(getExtension(f))) {
return true;
}
return false;
}
public String getDescription() {
return DESCRIPTION;
}
private String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
}
/**
* Data representation class for the channels list
*/
public class ChannelTableModel extends AbstractTableModel implements TableModelListener {
private static final long serialVersionUID = 3290621191844925827L;
private ArrayList<ChannelSpec> channels_;
private AcquisitionEngine acqEng_;
public final String[] COLUMN_NAMES = new String[]{
"Configuration",
"Exposure",
"Z-offset",
"Z-stack",
"Skip Fr.",
"Color"
};
public ChannelTableModel(AcquisitionEngine eng) {
acqEng_ = eng;
addTableModelListener(this);
}
public int getRowCount() {
if (channels_ == null) {
return 0;
} else {
return channels_.size();
}
}
public int getColumnCount() {
return COLUMN_NAMES.length;
}
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (channels_ != null && rowIndex < channels_.size()) {
if (columnIndex == 0) {
return channels_.get(rowIndex).config_;
} else if (columnIndex == 1) {
return new Double(channels_.get(rowIndex).exposure_);
} else if (columnIndex == 2) {
return new Double(channels_.get(rowIndex).zOffset_);
} else if (columnIndex == 3) {
return new Boolean(channels_.get(rowIndex).doZStack_);
} else if (columnIndex == 4) {
return new Integer(channels_.get(rowIndex).skipFactorFrame_);
} else if (columnIndex == 5) {
return channels_.get(rowIndex).color_;
}
}
return null;
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public void setValueAt(Object value, int row, int col) {
if (row >= channels_.size() || value == null) {
return;
}
ChannelSpec channel = channels_.get(row);
if (col == 0) {
channel.config_ = value.toString();
} else if (col == 1) {
channel.exposure_ = ((Double) value).doubleValue();
} else if (col == 2) {
channel.zOffset_ = ((Double) value).doubleValue();
} else if (col == 3) {
channel.doZStack_ = (Boolean) value;
} else if (col == 4) {
channel.skipFactorFrame_ = ((Integer) value).intValue();
} else if (col == 5) {
channel.color_ = (Color) value;
}
acqEng_.setChannel(row, channel);
repaint();
}
public boolean isCellEditable(int nRow, int nCol) {
if (nCol == 3) {
if (!acqEng_.isZSliceSettingEnabled()) {
return false;
}
}
return true;
}
/*
* Catched events thrown by the ColorEditor
* Will write the new color into the Color Prefs
*/
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
if (row < 0) {
return;
}
int col = e.getColumn();
if (col < 0) {
return;
}
ChannelSpec channel = channels_.get(row);
TableModel model = (TableModel) e.getSource();
if (col == 5) {
Color color = (Color) model.getValueAt(row, col);
colorPrefs_.putInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, color.getRGB());
}
}
public void setChannels(ArrayList<ChannelSpec> ch) {
channels_ = ch;
}
public ArrayList<ChannelSpec> getChannels() {
return channels_;
}
public void addNewChannel() {
ChannelSpec channel = new ChannelSpec();
channel.config_ = "";
if (acqEng_.getChannelConfigs().length > 0) {
for (String config : acqEng_.getChannelConfigs()) {
boolean unique = true;
for (ChannelSpec chan:channels_) {
if (config.contentEquals(chan.config_))
unique = false;
}
if (unique) {
channel.config_ = config;
break;
}
}
if (channel.config_.length() == 0) {
ReportingUtils.showMessage("No more channels are available\nin this channel group.");
} else {
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
channels_.add(channel);
}
}
}
public void removeChannel(int chIndex) {
if (chIndex >= 0 && chIndex < channels_.size()) {
channels_.remove(chIndex);
}
}
public int rowDown(int rowIdx) {
if (rowIdx >= 0 && rowIdx < channels_.size() - 1) {
ChannelSpec channel = channels_.get(rowIdx);
channels_.remove(rowIdx);
channels_.add(rowIdx + 1, channel);
return rowIdx + 1;
}
return rowIdx;
}
public int rowUp(int rowIdx) {
if (rowIdx >= 1 && rowIdx < channels_.size()) {
ChannelSpec channel = channels_.get(rowIdx);
channels_.remove(rowIdx);
channels_.add(rowIdx - 1, channel);
return rowIdx - 1;
}
return rowIdx;
}
public String[] getAvailableChannels() {
return acqEng_.getChannelConfigs();
}
/**
* Remove all channels from the list which are not compatible with
* the current acquisition settings
*/
public void cleanUpConfigurationList() {
String config;
for (Iterator<ChannelSpec> it = channels_.iterator(); it.hasNext();) {
config = it.next().config_;
if (!config.contentEquals("") && !acqEng_.isConfigAvailable(config)) {
it.remove();
}
}
fireTableStructureChanged();
}
/**
* reports if the same channel name is used twice
*/
public boolean duplicateChannels() {
for (int i = 0; i < channels_.size() - 1; i++) {
for (int j = i + 1; j < channels_.size(); j++) {
if (channels_.get(i).config_.equals(channels_.get(j).config_)) {
return true;
}
}
}
return false;
}
}
/**
* Cell editing using either JTextField or JComboBox depending on whether the
* property enforces a set of allowed values.
*/
public class ChannelCellEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = -8374637422965302637L;
JTextField text_ = new JTextField();
JComboBox combo_ = new JComboBox();
JCheckBox checkBox_ = new JCheckBox();
JLabel colorLabel_ = new JLabel();
int editCol_ = -1;
int editRow_ = -1;
ChannelSpec channel_ = null;
// This method is called when a cell value is edited by the user.
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int colIndex) {
if (isSelected) {
// cell (and perhaps other cells) are selected
}
ChannelTableModel model = (ChannelTableModel) table.getModel();
ArrayList<ChannelSpec> channels = model.getChannels();
final ChannelSpec channel = channels.get(rowIndex);
channel_ = channel;
colIndex = table.convertColumnIndexToModel(colIndex);
// Configure the component with the specified value
editRow_ = rowIndex;
editCol_ = colIndex;
if (colIndex == 1 || colIndex == 2) {
// exposure and z offset
text_.setText(((Double) value).toString());
return text_;
} else if (colIndex == 3) {
checkBox_.setSelected((Boolean) value);
return checkBox_;
} else if (colIndex == 4) {
// skip
text_.setText(((Integer) value).toString());
return text_;
} else if (colIndex == 0) {
// channel
combo_.removeAllItems();
// remove old listeners
ActionListener[] l = combo_.getActionListeners();
for (int i = 0; i < l.length; i++) {
combo_.removeActionListener(l[i]);
}
combo_.removeAllItems();
String configs[] = model.getAvailableChannels();
for (int i = 0; i < configs.length; i++) {
combo_.addItem(configs[i]);
}
combo_.setSelectedItem(channel.config_);
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
// end editing on selection change
combo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
fireEditingStopped();
}
});
// Return the configured component
return combo_;
} else {
// ColorEditor takes care of this
return colorLabel_;
}
}
// This method is called when editing is completed.
// It must return the new value to be stored in the cell.
public Object getCellEditorValue() {
// TODO: if content of column does not match type we get an exception
try {
if (editCol_ == 0) {
// As a side effect, change to the color of the new channel
channel_.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + combo_.getSelectedItem(), Color.white.getRGB()));
return combo_.getSelectedItem();
} else if (editCol_ == 1 || editCol_ == 2) {
return new Double(NumberUtils.displayStringToDouble(text_.getText()));
} else if (editCol_ == 3) {
return new Boolean(checkBox_.isSelected());
} else if (editCol_ == 4) {
return new Integer(NumberUtils.displayStringToInt(text_.getText()));
} else if (editCol_ == 5) {
Color c = colorLabel_.getBackground();
return c;
} else {
String err = new String("Internal error: unknown column");
return err;
}
} catch (ParseException p) {
ReportingUtils.showError(p);
}
String err = new String("Internal error: unknown column");
return err;
}
}
/**
* Renderer class for the channel table.
*/
public class ChannelCellRenderer extends JLabel implements TableCellRenderer {
private static final long serialVersionUID = -4328340719459382679L;
private AcquisitionEngine acqEng_;
// This method is called each time a cell in a column
// using this renderer needs to be rendered.
public ChannelCellRenderer(AcquisitionEngine acqEng) {
super();
acqEng_ = acqEng;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int colIndex) {
this.setEnabled(table.isEnabled());
ChannelTableModel model = (ChannelTableModel) table.getModel();
ArrayList<ChannelSpec> channels = model.getChannels();
ChannelSpec channel = channels.get(rowIndex);
if (hasFocus) {
// this cell is the anchor and the table has the focus
}
colIndex = table.convertColumnIndexToModel(colIndex);
setOpaque(false);
if (colIndex == 0) {
setText(channel.config_);
} else if (colIndex == 1) {
setText(NumberUtils.doubleToDisplayString(channel.exposure_));
} else if (colIndex == 2) {
setText(NumberUtils.doubleToDisplayString(channel.zOffset_));
} else if (colIndex == 3) {
JCheckBox check = new JCheckBox("", channel.doZStack_);
check.setEnabled(acqEng_.isZSliceSettingEnabled() && table.isEnabled());
if (isSelected) {
check.setBackground(table.getSelectionBackground());
check.setOpaque(true);
} else {
check.setOpaque(false);
check.setBackground(table.getBackground());
}
return check;
} else if (colIndex == 4) {
setText(Integer.toString(channel.skipFactorFrame_));
} else if (colIndex == 5) {
setText("");
setBackground(channel.color_);
setOpaque(true);
}
if (isSelected) {
setBackground(table.getSelectionBackground());
setOpaque(true);
} else {
setOpaque(false);
setBackground(table.getBackground());
}
// Since the renderer is a component, return itself
return this;
}
// The following methods override the defaults for performance reasons
public void validate() {
}
public void revalidate() {
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
}
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
}
}
public void createChannelTable() {
channelTable_ = new JTable();
channelTable_.setFont(new Font("Dialog", Font.PLAIN, 10));
channelTable_.setAutoCreateColumnsFromModel(false);
model_ = new ChannelTableModel(acqEng_);
channelTable_.setModel(model_);
model_.setChannels(acqEng_.getChannels());
ChannelCellEditor cellEditor = new ChannelCellEditor();
ChannelCellRenderer cellRenderer = new ChannelCellRenderer(acqEng_);
channelTable_.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int k = 0; k < model_.getColumnCount(); k++) {
int colIndex = search(columnOrder_, k);
if (colIndex < 0) {
colIndex = k;
}
if (colIndex == model_.getColumnCount() - 1) {
ColorRenderer cr = new ColorRenderer(true);
ColorEditor ce = new ColorEditor(model_, model_.getColumnCount() - 1);
TableColumn column = new TableColumn(model_.getColumnCount() - 1, 200, cr, ce);
column.setPreferredWidth(columnWidth_[model_.getColumnCount() - 1]);
channelTable_.addColumn(column);
} else {
TableColumn column = new TableColumn(colIndex, 200, cellRenderer, cellEditor);
column.setPreferredWidth(columnWidth_[colIndex]);
channelTable_.addColumn(column);
}
}
channelTablePane_.setViewportView(channelTable_);
}
public JPanel createPanel(String text, int left, int top, int right, int bottom) {
return createPanel(text, left, top, right, bottom, false);
}
public JPanel createPanel(String text, int left, int top, int right, int bottom, boolean checkBox) {
ComponentTitledPanel thePanel;
if (checkBox) {
thePanel = new CheckBoxPanel(text);
} else {
thePanel = new LabelPanel(text);
}
thePanel.setTitleFont(new Font("Dialog",Font.BOLD,12));
panelList_.add(thePanel);
thePanel.setBounds(left, top, right - left, bottom - top);
dayBorder_ = BorderFactory.createEtchedBorder();
nightBorder_ = BorderFactory.createEtchedBorder(Color.gray, Color.darkGray);
//updatePanelBorder(thePanel);
thePanel.setLayout(null);
getContentPane().add(thePanel);
return thePanel;
}
public void updatePanelBorder(JPanel thePanel) {
TitledBorder border = (TitledBorder) thePanel.getBorder();
if (gui_.getBackgroundStyle().contentEquals("Day")) {
border.setBorder(dayBorder_);
} else {
border.setBorder(nightBorder_);
}
}
public void createEmptyPanels() {
panelList_ = new Vector<JPanel>();
framesPanel_ = (CheckBoxPanel) createPanel("Time points", 5, 5, 220, 91, true); // (text, left, top, right, bottom)
positionsPanel_ = (CheckBoxPanel) createPanel("Multiple positions (XY)", 5, 93, 220, 154, true);
slicesPanel_ = (CheckBoxPanel) createPanel("Z-stacks (slices)", 5, 156, 220, 306, true);
acquisitionOrderPanel_ = createPanel("Acquisition order", 226, 5, 415, 91);
summaryPanel_ = createPanel("Summary", 226, 180, 415, 306);
afPanel_ = (CheckBoxPanel) createPanel("Autofocus", 226, 93, 415, 178, true);
channelsPanel_ = (CheckBoxPanel) createPanel("Channels", 5, 308, 510, 451, true);
savePanel_ = (CheckBoxPanel) createPanel("Save images", 5, 453, 510, 620, true);
}
/**
* Acquisition control dialog box.
* Specification of all parameters required for the acquisition.
* @param acqEng - acquisition engine
* @param prefs - application preferences node
*/
public AcqControlDlg(AcquisitionEngine acqEng, Preferences prefs, DeviceControlGUI gui) {
super();
prefs_ = prefs;
gui_ = gui;
guiColors_ = new GUIColors();
Preferences root = Preferences.userNodeForPackage(this.getClass());
acqPrefs_ = root.node(root.absolutePath() + "/" + ACQ_SETTINGS_NODE);
colorPrefs_ = root.node(root.absolutePath() + "/" + COLOR_SETTINGS_NODE);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
numberFormat_ = NumberFormat.getNumberInstance();
addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent e) {
close();
}
});
acqEng_ = acqEng;
getContentPane().setLayout(null);
setResizable(false);
setTitle("Multi-dimensional Acquisition");
setBackground(guiColors_.background.get(gui_.getBackgroundStyle()));
createEmptyPanels();
// Frames panel
framesPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
final JLabel numberLabel = new JLabel();
numberLabel.setFont(new Font("Arial", Font.PLAIN, 10));
numberLabel.setText("Number");
framesPanel_.add(numberLabel);
numberLabel.setBounds(15, 25, 54, 24);
SpinnerModel sModel = new SpinnerNumberModel(
new Integer(1),
new Integer(1),
null,
new Integer(1));
numFrames_ = new JSpinner(sModel);
((JSpinner.DefaultEditor) numFrames_.getEditor()).getTextField().setFont(new Font("Arial", Font.PLAIN, 10));
//numFrames_.setValue((int) acqEng_.getNumFrames());
framesPanel_.add(numFrames_);
numFrames_.setBounds(60, 25, 70, 24);
numFrames_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
applySettings();
}
});
final JLabel intervalLabel = new JLabel();
intervalLabel.setFont(new Font("Arial", Font.PLAIN, 10));
intervalLabel.setText("Interval");
framesPanel_.add(intervalLabel);
intervalLabel.setBounds(15, 52, 43, 24);
interval_ = new JFormattedTextField(numberFormat_);
interval_.setFont(new Font("Arial", Font.PLAIN, 10));
interval_.setValue(new Double(1.0));
interval_.addPropertyChangeListener("value", this);
framesPanel_.add(interval_);
interval_.setBounds(60, 52, 55, 24);
timeUnitCombo_ = new JComboBox();
timeUnitCombo_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
interval_.setText(NumberUtils.doubleToDisplayString(convertMsToTime(acqEng_.getFrameIntervalMs(), timeUnitCombo_.getSelectedIndex())));
}
});
timeUnitCombo_.setModel(new DefaultComboBoxModel(new String[]{"ms", "s", "min"}));
timeUnitCombo_.setFont(new Font("Arial", Font.PLAIN, 10));
timeUnitCombo_.setBounds(120, 52, 67, 24);
framesPanel_.add(timeUnitCombo_);
// Positions (XY) panel
listButton_ = new JButton();
listButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui_.showXYPositionList();
}
});
listButton_.setToolTipText("Open XY list dialog");
listButton_.setIcon(SwingResourceManager.getIcon(AcqControlDlg.class, "icons/application_view_list.png"));
listButton_.setText("Edit position list...");
listButton_.setMargin(new Insets(2, 5, 2, 5));
listButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
listButton_.setBounds(42, 25, 136, 26);
positionsPanel_.add(listButton_);
// Slices panel
slicesPanel_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
// enable disable all related contrtols
applySettings();
}
});
final JLabel zbottomLabel = new JLabel();
zbottomLabel.setFont(new Font("Arial", Font.PLAIN, 10));
zbottomLabel.setText("Z-start [um]");
zbottomLabel.setBounds(30, 30, 69, 15);
slicesPanel_.add(zbottomLabel);
zBottom_ = new JFormattedTextField(numberFormat_);
zBottom_.setFont(new Font("Arial", Font.PLAIN, 10));
zBottom_.setBounds(95, 27, 54, 21);
zBottom_.setValue(new Double(1.0));
zBottom_.addPropertyChangeListener("value", this);
slicesPanel_.add(zBottom_);
setBottomButton_ = new JButton();
setBottomButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setBottomPosition();
}
});
setBottomButton_.setMargin(new Insets(-5, -5, -5, -5));
setBottomButton_.setFont(new Font("", Font.PLAIN, 10));
setBottomButton_.setText("Set");
setBottomButton_.setBounds(150, 27, 50, 22);
slicesPanel_.add(setBottomButton_);
final JLabel ztopLabel = new JLabel();
ztopLabel.setFont(new Font("Arial", Font.PLAIN, 10));
ztopLabel.setText("Z-end [um]");
ztopLabel.setBounds(30, 53, 69, 15);
slicesPanel_.add(ztopLabel);
zTop_ = new JFormattedTextField(numberFormat_);
zTop_.setFont(new Font("Arial", Font.PLAIN, 10));
zTop_.setBounds(95, 50, 54, 21);
zTop_.setValue(new Double(1.0));
zTop_.addPropertyChangeListener("value", this);
slicesPanel_.add(zTop_);
setTopButton_ = new JButton();
setTopButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setTopPosition();
}
});
setTopButton_.setMargin(new Insets(-5, -5, -5, -5));
setTopButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
setTopButton_.setText("Set");
setTopButton_.setBounds(150, 50, 50, 22);
slicesPanel_.add(setTopButton_);
final JLabel zstepLabel = new JLabel();
zstepLabel.setFont(new Font("Arial", Font.PLAIN, 10));
zstepLabel.setText("Z-step [um]");
zstepLabel.setBounds(30, 76, 69, 15);
slicesPanel_.add(zstepLabel);
zStep_ = new JFormattedTextField(numberFormat_);
zStep_.setFont(new Font("Arial", Font.PLAIN, 10));
zStep_.setBounds(95, 73, 54, 21);
zStep_.setValue(new Double(1.0));
zStep_.addPropertyChangeListener("value", this);
slicesPanel_.add(zStep_);
zValCombo_ = new JComboBox();
zValCombo_.setFont(new Font("Arial", Font.PLAIN, 10));
zValCombo_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zValCalcChanged();
}
});
zValCombo_.setModel(new DefaultComboBoxModel(new String[]{"relative Z", "absolute Z"}));
zValCombo_.setBounds(30, 97, 110, 22);
slicesPanel_.add(zValCombo_);
stackKeepShutterOpenCheckBox_ = new JCheckBox();
stackKeepShutterOpenCheckBox_.setText("Keep shutter open");
stackKeepShutterOpenCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
stackKeepShutterOpenCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
applySettings();
}
});
stackKeepShutterOpenCheckBox_.setSelected(false);
stackKeepShutterOpenCheckBox_.setBounds(60,121,150,22);
slicesPanel_.add(stackKeepShutterOpenCheckBox_);
// Acquisition order panel
posModeCombo_ = new JComboBox();
posModeCombo_.setFont(new Font("", Font.PLAIN, 10));
posModeCombo_.setBounds(15, 23, 151, 22);
posModeCombo_.setEnabled(false);
acquisitionOrderPanel_.add(posModeCombo_);
posModeCombo_.addItem(new PositionMode(PositionMode.MULTI_FIELD));
posModeCombo_.addItem(new PositionMode(PositionMode.TIME_LAPSE));
sliceModeCombo_ = new JComboBox();
sliceModeCombo_.setFont(new Font("", Font.PLAIN, 10));
sliceModeCombo_.setBounds(15, 49, 151, 22);
acquisitionOrderPanel_.add(sliceModeCombo_);
sliceModeCombo_.addItem(new SliceMode(SliceMode.CHANNELS_FIRST));
sliceModeCombo_.addItem(new SliceMode(SliceMode.SLICES_FIRST));
// Summary panel
summaryTextArea_ = new JTextArea();
summaryTextArea_.setFont(new Font("Arial", Font.PLAIN, 10));
summaryTextArea_.setEditable(false);
summaryTextArea_.setBounds(4, 19, 273, 99);
summaryTextArea_.setMargin(new Insets(2, 2, 2, 2));
summaryTextArea_.setOpaque(false);
summaryPanel_.add(summaryTextArea_);
// Autofocus panel
afPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
applySettings();
}
});
afButton_ = new JButton();
afButton_.setToolTipText("Set autofocus options");
afButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
afOptions();
}
});
afButton_.setText("Options...");
afButton_.setIcon(SwingResourceManager.getIcon(AcqControlDlg.class, "icons/wrench_orange.png"));
afButton_.setMargin(new Insets(2, 5, 2, 5));
afButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
afButton_.setBounds(50, 21, 100, 28);
afPanel_.add(afButton_);
final JLabel afSkipFrame1 = new JLabel();
afSkipFrame1.setFont(new Font("Dialog", Font.PLAIN, 10));
afSkipFrame1.setText("Skip frame(s): ");
afSkipFrame1.setBounds(35, 54, 70, 21);
afPanel_.add(afSkipFrame1);
afSkipInterval_ = new JSpinner(new SpinnerNumberModel(0, 0, null, 1));
((JSpinner.DefaultEditor) afSkipInterval_.getEditor()).getTextField().setFont(new Font("Arial", Font.PLAIN, 10));
afSkipInterval_.setBounds(105, 54, 55, 22);
afSkipInterval_.setValue(new Integer(acqEng_.getAfSkipInterval()));
afSkipInterval_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
applySettings();
afSkipInterval_.setValue(new Integer(acqEng_.getAfSkipInterval()));
}
});
afPanel_.add(afSkipInterval_);
// Channels panel
channelsPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
final JLabel channelsLabel = new JLabel();
channelsLabel.setFont(new Font("Arial", Font.PLAIN, 10));
channelsLabel.setBounds(90, 19, 80, 24);
channelsLabel.setText("Channel group:");
channelsPanel_.add(channelsLabel);
channelGroupCombo_ = new JComboBox();
channelGroupCombo_.setFont(new Font("", Font.PLAIN, 10));
updateGroupsCombo();
channelGroupCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String newGroup = (String) channelGroupCombo_.getSelectedItem();
if (acqEng_.setChannelGroup(newGroup)) {
model_.cleanUpConfigurationList();
if (gui_.getAutofocusManager() != null) {
try {
gui_.getAutofocusManager().refresh();
} catch (MMException e) {
ReportingUtils.showError(e);
}
}
} else {
updateGroupsCombo();
}
}
});
channelGroupCombo_.setBounds(165, 20, 150, 22);
channelsPanel_.add(channelGroupCombo_);
channelTablePane_ = new JScrollPane();
channelTablePane_.setFont(new Font("Arial", Font.PLAIN, 10));
channelTablePane_.setBounds(10, 45, 414, 90);
channelsPanel_.add(channelTablePane_);
final JButton addButton = new JButton();
addButton.setFont(new Font("Arial", Font.PLAIN, 10));
addButton.setMargin(new Insets(0, 0, 0, 0));
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
model_.addNewChannel();
model_.fireTableStructureChanged();
}
});
addButton.setText("New");
addButton.setBounds(430, 45, 68, 22);
channelsPanel_.add(addButton);
final JButton removeButton = new JButton();
removeButton.setFont(new Font("Arial", Font.PLAIN, 10));
removeButton.setMargin(new Insets(-5, -5, -5, -5));
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
model_.removeChannel(sel);
model_.fireTableStructureChanged();
if (channelTable_.getRowCount() > sel) {
channelTable_.setRowSelectionInterval(sel,sel);
}
}
}
});
removeButton.setText("Remove");
removeButton.setBounds(430, 69, 68, 22);
channelsPanel_.add(removeButton);
final JButton upButton = new JButton();
upButton.setFont(new Font("Arial", Font.PLAIN, 10));
upButton.setMargin(new Insets(0, 0, 0, 0));
upButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
int newSel = model_.rowUp(sel);
model_.fireTableStructureChanged();
channelTable_.setRowSelectionInterval(newSel, newSel);
//applySettings();
}
}
});
upButton.setText("Up");
upButton.setBounds(430, 93, 68, 22);
channelsPanel_.add(upButton);
final JButton downButton = new JButton();
downButton.setFont(new Font("Arial", Font.PLAIN, 10));
downButton.setMargin(new Insets(0, 0, 0, 0));
downButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
int newSel = model_.rowDown(sel);
model_.fireTableStructureChanged();
channelTable_.setRowSelectionInterval(newSel, newSel);
//applySettings();
}
}
});
downButton.setText("Down");
downButton.setBounds(430, 117, 68, 22);
channelsPanel_.add(downButton);
chanKeepShutterOpenCheckBox_ = new JCheckBox();
chanKeepShutterOpenCheckBox_.setText("Keep shutter open");
chanKeepShutterOpenCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
chanKeepShutterOpenCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
applySettings();
}
});
chanKeepShutterOpenCheckBox_.setSelected(false);
chanKeepShutterOpenCheckBox_.setBounds(330,20,150,22);
channelsPanel_.add(chanKeepShutterOpenCheckBox_);
// Save panel
savePanel_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (!savePanel_.isSelected()) {
displayModeCombo_.setSelectedIndex(0);
}
commentTextArea_.setEnabled(savePanel_.isSelected());
applySettings();
}
});
displayMode_ = new JLabel();
displayMode_.setFont(new Font("Arial", Font.PLAIN, 10));
displayMode_.setText("Display");
displayMode_.setBounds(150, 15, 49, 21);
savePanel_.add(displayMode_);
displayModeCombo_ = new JComboBox();
displayModeCombo_.setFont(new Font("", Font.PLAIN, 10));
displayModeCombo_.setBounds(188, 14, 150, 24);
displayModeCombo_.addItem(new DisplayMode(DisplayMode.ALL));
displayModeCombo_.addItem(new DisplayMode(DisplayMode.LAST_FRAME));
displayModeCombo_.addItem(new DisplayMode(DisplayMode.SINGLE_WINDOW));
displayModeCombo_.setEnabled(false);
savePanel_.add(displayModeCombo_);
rootLabel_ = new JLabel();
rootLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
rootLabel_.setText("Directory root");
rootLabel_.setBounds(10, 40, 72, 22);
savePanel_.add(rootLabel_);
rootField_ = new JTextField();
rootField_.setFont(new Font("Arial", Font.PLAIN, 10));
rootField_.setBounds(90, 40, 354, 22);
savePanel_.add(rootField_);
browseRootButton_ = new JButton();
browseRootButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setRootDirectory();
}
});
browseRootButton_.setMargin(new Insets(2, 5, 2, 5));
browseRootButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
browseRootButton_.setText("...");
browseRootButton_.setBounds(445, 40, 47, 24);
savePanel_.add(browseRootButton_);
namePrefixLabel_ = new JLabel();
namePrefixLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
namePrefixLabel_.setText("Name prefix");
namePrefixLabel_.setBounds(10, 65, 76, 22);
savePanel_.add(namePrefixLabel_);
nameField_ = new JTextField();
nameField_.setFont(new Font("Arial", Font.PLAIN, 10));
nameField_.setBounds(90, 65, 354, 22);
savePanel_.add(nameField_);
commentLabel_ = new JLabel();
commentLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
commentLabel_.setText("Comments");
commentLabel_.setBounds(10, 90, 76, 22);
savePanel_.add(commentLabel_);
JScrollPane commentScrollPane = new JScrollPane();
commentScrollPane.setBounds(90, 90, 354, 62);
savePanel_.add(commentScrollPane);
commentTextArea_ = new JTextArea();
commentScrollPane.setViewportView(commentTextArea_);
commentTextArea_.setFont(new Font("", Font.PLAIN, 10));
commentTextArea_.setToolTipText("Comment for the current acquistion");
commentTextArea_.setWrapStyleWord(true);
commentTextArea_.setLineWrap(true);
commentTextArea_.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
//commentTextArea_.setBounds(91, 485, 354, 62);
//savePanel_.add(commentTextArea_);
// Main buttons
final JButton closeButton = new JButton();
closeButton.setFont(new Font("Arial", Font.PLAIN, 10));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSettings();
saveAcqSettings();
AcqControlDlg.this.dispose();
gui_.makeActive();
}
});
closeButton.setText("Close");
closeButton.setBounds(430, 10, 77, 22);
getContentPane().add(closeButton);
final JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(-9, -9, -9, -9));
acquireButton.setFont(new Font("Arial", Font.BOLD, 12));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AbstractCellEditor ae = (AbstractCellEditor) channelTable_.getCellEditor();
if (ae != null) {
ae.stopCellEditing();
}
runAcquisition();
}
});
acquireButton.setText("Acquire!");
acquireButton.setBounds(430, 44, 77, 22);
getContentPane().add(acquireButton);
final JButton stopButton = new JButton();
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
acqEng_.abortRequest();
}
});
stopButton.setText("Stop");
stopButton.setFont(new Font("Arial", Font.BOLD, 12));
stopButton.setBounds(430, 68, 77, 22);
getContentPane().add(stopButton);
final JButton loadButton = new JButton();
loadButton.setFont(new Font("Arial", Font.PLAIN, 10));
loadButton.setMargin(new Insets(-5, -5, -5, -5));
loadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadAcqSettingsFromFile();
}
});
loadButton.setText("Load...");
loadButton.setBounds(430, 102, 77, 22);
getContentPane().add(loadButton);
final JButton saveAsButton = new JButton();
saveAsButton.setFont(new Font("Arial", Font.PLAIN, 10));
saveAsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAsAcqSettingsToFile();
}
});
saveAsButton.setText("Save...");
saveAsButton.setBounds(430, 126, 77, 22);
saveAsButton.setMargin(new Insets(-5, -5, -5, -5));
getContentPane().add(saveAsButton);
// update GUI contentss
// load window settings
int x = 100;
int y = 100;
this.setBounds(x, y, 521, 645);
if (prefs_ != null) {
x = prefs_.getInt(ACQ_CONTROL_X, x);
y = prefs_.getInt(ACQ_CONTROL_Y, y);
setLocation(x, y);
// load override settings
// enable/disable dependent controls
}
// add update event listeners
positionsPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
applySettings();
}
});
displayModeCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
sliceModeCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
posModeCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
// load acquistion settings
loadAcqSettings();
// create the table of channels
createChannelTable();
// update summary
updateGUIContents();
}
/** Called when a field's "value" property changes. Causes the Summary to be updated*/
public void propertyChange(PropertyChangeEvent e) {
// update summary
applySettings();
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void afOptions() {
if (gui_.getAutofocusManager().getDevice() != null) {
gui_.getAutofocusManager().showOptionsDialog();
}
}
public boolean inArray(String member, String[] group) {
for (int i = 0; i < group.length; i++) {
if (member.equals(group[i])) {
return true;
}
}
return false;
}
public void close() {
try {
saveSettings();
}
catch( Throwable t){
ReportingUtils.logError(t, "in saveSettings");
}
try {
saveAcqSettings();
}
catch( Throwable t){
ReportingUtils.logError(t, "in saveAcqSettings");
}
try{
dispose();
}
catch( Throwable t){
ReportingUtils.logError(t, "in dispose");
}
if( null!= gui_){
try{
gui_.makeActive();
}
catch( Throwable t){
ReportingUtils.logError(t, "in makeActive");
}
}
}
public void updateGroupsCombo() {
String groups[] = acqEng_.getAvailableGroups();
if (groups.length != 0) {
channelGroupCombo_.setModel(new DefaultComboBoxModel(groups));
if (!inArray(acqEng_.getChannelGroup(), groups)) {
acqEng_.setChannelGroup(acqEng_.getFirstConfigGroup());
}
channelGroupCombo_.setSelectedItem(acqEng_.getChannelGroup());
}
}
public void updateChannelAndGroupCombo() {
updateGroupsCombo();
model_.cleanUpConfigurationList();
}
public synchronized void loadAcqSettings() {
disableGUItoSettings_ = true;
// load acquisition engine preferences
acqEng_.clear();
int numFrames = acqPrefs_.getInt(ACQ_NUMFRAMES, 1);
double interval = acqPrefs_.getDouble(ACQ_INTERVAL, 0.0);
acqEng_.setFrames(numFrames, interval);
acqEng_.enableFramesSetting(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_FRAME, false));
framesPanel_.setSelected(acqEng_.isFramesSettingEnabled());
numFrames_.setValue(acqEng_.getNumFrames());
int unit = acqPrefs_.getInt(ACQ_TIME_UNIT, 0);
timeUnitCombo_.setSelectedIndex(unit);
double bottom = acqPrefs_.getDouble(ACQ_ZBOTTOM, 0.0);
double top = acqPrefs_.getDouble(ACQ_ZTOP, 0.0);
double step = acqPrefs_.getDouble(ACQ_ZSTEP, 1.0);
if (Math.abs(step) < Math.abs(acqEng_.getMinZStepUm())) {
step = acqEng_.getMinZStepUm();
}
zVals_ = acqPrefs_.getInt(ACQ_Z_VALUES, 0);
acqEng_.setSlices(bottom, top, step, zVals_ == 0 ? false : true);
acqEng_.enableZSliceSetting(acqPrefs_.getBoolean(ACQ_ENABLE_SLICE_SETTINGS, acqEng_.isZSliceSettingEnabled()));
acqEng_.enableMultiPosition(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_POSITION, acqEng_.isMultiPositionEnabled()));
positionsPanel_.setSelected(acqEng_.isMultiPositionEnabled());
slicesPanel_.setSelected(acqEng_.isZSliceSettingEnabled());
acqEng_.enableChannelsSetting(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_CHANNEL, false));
channelsPanel_.setSelected(acqEng_.isChannelsSettingEnabled());
savePanel_.setSelected(acqPrefs_.getBoolean(ACQ_SAVE_FILES, false));
nameField_.setText(acqPrefs_.get(ACQ_DIR_NAME, "Untitled"));
String os_name = System.getProperty("os.name", "");
rootField_.setText(acqPrefs_.get(ACQ_ROOT_NAME, System.getProperty("user.home") + "/AcquisitionData"));
acqEng_.setSliceMode(acqPrefs_.getInt(ACQ_SLICE_MODE, acqEng_.getSliceMode()));
acqEng_.setDisplayMode(acqPrefs_.getInt(ACQ_DISPLAY_MODE, acqEng_.getDisplayMode()));
acqEng_.setPositionMode(acqPrefs_.getInt(ACQ_POSITION_MODE, acqEng_.getPositionMode()));
acqEng_.enableAutoFocus(acqPrefs_.getBoolean(ACQ_AF_ENABLE, acqEng_.isAutoFocusEnabled()));
acqEng_.setAfSkipInterval(acqPrefs_.getInt(ACQ_AF_SKIP_INTERVAL, acqEng_.getAfSkipInterval()));
acqEng_.setChannelGroup(acqPrefs_.get(ACQ_CHANNEL_GROUP, acqEng_.getFirstConfigGroup()));
afPanel_.setSelected(acqEng_.isAutoFocusEnabled());
acqEng_.keepShutterOpenForChannels(acqPrefs_.getBoolean(ACQ_CHANNELS_KEEP_SHUTTER_OPEN, false));
acqEng_.keepShutterOpenForStack(acqPrefs_.getBoolean(ACQ_STACK_KEEP_SHUTTER_OPEN, false));
int numChannels = acqPrefs_.getInt(ACQ_NUM_CHANNELS, 0);
ChannelSpec defaultChannel = new ChannelSpec();
acqEng_.getChannels().clear();
for (int i = 0; i < numChannels; i++) {
String name = acqPrefs_.get(CHANNEL_NAME_PREFIX + i, "Undefined");
double exp = acqPrefs_.getDouble(CHANNEL_EXPOSURE_PREFIX + i, 0.0);
Boolean doZStack = acqPrefs_.getBoolean(CHANNEL_DOZSTACK_PREFIX + i, true);
double zOffset = acqPrefs_.getDouble(CHANNEL_ZOFFSET_PREFIX + i, 0.0);
ContrastSettings s8 = new ContrastSettings();
s8.min = acqPrefs_.getDouble(CHANNEL_CONTRAST8_MIN_PREFIX + i, defaultChannel.contrast8_.min);
s8.max = acqPrefs_.getDouble(CHANNEL_CONTRAST8_MAX_PREFIX + i, defaultChannel.contrast8_.max);
ContrastSettings s16 = new ContrastSettings();
s16.min = acqPrefs_.getDouble(CHANNEL_CONTRAST16_MIN_PREFIX + i, defaultChannel.contrast16_.min);
s16.max = acqPrefs_.getDouble(CHANNEL_CONTRAST16_MAX_PREFIX + i, defaultChannel.contrast16_.max);
int r = acqPrefs_.getInt(CHANNEL_COLOR_R_PREFIX + i, defaultChannel.color_.getRed());
int g = acqPrefs_.getInt(CHANNEL_COLOR_G_PREFIX + i, defaultChannel.color_.getGreen());
int b = acqPrefs_.getInt(CHANNEL_COLOR_B_PREFIX + i, defaultChannel.color_.getBlue());
int skip = acqPrefs_.getInt(CHANNEL_SKIP_PREFIX + i, defaultChannel.skipFactorFrame_);
Color c = new Color(r, g, b);
acqEng_.addChannel(name, exp, doZStack, zOffset, s8, s16, skip, c);
}
// Restore Column Width and Column order
int columnCount = 6;
columnWidth_ = new int[columnCount];
columnOrder_ = new int[columnCount];
for (int k = 0; k < columnCount; k++) {
columnWidth_[k] = acqPrefs_.getInt(ACQ_COLUMN_WIDTH + k, ACQ_DEFAULT_COLUMN_WIDTH);
columnOrder_[k] = acqPrefs_.getInt(ACQ_COLUMN_ORDER + k, k);
}
disableGUItoSettings_ = false;
}
public synchronized void saveAcqSettings() {
try {
acqPrefs_.clear();
} catch (BackingStoreException e) {
ReportingUtils.showError(e);
}
applySettings();
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_FRAME, acqEng_.isFramesSettingEnabled());
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_CHANNEL, acqEng_.isChannelsSettingEnabled());
acqPrefs_.putInt(ACQ_NUMFRAMES, acqEng_.getNumFrames());
acqPrefs_.putDouble(ACQ_INTERVAL, acqEng_.getFrameIntervalMs());
acqPrefs_.putInt(ACQ_TIME_UNIT, timeUnitCombo_.getSelectedIndex());
acqPrefs_.putDouble(ACQ_ZBOTTOM, acqEng_.getSliceZBottomUm());
acqPrefs_.putDouble(ACQ_ZTOP, acqEng_.getZTopUm());
acqPrefs_.putDouble(ACQ_ZSTEP, acqEng_.getSliceZStepUm());
acqPrefs_.putBoolean(ACQ_ENABLE_SLICE_SETTINGS, acqEng_.isZSliceSettingEnabled());
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_POSITION, acqEng_.isMultiPositionEnabled());
acqPrefs_.putInt(ACQ_Z_VALUES, zVals_);
acqPrefs_.putBoolean(ACQ_SAVE_FILES, savePanel_.isSelected());
acqPrefs_.put(ACQ_DIR_NAME, nameField_.getText());
acqPrefs_.put(ACQ_ROOT_NAME, rootField_.getText());
acqPrefs_.putInt(ACQ_SLICE_MODE, acqEng_.getSliceMode());
acqPrefs_.putInt(ACQ_DISPLAY_MODE, acqEng_.getDisplayMode());
acqPrefs_.putInt(ACQ_POSITION_MODE, acqEng_.getPositionMode());
acqPrefs_.putBoolean(ACQ_AF_ENABLE, acqEng_.isAutoFocusEnabled());
acqPrefs_.putInt(ACQ_AF_SKIP_INTERVAL, acqEng_.getAfSkipInterval());
acqPrefs_.putBoolean(ACQ_CHANNELS_KEEP_SHUTTER_OPEN, acqEng_.isShutterOpenForChannels());
acqPrefs_.putBoolean(ACQ_STACK_KEEP_SHUTTER_OPEN, acqEng_.isShutterOpenForStack());
acqPrefs_.put(ACQ_CHANNEL_GROUP, acqEng_.getChannelGroup());
ArrayList<ChannelSpec> channels = acqEng_.getChannels();
acqPrefs_.putInt(ACQ_NUM_CHANNELS, channels.size());
for (int i = 0; i < channels.size(); i++) {
ChannelSpec channel = channels.get(i);
acqPrefs_.put(CHANNEL_NAME_PREFIX + i, channel.config_);
acqPrefs_.putDouble(CHANNEL_EXPOSURE_PREFIX + i, channel.exposure_);
acqPrefs_.putBoolean(CHANNEL_DOZSTACK_PREFIX + i, channel.doZStack_);
acqPrefs_.putDouble(CHANNEL_ZOFFSET_PREFIX + i, channel.zOffset_);
acqPrefs_.putDouble(CHANNEL_CONTRAST8_MIN_PREFIX + i, channel.contrast8_.min);
acqPrefs_.putDouble(CHANNEL_CONTRAST8_MAX_PREFIX + i, channel.contrast8_.max);
acqPrefs_.putDouble(CHANNEL_CONTRAST16_MIN_PREFIX + i, channel.contrast16_.min);
acqPrefs_.putDouble(CHANNEL_CONTRAST16_MAX_PREFIX + i, channel.contrast16_.max);
acqPrefs_.putInt(CHANNEL_COLOR_R_PREFIX + i, channel.color_.getRed());
acqPrefs_.putInt(CHANNEL_COLOR_G_PREFIX + i, channel.color_.getGreen());
acqPrefs_.putInt(CHANNEL_COLOR_B_PREFIX + i, channel.color_.getBlue());
acqPrefs_.putInt(CHANNEL_SKIP_PREFIX + i, channel.skipFactorFrame_);
}
// Save model column widths and order
for (int k = 0; k < model_.getColumnCount(); k++) {
acqPrefs_.putInt(ACQ_COLUMN_WIDTH + k, findTableColumn(channelTable_, k).getWidth());
acqPrefs_.putInt(ACQ_COLUMN_ORDER + k, channelTable_.convertColumnIndexToView(k));
}
try {
acqPrefs_.flush();
} catch (BackingStoreException ex) {
ReportingUtils.logError(ex);
}
}
// Returns the TableColumn associated with the specified column
// index in the model
public TableColumn findTableColumn(JTable table, int columnModelIndex) {
Enumeration<?> e = table.getColumnModel().getColumns();
for (; e.hasMoreElements();) {
TableColumn col = (TableColumn) e.nextElement();
if (col.getModelIndex() == columnModelIndex) {
return col;
}
}
return null;
}
protected void enableZSliceControls(boolean state) {
zBottom_.setEnabled(state);
zTop_.setEnabled(state);
zStep_.setEnabled(state);
zValCombo_.setEnabled(state);
}
protected void setRootDirectory() {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setCurrentDirectory(new File(acqEng_.getRootName()));
int retVal = fc.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
rootField_.setText(fc.getSelectedFile().getAbsolutePath());
acqEng_.setRootName(fc.getSelectedFile().getAbsolutePath());
}
}
protected void setTopPosition() {
double z = acqEng_.getCurrentZPos();
zTop_.setText(NumberUtils.doubleToDisplayString(z));
applySettings();
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void setBottomPosition() {
double z = acqEng_.getCurrentZPos();
zBottom_.setText(NumberUtils.doubleToDisplayString(z));
applySettings();
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void loadAcqSettingsFromFile() {
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new AcqFileFilter());
if (null != prefs_)
acqDir_ = prefs_.get(ACQ_FILE_DIR, null);
if (acqDir_ != null) {
fc.setCurrentDirectory(new File(acqDir_));
}
int retVal = fc.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
acqFile_ = fc.getSelectedFile();
try {
FileInputStream in = new FileInputStream(acqFile_);
acqPrefs_.clear();
Preferences.importPreferences(in);
loadAcqSettings();
updateGUIContents();
in.close();
acqDir_ = acqFile_.getParent();
prefs_.put(ACQ_FILE_DIR, acqDir_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void loadAcqSettingsFromFile(String path) {
acqFile_ = new File(path);
try {
FileInputStream in = new FileInputStream(acqFile_);
acqPrefs_.clear();
Preferences.importPreferences(in);
loadAcqSettings();
updateGUIContents();
in.close();
acqDir_ = acqFile_.getParent();
if (acqDir_ != null) {
prefs_.put(ACQ_FILE_DIR, acqDir_);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
protected boolean saveAsAcqSettingsToFile() {
saveAcqSettings();
JFileChooser fc = new JFileChooser();
boolean saveFile = true;
if (acqPrefs_ == null) {
return false; //nothing to save
}
do {
if (acqFile_ == null) {
acqFile_ = new File(NEW_ACQFILE_NAME);
}
fc.setSelectedFile(acqFile_);
int retVal = fc.showSaveDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
acqFile_ = fc.getSelectedFile();
// check if file already exists
if (acqFile_.exists()) {
int sel = JOptionPane.showConfirmDialog(this,
"Overwrite " + acqFile_.getName(),
"File Save",
JOptionPane.YES_NO_OPTION);
if (sel == JOptionPane.YES_OPTION) {
saveFile = true;
} else {
saveFile = false;
}
}
} else {
return false;
}
} while (saveFile == false);
FileOutputStream os;
try {
os = new FileOutputStream(acqFile_);
acqPrefs_.exportNode(os);
} catch (FileNotFoundException e) {
ReportingUtils.showError(e);
return false;
} catch (IOException e) {
ReportingUtils.showError(e);
return false;
} catch (BackingStoreException e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public void runAcquisition() {
if (acqEng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(this, "Cannot start acquisition: previous acquisition still in progress.");
return;
}
try {
applySettings();
//saveAcqSettings(); // This is too slow.
ChannelTableModel model = (ChannelTableModel) channelTable_.getModel();
if (acqEng_.isChannelsSettingEnabled() && model.duplicateChannels()) {
JOptionPane.showMessageDialog(this, "Cannot start acquisition using the same channel twice");
return;
}
acqEng_.acquire();
} catch (MMAcqDataException e) {
ReportingUtils.showError(e);
return;
} catch (MMException e) {
ReportingUtils.showError(e);
return;
}
}
public void runAcquisition(String acqName, String acqRoot) {
if (acqEng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(this, "Unable to start the new acquisition task: previous acquisition still in progress.");
return;
}
try {
applySettings();
acqEng_.setDirName(acqName);
acqEng_.setRootName(acqRoot);
acqEng_.setSaveFiles(true);
acqEng_.acquire();
} catch (MMException e) {
ReportingUtils.showError(e);
return;
} catch (MMAcqDataException e) {
ReportingUtils.showError(e);
return;
}
}
public boolean runWellScan(WellAcquisitionData wad) {
boolean result = true;
if (acqEng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(this, "Unable to start the new acquisition task: previous acquisition still in progress.");
result = false;
return result;
}
try {
applySettings();
acqEng_.setSaveFiles(true);
result = acqEng_.acquireWellScan(wad);
if (result == false) {
acqEng_.stop(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//acqEng_.setFinished();
return result;
}
// wait until acquisition is done
while (acqEng_.isMultiFieldRunning()) {
try {
ReportingUtils.logMessage("DBG: Waiting in AcqWindow");
Thread.sleep(1000);
} catch (InterruptedException e) {
ReportingUtils.logError(e);
return result;
}
}
} catch (MMException e) {
ReportingUtils.showError(e);
return false;
} catch (MMAcqDataException e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean isAcquisitionRunning() {
return acqEng_.isAcquisitionRunning();
}
public static int search(int[] numbers, int key) {
for (int index = 0; index < numbers.length; index++) {
if (numbers[index] == key) {
return index;
}
}
return -1;
}
public void updateGUIContents() {
if (disableGUItoSettings_) {
return;
}
disableGUItoSettings_ = true;
// Disable update prevents action listener loops
// TODO: remove setChannels()
model_.setChannels(acqEng_.getChannels());
double intervalMs = acqEng_.getFrameIntervalMs();
interval_.setText(numberFormat_.format(convertMsToTime(intervalMs, timeUnitCombo_.getSelectedIndex())));
zBottom_.setText(NumberUtils.doubleToDisplayString(acqEng_.getSliceZBottomUm()));
zTop_.setText(NumberUtils.doubleToDisplayString(acqEng_.getZTopUm()));
zStep_.setText(NumberUtils.doubleToDisplayString(acqEng_.getSliceZStepUm()));
framesPanel_.setSelected(acqEng_.isFramesSettingEnabled());
slicesPanel_.setSelected(acqEng_.isZSliceSettingEnabled());
positionsPanel_.setSelected(acqEng_.isMultiPositionEnabled());
afPanel_.setSelected(acqEng_.isAutoFocusEnabled());
posModeCombo_.setEnabled(positionsPanel_.isSelected() && framesPanel_.isSelected());
sliceModeCombo_.setEnabled(slicesPanel_.isSelected() && channelsPanel_.isSelected());
afSkipInterval_.setEnabled(acqEng_.isAutoFocusEnabled());
// These values need to be cached or we will loose them due to the Spinners OnChanged methods calling applySetting
Integer numFrames = new Integer(acqEng_.getNumFrames());
Integer afSkipInterval = new Integer(acqEng_.getAfSkipInterval());
if (acqEng_.isFramesSettingEnabled())
numFrames_.setValue(numFrames);
afSkipInterval_.setValue(afSkipInterval);
enableZSliceControls(acqEng_.isZSliceSettingEnabled());
model_.fireTableStructureChanged();
channelGroupCombo_.setSelectedItem(acqEng_.getChannelGroup());
sliceModeCombo_.setSelectedIndex(acqEng_.getSliceMode());
try {
displayModeCombo_.setSelectedIndex(acqEng_.getDisplayMode());
} catch (IllegalArgumentException e) {
displayModeCombo_.setSelectedIndex(0);
}
if (framesPanel_.isSelected() && positionsPanel_.isSelected())
posModeCombo_.setSelectedIndex(acqEng_.getPositionMode());
else
posModeCombo_.setSelectedIndex(PositionMode.TIME_LAPSE);
zValCombo_.setSelectedIndex(zVals_);
stackKeepShutterOpenCheckBox_.setSelected(acqEng_.isShutterOpenForStack());
chanKeepShutterOpenCheckBox_.setSelected(acqEng_.isShutterOpenForChannels());
channelTable_.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
boolean selected = channelsPanel_.isSelected();
channelTable_.setEnabled(selected);
channelTable_.getTableHeader().setForeground(selected ? Color.black : Color.gray);
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
disableGUItoSettings_ = false;
}
private void applySettings() {
if (disableGUItoSettings_) {
return;
}
disableGUItoSettings_ = true;
AbstractCellEditor ae = (AbstractCellEditor) channelTable_.getCellEditor();
if (ae != null) {
ae.stopCellEditing();
}
try {
double zStep = NumberUtils.displayStringToDouble(zStep_.getText());
if (Math.abs(zStep) < acqEng_.getMinZStepUm()) {
zStep = acqEng_.getMinZStepUm();
}
acqEng_.setSlices(NumberUtils.displayStringToDouble(zBottom_.getText()), NumberUtils.displayStringToDouble(zTop_.getText()), zStep, zVals_ == 0 ? false : true);
acqEng_.enableZSliceSetting(slicesPanel_.isSelected());
acqEng_.enableMultiPosition(positionsPanel_.isSelected());
if( channelsPanel_.isSelected())
{
acqEng_.setSliceMode(((SliceMode) sliceModeCombo_.getSelectedItem()).getID());
}
else if(slicesPanel_.isSelected())
{
acqEng_.setSliceMode(SliceMode.SLICES_FIRST);
}
acqEng_.setDisplayMode(((DisplayMode) displayModeCombo_.getSelectedItem()).getID());
acqEng_.setPositionMode(posModeCombo_.getSelectedIndex());
acqEng_.enableChannelsSetting(channelsPanel_.isSelected());
acqEng_.setChannels(((ChannelTableModel) channelTable_.getModel()).getChannels());
acqEng_.enableFramesSetting(framesPanel_.isSelected());
acqEng_.setFrames((Integer) numFrames_.getValue(),
convertTimeToMs(NumberUtils.displayStringToDouble(interval_.getText()), timeUnitCombo_.getSelectedIndex()));
acqEng_.setAfSkipInterval(NumberUtils.displayStringToInt(afSkipInterval_.getValue().toString()));
acqEng_.keepShutterOpenForChannels(chanKeepShutterOpenCheckBox_.isSelected());
acqEng_.keepShutterOpenForStack(stackKeepShutterOpenCheckBox_.isSelected());
} catch (ParseException p) {
ReportingUtils.showError(p);
// TODO: throw error
}
acqEng_.setSaveFiles(savePanel_.isSelected());
acqEng_.setDirName(nameField_.getText());
acqEng_.setRootName(rootField_.getText());
// update summary
acqEng_.setComment(commentTextArea_.getText());
acqEng_.enableAutoFocus(afPanel_.isSelected());
acqEng_.setParameterPreferences(acqPrefs_);
disableGUItoSettings_ = false;
updateGUIContents();
}
/**
* Save settings to application properties.
*
*/
private void saveSettings() {
Rectangle r = getBounds();
if (prefs_ != null) {
// save window position
prefs_.putInt(ACQ_CONTROL_X, r.x);
prefs_.putInt(ACQ_CONTROL_Y, r.y);
}
}
private double convertTimeToMs(double interval, int units) {
if (units == 1) {
return interval * 1000; // sec
} else if (units == 2) {
return interval * 60.0 * 1000.0; // min
} else if (units == 0) {
return interval;
}
ReportingUtils.showError("Unknown units supplied for acquisition interval!");
return interval;
}
private double convertMsToTime(double intervalMs, int units) {
if (units == 1) {
return intervalMs / 1000; // sec
} else if (units == 2) {
return intervalMs / (60.0 * 1000.0); // min
} else if (units == 0) {
return intervalMs;
}
ReportingUtils.showError("Unknown units supplied for acquisition interval!");
return intervalMs;
}
private void zValCalcChanged() {
if (zValCombo_.getSelectedIndex() == 0) {
setTopButton_.setEnabled(false);
setBottomButton_.setEnabled(false);
} else {
setTopButton_.setEnabled(true);
setBottomButton_.setEnabled(true);
}
if (zVals_ == zValCombo_.getSelectedIndex()) {
return;
}
zVals_ = zValCombo_.getSelectedIndex();
double zBottomUm, zTopUm;
try {
zBottomUm = NumberUtils.displayStringToDouble(zBottom_.getText());
zTopUm = NumberUtils.displayStringToDouble(zTop_.getText());
} catch (ParseException e) {
ReportingUtils.logError(e);
return;
}
double curZ = acqEng_.getCurrentZPos();
double newTop, newBottom;
if (zVals_ == 0) {
setTopButton_.setEnabled(false);
setBottomButton_.setEnabled(false);
// convert from absolute to relative
newTop = zTopUm - curZ;
newBottom = zBottomUm - curZ;
} else {
setTopButton_.setEnabled(true);
setBottomButton_.setEnabled(true);
// convert from relative to absolute
newTop = zTopUm + curZ;
newBottom = zBottomUm + curZ;
}
zBottom_.setText(NumberUtils.doubleToDisplayString(newBottom));
zTop_.setText(NumberUtils.doubleToDisplayString(newTop));
}
/**
* This method is called from the Options dialog, to set the background style
*/
public void setBackgroundStyle(String style) {
setBackground(guiColors_.background.get(style));
for (JPanel panel : panelList_) {
//updatePanelBorder(panel);
}
repaint();
}
public class ComponentTitledPanel extends JPanel {
public ComponentTitledBorder compTitledBorder;
public boolean borderSet_ = false;
public Component titleComponent;
public void setBorder(Border border) {
if (compTitledBorder != null && borderSet_)
compTitledBorder.setBorder(border);
else
super.setBorder(border);
}
public Border getBorder() {
return compTitledBorder;
}
public void setTitleFont(Font font) {
titleComponent.setFont(font);
}
}
public class LabelPanel extends ComponentTitledPanel {
LabelPanel(String title) {
super();
titleComponent = new JLabel(title);
JLabel label = (JLabel) titleComponent;
//Dimension d = label.getPreferredSize();
label.setOpaque(true);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
//d.height = 23;
//d.width+=10;
//label.setPreferredSize(d);
compTitledBorder = new ComponentTitledBorder(label, this, BorderFactory.createEtchedBorder());
this.setBorder(compTitledBorder);
borderSet_ = true;
}
}
public class CheckBoxPanel extends ComponentTitledPanel {
JCheckBox checkBox;
CheckBoxPanel(String title) {
super();
titleComponent = new JCheckBox(title);
checkBox = (JCheckBox) titleComponent;
compTitledBorder = new ComponentTitledBorder(checkBox, this, BorderFactory.createEtchedBorder());
this.setBorder(compTitledBorder);
borderSet_ = true;
final CheckBoxPanel thisPanel = this;
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean enable = checkBox.isSelected();
thisPanel.setChildrenEnabled(enable);
}
});
}
public void setChildrenEnabled(boolean enabled) {
Component comp[] = this.getComponents();
for (int i = 0; i < comp.length; i++) {
comp[i].setEnabled(enabled);
}
}
public boolean isSelected() {
return checkBox.isSelected();
}
public void setSelected(boolean selected) {
checkBox.setSelected(selected);
setChildrenEnabled(selected);
}
public void addActionListener(ActionListener actionListener) {
checkBox.addActionListener(actionListener);
}
public void removeActionListeners() {
for (ActionListener l:checkBox.getActionListeners())
checkBox.removeActionListener(l);
}
}
} |
package client.gui.settings;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import client.gui.FancierTable;
import client.gui.MainFrame;
import client.gui.MainFrame.StatusHint;
import client.indexnode.IndexNode;
import client.indexnode.IndexNodeCommunicator;
import client.platform.ClientConfigDefaults.CK;
import common.FS2Constants;
import common.Logger;
import common.Util;
@SuppressWarnings("serial")
public class IndexnodeSettings extends SettingsPanel {
private class IndexNodeStatusRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
IndexNode node = comm.getRegisteredIndexNodes().get(nodesTable.convertRowIndexToModel(row));
setIcon(node.wasAdvertised() ? frame.getGui().getUtil().getImage("autodetect") : null);
return this;
}
}
private class IndexNodeDateRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Date lastSeen = (Date) value;
setText(lastSeen.getTime() == 0 ? "never" : Util.formatDate(lastSeen));
return this;
}
}
private class IndexNodeNameRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
IndexNode node = comm.getRegisteredIndexNodes().get(nodesTable.convertRowIndexToModel(row));
String icon;
switch (node.getNodeStatus()) {
case ACTIVE:
icon = node.isSecure() ? "secure" : "connect";
break;
case AUTHREQUIRED:
icon = "secure";
break;
case UNCONTACTABLE:
icon = "disconnect";
break;
case INCOMPATIBLE:
icon = "error";
break;
case FIREWALLED:
icon = "failure";
break;
default:
icon = "disconnect";
break;
}
setIcon(frame.getGui().getUtil().getImage(icon));
return this;
}
}
private JTable nodesTable;
private JCheckBox autodetect;
private IndexNodeCommunicator comm;
private JButton addIndexnode, removeIndexnode, setPassword;
public IndexnodeSettings(final MainFrame frame) {
super(frame, "Indexnodes", frame.getGui().getUtil().getImage("autodetect"));
comm = frame.getGui().getShareServer().getIndexNodeCommunicator();
setupAutoDetectButton(frame);
setupButtons(frame);
nodesTable = new FancierTable(comm, frame.getGui().getConf(), CK.INDEXNODE_TABLE_COLWIDTHS);
add(new JScrollPane(nodesTable), BorderLayout.CENTER);
for (int i = 0; i < comm.getColumnCount(); i++) {
TableColumn col = nodesTable.getColumn(comm.getColumnName(i));
if (i == 0) col.setCellRenderer(new IndexNodeNameRenderer());
if (i == 1) col.setCellRenderer(new IndexNodeStatusRenderer());
if (i == 2) col.setCellRenderer(new IndexNodeDateRenderer());
}
registerHint(nodesTable, new StatusHint(frame.getGui().getUtil().getImage("autodetect"), "Lists all indexnodes known to FS2 at this point in time"));
nodesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (nodesTable.getSelectedRows().length == 0) {
removeIndexnode.setEnabled(false);
setPassword.setEnabled(false);
} else {
removeIndexnode.setEnabled(true);
setPassword.setEnabled(comm.getRegisteredIndexNodes().get(nodesTable.convertRowIndexToModel(nodesTable.getSelectedRow())).isSecure());
}
}
});
}
private void setupButtons(final MainFrame frame) {
JPanel buttonsPanel = new JPanel(new FlowLayout());
add(buttonsPanel, BorderLayout.SOUTH);
addIndexnode = new JButton("Add indexnode...", frame.getGui().getUtil().getImage("add"));
addIndexnode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addIndexnode(frame);
}
});
registerHint(addIndexnode, new StatusHint(frame.getGui().getUtil().getImage("add"), "Click here to add a new indexnode manually"));
removeIndexnode = new JButton("Remove selected indexnode", frame.getGui().getUtil().getImage("delete"));
removeIndexnode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeIndexnode();
}
});
registerHint(removeIndexnode,new StatusHint(frame.getGui().getUtil().getImage("delete"), "Click here to de-register the selected indexnode"));
removeIndexnode.setEnabled(false);
setPassword = new JButton("Provide password...", frame.getGui().getUtil().getImage("unlock"));
setPassword.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setPassword();
}
});
registerHint(setPassword, new StatusHint(frame.getGui().getUtil().getImage("unlock"), "Click here to provide a password for a secure indexnode..."));
setPassword.setEnabled(false);
buttonsPanel.add(addIndexnode);
buttonsPanel.add(removeIndexnode);
buttonsPanel.add(setPassword);
}
private void setupAutoDetectButton(final MainFrame frame) {
JPanel autoPanel = new JPanel(new BorderLayout());
add(autoPanel, BorderLayout.NORTH);
autodetect = new JCheckBox();
autodetect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (autodetect.isSelected()) {
comm.enableAdvertAcceptance();
} else {
comm.disableAdvertAcceptance();
}
}
});
autodetect.setSelected(comm.isListeningForAdverts());
autoPanel.add(autodetect,BorderLayout.CENTER);
registerHint(autodetect, new StatusHint(frame.getGui().getUtil().getImage("autodetect"), "(saved on change) Check this box to enable autodetection of indexnodes"));
JLabel autolabel = new JLabel("Autodetect indexnodes: ", frame.getGui().getUtil().getImage("autodetect"), JLabel.LEFT);
autoPanel.add(autolabel, BorderLayout.WEST);
registerHint(autolabel, new StatusHint(frame.getGui().getUtil().getImage("autodetect"), "(saved on change) Check this box to enable autodetection of indexnodes"));
}
private void addIndexnode(final MainFrame frame) {
String result = (String) JOptionPane.showInputDialog(null, "Enter the URL of the new indexnode:", "New Indexnode", JOptionPane.QUESTION_MESSAGE, null, null, "");
if (result == null) return;
try {
if (!result.toLowerCase().startsWith("http:
final URL resURL = new URL(result);
Thread elsewhere = new Thread(new Runnable() {
@Override
public void run() {
comm.registerNewIndexNode(resURL);
}
}, "Add new indexnode thread");
elsewhere.setDaemon(true);
elsewhere.start();
frame.setStatusHint("Added: " + result + "... It might take a few seconds to show up...");
} catch (MalformedURLException ex) {
frame.setStatusHint(new StatusHint(frame.getGui().getUtil().getImage("error"), "Invalid new indexnode URL! (" + ex.getMessage() + ")"));
Logger.log("Invalid new indexnode URL: " + ex);
}
}
private void removeIndexnode() {
int[] togo = nodesTable.getSelectedRows();
List<IndexNode> goodbye = new ArrayList<IndexNode>();
for (int i : togo) {
goodbye.add(comm.getRegisteredIndexNodes().get(nodesTable.convertRowIndexToModel(i)));
}
for (IndexNode n : goodbye) comm.deregisterIndexNode(n);
}
private void setPassword() {
JPasswordField password = new JPasswordField();
JLabel label = new JLabel("<html><b>Enter this indexnode's password carefully.</b><br>The indexnode may create you an account if you do not already have one.</html>");
if (JOptionPane.showConfirmDialog(null, new Object[] {label, password}, "Password:", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
IndexNode node = comm.getRegisteredIndexNodes().get(nodesTable.convertRowIndexToModel(nodesTable.getSelectedRow()));
node.setPassword(Util.md5(FS2Constants.FS2_USER_PASSWORD_SALT + CharBuffer.wrap(password.getPassword())));
for (int i = 0; i < password.getPassword().length; i++) password.getPassword()[i] = 0; // Null out password from memory.
}
}
} |
package com.aha.userinterface;
import com.aha.businesslogic.model.Flight;
import com.aha.businesslogic.model.User;
import com.aha.data.FlightRepository;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//import java.util.List;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HB
*/
public class ListFlightsForm extends javax.swing.JFrame {
FlightRepository flightRepo = new FlightRepository();
private final User user;
private Flight selectedFlight;
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy kk:mm");
/**
* Creates new form ListFlights
*
* @param user
*/
public ListFlightsForm(User user) {
FlightSearchPanel flightSearchPanel = new FlightSearchPanel();
flightSearchPanel.setLocation(0, 40);
flightSearchPanel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FlightSearchEvent event = (FlightSearchEvent) e;
listFlights(event.getAirportCodeFrom(), event.getAirportCodeTo(), event.getDeparture());
}
});
add(flightSearchPanel);
this.user = user;
initComponents();
jLbl_User.setText(user.getName());
jLbl_UserType.setText("[" + user.getClass().getSimpleName() + "]");
listFlights("", "", null);
showSelectedFlightId();
//Set jTable rows sortable
jTable1.setAutoCreateRowSorter(true);
}
private String flightDepartureToString(Flight flight) {
String departure = DATE_FORMAT.format(flight.getDeparture());
return departure;
}
private String flightArrivalToString(Flight flight) {
Calendar cal = Calendar.getInstance();
cal.setTime(flight.getDeparture());
cal.add(Calendar.MINUTE, flight.getFlightDuration());
String arrival = DATE_FORMAT.format(cal.getTime());
return arrival;
}
private boolean flightMatchesFilter(Flight flight, String airportCodeFrom, String airportCodeTo, Date departure) {
if (!airportCodeFrom.isEmpty() && !flight.getAirportFrom().getCode().equals(airportCodeFrom)) {
// "From" Airport code is set in filter and flight doesn't match, return false
return false;
}
if (!airportCodeTo.isEmpty() && !flight.getAirportTo().getCode().equals(airportCodeTo)) {
// "To" Airport code is set in filter and flight doesn't match, return false
return false;
}
if (departure != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String formattedFilterDeparture = dateFormat.format(departure);
String formattedFlightDeparture = dateFormat.format(flight.getDeparture());
if (!formattedFilterDeparture.equals(formattedFlightDeparture)) {
return false;
}
}
return true;
}
private void listFlights(String airportCodeFrom, String airportCodeTo, Date departure) {
DefaultTableModel listFlightModel = (DefaultTableModel) jTable1.getModel();
listFlightModel.setRowCount(0);
selectedFlight = null;
for (Flight flight : flightRepo.getFlights()) {
if (flightMatchesFilter(flight, airportCodeFrom, airportCodeTo, departure)) {
listFlightModel.addRow(new Object[]{
//Flight number
flight.getFlightNumber(),
//From
flight.getAirportFrom().getCity(),
//Departure
flightDepartureToString(flight),
flight.getAirportTo().getCity(),
//Arrival
flightArrivalToString(flight),
//Price
flight.getPrice(),
//Book flight
});
}
}
}
private void showSelectedFlightId() {
final DefaultTableModel listFlightModel = (DefaultTableModel) jTable1.getModel();
jTable1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
bookFlightError.setText("");
if (jTable1.getSelectedRow() >= 0) {
String selectedflightNumber = String.valueOf(listFlightModel.getValueAt(jTable1.getSelectedRow(), 0));
selectedFlight = flightRepo.getFlightByFlightNumber(selectedflightNumber);
bookedFlightLabel.setText(String.valueOf(selectedFlight.getFlightNumber()));
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLbl_FlightNum = new javax.swing.JLabel();
jLbl_From = new javax.swing.JLabel();
jLbl_Departure = new javax.swing.JLabel();
jLbl_To = new javax.swing.JLabel();
jLbl_Arrival = new javax.swing.JLabel();
jLbl_Price = new javax.swing.JLabel();
jLbl_Book = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jLbl_User = new javax.swing.JLabel();
jLbl_UserType = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
bookedFlightLabel = new javax.swing.JLabel();
bookFlightButton = new javax.swing.JButton();
bookFlightError = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLbl_FlightNum.setText("Flight number");
jLbl_From.setText("From");
jLbl_Departure.setText("Departure");
jLbl_To.setText("To");
jLbl_Arrival.setText("Arrival");
jLbl_Price.setText("Price");
jLbl_Book.setText("Book this flight");
jLabel2.setText("jLabel2");
jLabel3.setText("jLabel3");
jLabel4.setText("jLabel4");
jLabel5.setText("jLabel5");
jLabel6.setText("jLabel6");
jLabel7.setText("jLabel7");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("AHA Bernot Helga, Simonics Anett");
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabel1.setText("Welcome");
jLbl_User.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLbl_User.setText("user");
jLbl_UserType.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLbl_UserType.setText("user type");
jLabel8.setText("Your flight preference:");
bookFlightButton.setText("Book flight");
bookFlightButton.setAlignmentY(0.0F);
bookFlightButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bookFlightButtonActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Flight number", "From", "Departure", "To", "Arrival", "Price"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setToolTipText("Highlight row to select flight");
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTable1.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(21, 21, 21)
.addComponent(bookedFlightLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLbl_User)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLbl_UserType)
.addGap(41, 41, 41))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(bookFlightError)
.addGap(50, 50, 50)
.addComponent(bookFlightButton)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLbl_UserType)
.addComponent(jLbl_User)
.addComponent(jLabel1)
.addComponent(jLabel8)
.addComponent(bookedFlightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(bookFlightError)
.addGap(29, 29, 29))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(bookFlightButton)
.addContainerGap())))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void bookFlightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bookFlightButtonActionPerformed
// TODO add your handling code here:
DefaultTableModel listFlightModel = (DefaultTableModel) jTable1.getModel();
if (selectedFlight != null) {
SelectSeatForm selectSeatForm = new SelectSeatForm(selectedFlight, user);
selectSeatForm.setVisible(true);
this.dispose();
} //Set error msg if no flight is selected
else {
bookFlightError.setText("Please choose a flight");
bookFlightError.setForeground(Color.red);
}
}//GEN-LAST:event_bookFlightButtonActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bookFlightButton;
private javax.swing.JLabel bookFlightError;
private javax.swing.JLabel bookedFlightLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLbl_Arrival;
private javax.swing.JLabel jLbl_Book;
private javax.swing.JLabel jLbl_Departure;
private javax.swing.JLabel jLbl_FlightNum;
private javax.swing.JLabel jLbl_From;
private javax.swing.JLabel jLbl_Price;
private javax.swing.JLabel jLbl_To;
private javax.swing.JLabel jLbl_User;
private javax.swing.JLabel jLbl_UserType;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
} |
package com.android.email;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
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.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.io.output.NullWriter;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Process;
import android.os.PowerManager.WakeLock;
import android.text.TextUtils;
import android.util.Config;
import android.util.Log;
import com.android.email.activity.FolderList;
import com.android.email.mail.Address;
import com.android.email.mail.Body;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessageRetrievalListener;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.PushReceiver;
import com.android.email.mail.Pusher;
import com.android.email.mail.Store;
import com.android.email.mail.Transport;
import com.android.email.mail.Folder.FolderType;
import com.android.email.mail.Folder.OpenMode;
import com.android.email.mail.internet.MimeMessage;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.mail.internet.TextBody;
import com.android.email.mail.store.LocalStore;
import com.android.email.mail.store.LocalStore.LocalFolder;
import com.android.email.mail.store.LocalStore.LocalMessage;
import com.android.email.mail.store.LocalStore.PendingCommand;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
private static final int MAX_SMALL_MESSAGE_SIZE = Store.FETCH_BODY_SANE_SUGGESTED_SIZE;
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.android.email.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.android.email.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG = "com.android.email.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.android.email.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.android.email.MessagingController.markAllAsRead";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newFixedThreadPool(5);
public enum SORT_TYPE {
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) {
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending) {
if (ascending) {
return ascendingToast;
}
else {
return descendingToast;
}
}
public boolean isDefaultAscending() {
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
// Key is accountUuid:folderName , value is a long of the highest message UID ever emptied from Trash
private ConcurrentHashMap<String, Long> expungedUid = new ConcurrentHashMap<String, Long>();
private String createMessageKey(Account account, String folder, Message message) {
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid) {
return account.getUuid() + ":" + folder + ":" + uid;
}
private String createFolderKey(Account account, String folder) {
return account.getUuid() + ":" + folder;
}
private void suppressMessage(Account account, String folder, Message message) {
if (account == null || folder == null || message == null) {
return;
}
String messKey = createMessageKey(account, folder, message);
// Log.d(Email.LOG_TAG, "Suppressing message with key " + messKey);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, Message message) {
if (account == null || folder == null || message == null) {
return;
}
unsuppressMessage(account, folder, message.getUid());
}
private void unsuppressMessage(Account account, String folder, String uid) {
if (account == null || folder == null || uid == null) {
return;
}
String messKey = createMessageKey(account, folder, uid);
//Log.d(Email.LOG_TAG, "Unsuppressing message with key " + messKey);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message) {
if (account == null || folder == null || message == null) {
return false;
}
String messKey = createMessageKey(account, folder, message);
//Log.d(Email.LOG_TAG, "Checking suppression of message with key " + messKey);
if (deletedUids.containsKey(messKey)) {
//Log.d(Email.LOG_TAG, "Message with key " + messKey + " is suppressed");
return true;
}
Long expungedUidL = expungedUid.get(createFolderKey(account, folder));
if (expungedUidL != null) {
long expungedUid = expungedUidL;
String messageUidS = message.getUid();
try {
long messageUid = Long.parseLong(messageUidS);
if (messageUid <= expungedUid) {
return false;
}
}
catch (NumberFormatException nfe) {
// Nothing to do
}
}
return false;
}
private MessagingController(Application application) {
mApplication = application;
mThread = new Thread(this);
mThread.start();
if (memorizingListener != null)
{
addListener(memorizingListener);
}
}
public void log(String logmess) {
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, logmess);
}
if (Email.logFile != null) {
FileOutputStream fos = null;
try {
File logFile = new File(Email.logFile);
fos = new FileOutputStream(logFile, true);
PrintStream ps = new PrintStream(fos);
ps.println(new Date() + ":" + Email.LOG_TAG + ":" + logmess);
ps.flush();
ps.close();
fos.flush();
fos.close();
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Unable to log message '" + logmess + "'", e);
}
finally {
if (fos != null) {
try {
fos.close();
}
catch (Exception e) {
}
}
}
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application) {
if (inst == null) {
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy() {
return mBusy;
}
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
String commandDescription = null;
try {
Command command = mCommands.take();
if (command != null) {
commandDescription = command.description;
String ground = (command.isForeground ? "Foreground" : "Background" );
Log.i(Email.LOG_TAG, "Running " + ground + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
command.runnable.run();
Log.i(Email.LOG_TAG, ground + " Command '" + command.description + "' completed");
for (MessagingListener l : getListeners()) {
l.controllerCommandCompleted(mCommands.size() > 0);
}
if (command.listener != null && !getListeners().contains(command.listener)) {
command.listener.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable) {
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) {
int retries = 10;
Exception e = null;
while (retries
{
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
}
catch (InterruptedException ie) {
try
{
Thread.sleep(200);
}
catch (InterruptedException ne)
{
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener) {
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener)
{
if (memorizingListener != null && listener != null)
{
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener) {
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners() {
return mListeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders( final Account account, final boolean refreshRemote, final MessagingListener listener) {
threadPool.execute(new Runnable() {
public void run()
{
for (MessagingListener l : getListeners()) {
l.listFoldersStarted(account);
}
if (listener != null) {
listener.listFoldersStarted(account);
}
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder[] localFolders = localStore.getPersonalNamespaces();
if ( refreshRemote || localFolders == null || localFolders.length == 0) {
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners()) {
l.listFolders(account, localFolders);
}
if (listener != null) {
listener.listFolders(account, localFolders);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listFoldersFailed(account, e.getMessage());
}
if (listener != null) {
listener.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, e);
return;
}
for (MessagingListener l : getListeners()) {
l.listFoldersFinished(account);
}
if (listener != null) {
listener.listFoldersFinished(account);
}
}});
}
private void doRefreshRemote (final Account account, MessagingListener listener) {
put("doRefreshRemote", listener, new Runnable() {
public void run() {
try {
Store store = Store.getInstance(account.getStoreUri(), mApplication);
Folder[] remoteFolders = store.getPersonalNamespaces();
LocalStore localStore = (LocalStore)Store.getInstance( account.getLocalStoreUri(), mApplication);
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.length; i < count; i++) {
LocalFolder localFolder = localStore.getFolder(remoteFolders[i].getName());
if (!localFolder.exists()) {
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders[i].getName());
}
Folder[] localFolders = localStore.getPersonalNamespaces();
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders) {
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(Email.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName())) {
continue;
}
if (!remoteFolderNames.contains(localFolder.getName())) {
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces();
for (MessagingListener l : getListeners()) {
l.listFolders(account, localFolders);
}
for (MessagingListener l : getListeners()) {
l.listFoldersFinished(account);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listFoldersFailed(account, "");
}
addErrorMessage(account, e);
}
}
});
}
/**
* List the local message store for the given folder. This work is done
* synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) {
for (MessagingListener l : getListeners()) {
l.listLocalMessagesStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesStarted(account, folder);
}
threadPool.execute(new Runnable() {
public void run() {
Folder localFolder = null;
final LinkedBlockingQueue<MessageContainer> queue = new LinkedBlockingQueue<MessageContainer>();
final CountDownLatch latch = new CountDownLatch(1);
Runnable callbackRunner = new Runnable()
{
List<Message> pendingMessages = new ArrayList<Message>();
boolean stop = false;
public void run()
{
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "callbackRunner started");
}
while (stop == false)
{
MessageContainer messCont = null;
do
{
if (pendingMessages.isEmpty())
{
try
{
messCont = queue.take();
}
catch (InterruptedException ie)
{
Log.i(Email.LOG_TAG, "callbackRunner interrupted");
}
}
else
{
messCont = queue.poll();
}
if (messCont != null)
{
if (messCont.last == true)
{
stop = true;
messCont = null;
}
else if (messCont.message != null)
{
pendingMessages.add(messCont.message);
}
}
} while (messCont != null);
callbackPending();
}
latch.countDown();
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "callbackRunner finished");
}
}
private void callbackPending()
{
for (MessagingListener l : getListeners()) {
l.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
pendingMessages.clear();
}
};
Thread callbackThread = new Thread(callbackRunner);
callbackThread.start();
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
localFolder.getMessages(
new MessageRetrievalListener() {
int totalDone = 0;
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal) {
if (!message.isSet(Flag.DELETED) && isMessageSuppressed(account, folder, message) == false) {
MessageContainer messCont = new MessageContainer();
messCont.message = message;
queue.add(messCont);
totalDone++;
} else {
for (MessagingListener l : getListeners()) {
l.listLocalMessagesRemoveMessage(account, folder, message);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.listLocalMessagesRemoveMessage(account, folder, message);
}
}
}
public void messagesFinished(int number) {
}
}
);
MessageContainer messCont = new MessageContainer();
messCont.last = true;
queue.add(messCont);
latch.await(1000, TimeUnit.MILLISECONDS);
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "Got ack that callbackRunner finished");
}
for (MessagingListener l : getListeners()) {
l.listLocalMessagesFinished(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, e);
}
finally
{
if (latch.getCount() != 0)
{
MessageContainer messCont = new MessageContainer();
messCont.last = true;
queue.add(messCont);
}
if (localFolder != null)
{
try
{
localFolder.close(false);
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Exception while closing folder", e);
}
}
}
}});
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener) {
try {
LocalStore localStore = (LocalStore) Store.getInstance( account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
synchronizeMailbox(account, folder, listener);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts) {
for (Account account : accounts) {
try {
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e) {
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener) {
putBackground("synchronizeMailbox", listener, new Runnable() {
public void run() {
synchronizeMailboxSynchronous(account, folder, listener);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
*/
public void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener) {
/*
* We don't ever sync the Outbox.
*/
if (folder.equals(account.getOutboxFolderName())) {
return;
}
if (account.getErrorFolderName().equals(folder)){
return;
}
String debugLine = "Synchronizing folder " + account.getDescription() + ":" + folder;
Log.i(Email.LOG_TAG, debugLine);
log(debugLine);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxStarted(account, folder);
}
LocalFolder tLocalFolder = null;
Exception commandException = null;
try {
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "SYNC: About to process pending commands for folder " +
account.getDescription() + ":" + folder);
}
try {
processPendingCommandsSynchronous(account);
}
catch (Exception e) {
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: About to get local folder " + folder);
}
final LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
tLocalFolder = (LocalFolder) localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote store for " + folder);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote folder " + folder);
}
Folder remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
Log.i(Email.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest Email.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - Email.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: About to open remote folder " + folder);
}
remoteFolder.open(OpenMode.READ_WRITE);
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
// final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " +
remoteMessageCount);
}
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message thisMess : remoteMessageArray) {
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
}
remoteMessageArray = null;
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
*/
// Iterator<Message> iter = remoteMessages.iterator();
// while (iter.hasNext()) {
// Message message = iter.next();
// Message localMessage = localUidMap.get(message.getUid());
// if (localMessage == null ||
// (!localMessage.isSet(Flag.DELETED) &&
// !localMessage.isSet(Flag.X_DOWNLOADED_FULL) &&
// !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))) {
// unsyncedMessages.add(message);
// iter.remove();
}
else if (remoteMessageCount < 0) {
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store.
*/
for (Message localMessage : localMessages) {
if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED)) {
localMessage.setFlag(Flag.X_DESTROYED, true);
// Log.d(Email.LOG_TAG, "Destroying message " + localMessage.getUid() + " which isn't in the most recent group on server");
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages);
setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages);
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
remoteFolder.close(false);
localFolder.close(false);
if (Email.DEBUG) {
log( "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages + " new messages");
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished( account, folder, remoteMessageCount, newMessages);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxFinished( account, folder, remoteMessageCount, newMessages);
}
if (commandException != null) {
String rootMessage = getRootCauseMessage(commandException);
Log.e(Email.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed( account, folder, rootMessage);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxFailed( account, folder, rootMessage);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
tLocalFolder.close(false);
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
if (listener != null && getListeners().contains(listener) == false) {
listener.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, e);
log("Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
}
private void setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException
{
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount != -1) {
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
}
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages) throws MessagingException
{
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = inputMessages.size();
if (listSize > visibleLimit)
{
inputMessages = inputMessages.subList(listSize - visibleLimit, listSize);
}
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded at all");
}
unsyncedMessages.add(message);
}
else
{
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage( account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage( account, folder, localMessage);
}
}
}
}
else
{
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "Message with uid " + message.getUid() + " is already downloaded");
}
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
Log.i(Email.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "SYNC: About to sync " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
}
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
if (!message.isSet(Flag.SEEN)) {
newMessages.incrementAndGet();
}
// Store the new message locally
localFolder.appendMessages(new Message[] {
message
});
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false) {
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, e);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
Log.i(Email.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
Log.i(Email.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
Log.i(Email.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
}
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage( account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
public void messagesFinished(int total) {}
});
Log.i(Email.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
Log.i(Email.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (Email.DEBUG)
{
Log.v(Email.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
}
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
Message localMessage = localFolder.getMessage(message.getUid());
l.synchronizeMailboxAddOrUpdateMessage( account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN)) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}//for large messsages
Log.i(Email.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags()) {
Log.i(Email.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(syncFlagMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages) {
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged && isMessageSuppressed(account, folder, localMessage) == false) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
Log.i(Email.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
return newMessages.get();
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException
{
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED)) {
return false;
}
if (remoteMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED } ) {
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
} while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command) {
try {
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localStore.addPendingCommand(command);
}
catch (Exception e) {
addErrorMessage(account, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account) {
put("processPendingCommands", null, new Runnable() {
public void run() {
try {
processPendingCommandsSynchronous(account);
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException {
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands) {
processingCommand = command;
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Processing pending command '" + command + "'");
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command)) {
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) {
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) {
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) {
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) {
processPendingEmptyTrash(command, account);
}
localStore.removePendingCommand(command);
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Done processing pending command '" + command + "'");
}
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null) {
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(Email.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null) {
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(Email.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(Email.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(Email.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else {
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate.compareTo(localDate) > 0) {
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.DELETED, true);
}
else {
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
}
}
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException {
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists()) {
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) {
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(Email.LOCAL_UID_PREFIX)) {
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null) {
throw new MessagingException("processingPendingMoveOrCopy: remoteMessage " + uid + " does not exist", true);
}
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
}
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
}
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close(true);
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) {
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy) {
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else {
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close(true);
remoteDestFolder.close(true);
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
Message remoteMessage = null;
if (!uid.startsWith(Email.LOCAL_UID_PREFIX)) {
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null) {
return;
}
remoteMessage.setFlag(flag, newState);
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException {
String folder = command.arguments[0];
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null);
for (Message message : messages) {
if (message.isSet(Flag.SEEN) == false) {
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners()) {
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder);
}
try {
if (account.getErrorFolderName().equals(folder)) {
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
remoteFolder.setFlags(new Flag[]{Flag.SEEN}, true);
remoteFolder.close(false);
}
catch (UnsupportedOperationException uoe) {
Log.w(Email.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally {
localFolder.close(false);
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, Throwable t)
{
if (Email.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
String rootCauseMessage = getRootCauseMessage(t);
log("Error" + "'" + rootCauseMessage + "'");
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
message.setBody(new TextBody(baos.toString()));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(rootCauseMessage);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, localFolder.getName());
}
}
catch (Throwable it)
{
Log.e(Email.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (Email.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(Email.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
Log.i(Email.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
/**
* Mark the message with the given account, folder and uid either Seen or not Seen.
* @param account
* @param folder
* @param uid
* @param seen
*/
public void markMessageRead(
final Account account,
final String folder,
final String uid,
final boolean seen) {
setMessageFlag(account, folder, uid, Flag.SEEN, seen);
}
/**
* Mark the message with the given account, folder and uid either Seen or not Seen.
* @param account
* @param folder
* @param uid
* @param seen
*/
public void markMessageRead(
final Account account,
final Folder folder,
final Message message,
final boolean seen) {
setMessageFlag(account, folder, message, Flag.SEEN, seen);
}
public void setMessageFlag(
final Account account,
final String folder,
final String uid,
final Flag flag,
final boolean newState) {
// TODO: put this into the background, but right now that causes odd behavior
// because the MessageList doesn't have its own cache of the flag states
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
setMessageFlag(account, localFolder, message, flag, newState);
localFolder.close(false);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException(me);
}
}
public void setMessageFlag(
final Account account,
final Folder folder,
final Message message,
final Flag flag,
final boolean newState) {
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
try {
String uid = message.getUid();
String folderName = folder.getName();
message.setFlag(flag, newState);
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folderName))
{
sendCount.remove(uid);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folderName);
}
if (account.getErrorFolderName().equals(folderName))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folderName, uid, Boolean.toString(newState), flag.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException(me);
}
}//setMesssageFlag
public void clearAllPending(final Account account)
{
try
{
Log.w(Email.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, me);
}
}
private void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener) {
put("loadMessageForViewRemote", listener, new Runnable() {
public void run() {
Folder remoteFolder = null;
LocalFolder localFolder = null;
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
}
else {
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// This is a view message request, so mark it read
if (!message.isSet(Flag.SEEN)) {
markMessageRead(account, localFolder, message, true);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, e);
}
finally {
if (remoteFolder!=null) {
try {
remoteFolder.close(false);
}
catch (MessagingException e) {
Log.w(Email.LOG_TAG, null, e);
}
}
if (localFolder!=null) {
try {
localFolder.close(false);
}
catch (MessagingException e) {
Log.w(Email.LOG_TAG, null, e);
}
}
}//finally
}//run
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewStarted(account, folder, uid);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable() {
public void run() {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
for (MessagingListener l : getListeners()) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
loadMessageForViewRemote(account, folder, uid, listener);
localFolder.close(false);
return;
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] {
message
}, fp, null);
localFolder.close(false);
if (!message.isSet(Flag.SEEN)) {
markMessageRead(account, localFolder, message, true);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, e);
}
}
});
}
// public void loadMessageForViewSynchronous(final Account account, final String folder, final String uid,
// MessagingListener listener) {
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewStarted(account, folder, uid);
// LocalFolder localFolder = null;
// Folder remoteFolder = null;
// try {
// Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
// localFolder = (LocalFolder) localStore.getFolder(folder);
// localFolder.open(OpenMode.READ_WRITE);
// Message message = localFolder.getMessage(uid);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
// if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
// Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
// remoteFolder = remoteStore.getFolder(folder);
// remoteFolder.open(OpenMode.READ_WRITE);
// // Get the remote message and fully download it
// Message remoteMessage = remoteFolder.getMessage(uid);
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.BODY);
// remoteFolder.fetch(new Message[]{remoteMessage}, fp, null);
// // Store the message locally and load the stored message into memory
// localFolder.appendMessages(new Message[]{remoteMessage});
// message = localFolder.getMessage(uid);
// localFolder.fetch(new Message[]{message}, fp, null);
// // Mark that this message is now fully synched
// message.setFlag(Flag.X_DOWNLOADED_FULL, true);
// else {
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.ENVELOPE);
// fp.add(FetchProfile.Item.BODY);
// localFolder.fetch(new Message[]{
// message
// }, fp, null);
// if (!message.isSet(Flag.SEEN)) {
// markMessageRead(account, localFolder, message, true);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewBodyAvailable(account, folder, uid, message);
// if (listener != null) {
// listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewFinished(account, folder, uid, message);
// if (listener != null) {
// listener.loadMessageForViewFinished(account, folder, uid, message);
// catch (Exception e) {
// for (MessagingListener l : getListeners()) {
// l.loadMessageForViewFailed(account, folder, uid, e.getMessage());
// addErrorMessage(account, e);
// finally {
// if (localFolder!=null) {
// try {
// localFolder.close(false);
// catch (MessagingException e) {
// Log.w(Email.LOG_TAG, null, e);
// if (remoteFolder!=null) {
// try {
// remoteFolder.close(false);
// catch (MessagingException e) {
// Log.w(Email.LOG_TAG, null, e);
// }//loadMessageForViewSynchronous
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener) {
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try {
if (part.getBody() != null) {
for (MessagingListener l : getListeners()) {
l.loadAttachmentStarted(account, message, part, tag, false);
}
if (listener != null) {
listener.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null) {
listener.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me) {
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentStarted(account, message, part, tag, true);
}
if (listener != null) {
listener.loadAttachmentStarted(account, message, part, tag, false);
}
put("loadAttachment", listener, new Runnable() {
public void run() {
try {
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments) {
attachment.setBody(null);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(message.getFolder().getName());
Folder remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
FetchProfile fp = new FetchProfile();
fp.add(part);
remoteFolder.fetch(new Message[] { message }, fp, null);
localFolder.updateMessage((LocalMessage)message);
localFolder.close(false);
for (MessagingListener l : getListeners()) {
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null) {
listener.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me) {
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "", me);
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
if (listener != null) {
listener.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, me);
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close(false);
sendPendingMessages(account, null);
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
// TODO general failed
}
addErrorMessage(account, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener) {
putBackground("sendPendingMessages", listener, new Runnable() {
public void run() {
sendPendingMessagesSynchronous(account);
}
});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account) {
Folder localFolder = null;
try {
Store localStore = Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return;
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
Log.i(Email.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account.getTransportUri());
for (Message message : localMessages) {
if (message.isSet(Flag.DELETED)) {
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED)) {
Log.i(Email.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try {
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
Log.i(Email.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > Email.MAX_SEND_ATTEMPTS)
{
Log.e(Email.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try {
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
Log.i(Email.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
Log.i(Email.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
Log.i(Email.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
localSentFolder.getName(),
message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e) {
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
Log.i(Email.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(Email.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
localFolder.expunge();
if (localFolder.getMessageCount() == 0) {
localFolder.delete(false);
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, Email.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent i = FolderList.actionHandleAccountIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, Email.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close(false);
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void getAccountUnreadCount(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable() {
public void run() {
int unreadMessageCount = 0;
try {
unreadMessageCount = account.getUnreadMessageCount(context, mApplication);
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
l.accountStatusChanged(account, unreadMessageCount);
}
};
putBackground("getAccountUnread:" + account.getDescription(), l, unreadRunnable);
}
public boolean moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith(Email.LOCAL_UID_PREFIX)) {
suppressMessage(account, srcFolder, message);
put("moveMessage", null, new Runnable() {
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, false, listener);
}
});
return true;
}
else
{
return false;
}
}
public boolean isMoveCapable(Message message) {
if (!message.getUid().startsWith(Email.LOCAL_UID_PREFIX)) {
return true;
}
else {
return false;
}
}
public boolean isCopyCapable(Message message) {
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public boolean copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith(Email.LOCAL_UID_PREFIX)) {
put("copyMessage", null, new Runnable() {
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, true, listener);
}
});
return true;
}
else
{
return false;
}
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message message,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false)) {
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false)) {
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
Message lMessage = localSrcFolder.getMessage(message.getUid());
String origUid = message.getUid();
if (lMessage != null)
{
Log.i(Email.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", uid = " + origUid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(new Message[] { message }, fp, null);
localSrcFolder.copyMessages(new Message[] { message }, localDestFolder);
}
else {
localSrcFolder.moveMessages(new Message[] { message }, localDestFolder);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY;
command.arguments = new String[] { srcFolder, origUid, destFolder, Boolean.toString(isCopy) };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Error moving message", me);
}
}
public void deleteMessage(final Account account, final String folder, final Message message,
final MessagingListener listener) {
suppressMessage(account, folder, message);
put("deleteMessage", null, new Runnable() {
public void run() {
deleteMessageSynchronous(account, folder, message, listener);
}
});
}
private void deleteMessageSynchronous(final Account account, final String folder, final Message message,
MessagingListener listener) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(folder);
Message lMessage = localFolder.getMessage(message.getUid());
String origUid = message.getUid();
if (lMessage != null)
{
if (folder.equals(account.getTrashFolderName()))
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Deleting message in trash folder, not copying");
}
lMessage.setFlag(Flag.DELETED, true);
}
else
{
Folder localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (localTrashFolder.exists() == false)
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists() == true)
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Deleting message in normal folder, moving");
}
localFolder.moveMessages(new Message[] { message }, localTrashFolder);
}
}
}
localFolder.close(false);
unsuppressMessage(account, folder, message);
if (listener != null) {
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, account.getTrashFolderName());
}
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
}
if (folder.equals(account.getOutboxFolderName()))
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
account.getTrashFolderName(),
message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folder, origUid, Boolean.toString(true), Flag.DELETED.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY;
command.arguments = new String[] { folder, origUid, account.getTrashFolderName(), "false" };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folder, origUid, Boolean.toString(true), Flag.SEEN.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException {
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
remoteFolder.close(true);
}
}
public void emptyTrash(final Account account, MessagingListener listener) {
put("emptyTrash", listener, new Runnable() {
public void run() {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
localFolder.close(true);
for (MessagingListener l : getListeners()) {
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, e);
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
}
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
}
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener) {
WakeLock twakeLock = null;
if (useManualWakeLock) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Email");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(Email.MANUAL_WAKE_LOCK_TIMEOUT);
}
final WakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners()) {
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable() {
public void run() {
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
Log.i(Email.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null) {
accounts = new Account[] {
account
};
} else {
accounts = prefs.getAccounts();
}
for (final Account account : accounts) {
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
Log.i(Email.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
continue;
}
Log.i(Email.LOG_TAG, "Synchronizing account " + account.getDescription());
putBackground("sendPending " + account.getDescription(), null, new Runnable() {
public void run() {
if (account.isShowOngoing()) {
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent intent = FolderList.actionHandleAccountIntent(context, account, Email.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (Email.NOTIFICATION_LED_WHILE_SYNCING) {
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(Email.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally {
if (account.isShowOngoing()) {
notifMgr.cancel(Email.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
for (final Folder folder : localStore.getPersonalNamespaces())
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never sync a folder that isn't displayed
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
}
continue;
}
if (modeMismatch(aSyncMode, fSyncClass))
{
// Do not sync folders in the wrong class
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
}
continue;
}
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
}
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable() {
public void run() {
try {
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder tLocalFolder = (LocalFolder) localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
return;
}
if (account.isShowOngoing()) {
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
// JRV XXX TODO - do we want to notify MessageList too?
Intent intent = FolderList.actionHandleAccountIntent(context, account, Email.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (Email.NOTIFICATION_LED_WHILE_SYNCING) {
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(Email.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName(), listener);
}
finally {
if (account.isShowOngoing()) {
notifMgr.cancel(Email.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, e);
}
}
}
);
}
}
catch (MessagingException e) {
Log.e(Email.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, e);
}
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, e);
}
putBackground("finalize sync", null, new Runnable() {
public void run() {
Log.i(Email.LOG_TAG, "Finished mail sync");
if (wakeLock != null)
{
wakeLock.release();
}
for (MessagingListener l : getListeners()) {
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners()) {
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners()) {
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void notifyAccount(Context context, Account thisAccount, int unreadMessageCount)
{
boolean isNotifyAccount = thisAccount.isNotifyNewMail();
if (isNotifyAccount)
{
String notice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount,
thisAccount.getDescription());
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
context.getString(R.string.notification_new_title), System.currentTimeMillis());
notif.number = unreadMessageCount;
Intent i = FolderList.actionHandleAccountIntent(context, thisAccount);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_new_title), notice, pi);
String ringtone = thisAccount.getRingtone();
notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
if (thisAccount.isVibrate()) {
notif.defaults |= Notification.DEFAULT_VIBRATE;
}
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_OFF_TIME;
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.notify(thisAccount.getAccountNumber(), notif);
}
}
public void saveDraft(final Account account, final Message message) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] {
localFolder.getName(),
localMessage.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e) {
Log.e(Email.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, e);
}
}
private boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode)
{
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS))
{
return true;
}
else
{
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
class Command implements Comparable {
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
public int compareTo(Object arg0)
{
if (arg0 instanceof Command)
{
Command other = (Command)arg0;
if (other.isForeground == true && isForeground == false)
{
return 1;
}
else if (other.isForeground == false && isForeground == true)
{
return -1;
}
else
{
return (sequence - other.sequence);
}
}
return 0;
}
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
public Collection<Pusher> getPushers()
{
return pushers.values();
}
public Pusher setupPushing(final Account account)
{
Pusher pusher = pushers.get(account);
if (pusher != null)
{
return pusher;
}
Store store = null;
try
{
store = Store.getInstance(account.getStoreUri(), mApplication);
if (store.isPushCapable() == false)
{
Log.i(Email.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return null;
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Could not get remote store", e);
return null;
}
final MessagingController controller = this;
PushReceiver receiver = new PushReceiver()
{
WakeLock wakeLock = null;
int refCount = 0;
public synchronized void pushInProgress()
{
if (wakeLock == null)
{
PowerManager pm = (PowerManager) mApplication.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Email");
wakeLock.setReferenceCounted(false);
}
wakeLock.acquire(Email.PUSH_WAKE_LOCK_TIMEOUT);
refCount++;
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Acquired WakeLock for Pushing");
}
}
public synchronized void pushComplete()
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Considering releasing WakeLock for Pushing");
}
if (wakeLock != null)
{
if (refCount > 0)
{
refCount
}
if (refCount == 0)
{
try
{
if (Email.DEBUG)
{
Log.d(Email.LOG_TAG, "Releasing WakeLock for Pushing");
}
wakeLock.release();
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Failed to release WakeLock", e);
}
}
}
}
public void messagesFlagsChanged(String folderName,
List<Message> messages)
{
controller.messagesArrived(account, folderName, messages, false);
}
public void messagesArrived(String folderName, List<Message> messages)
{
controller.messagesArrived(account, folderName, messages, true);
}
public void pushError(String errorMessage, Exception e)
{
String errMess = errorMessage;
String body = null;
if (errMess == null && e != null)
{
errMess = e.getMessage();
}
body = errMess;
if (e != null)
{
body = e.toString();
}
controller.addErrorMessage(account, errMess, body);
}
public String getPushState(String folderName)
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
localFolder= (LocalFolder) localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
return localFolder.getPushState();
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to get push state from account " + account.getDescription()
+ ", folder " + folderName, e);
return null;
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close(false);
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to close folder '" + folderName + "' in account " + account.getDescription(), e);
}
}
}
}
public void setPushActive(String folderName, boolean enabled)
{
for (MessagingListener l : getListeners()) {
l.setPushActive(account, folderName, enabled);
}
}
};
try
{
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
for (final Folder folder : localStore.getPersonalNamespaces())
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never push a folder that isn't displayed
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
}
continue;
}
if (modeMismatch(aPushMode, fPushClass))
{
// Do not push folders in the wrong class
if (Email.DEBUG) {
Log.v(Email.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
}
continue;
}
Log.i(Email.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (names.size() > 0)
{
pusher = store.getPusher(receiver, names);
if (pusher != null)
{
pushers.put(account, pusher);
}
return pusher;
}
else
{
Log.i(Email.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return null;
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Got exception while setting up pushing", e);
}
return null;
}
public void stopPushing(Account account)
{
Pusher pusher = pushers.remove(account);
if (pusher != null)
{
pusher.stop();
}
}
public void stopAllPushing()
{
Log.i(Email.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext())
{
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final String folderName, final List<Message> messages, final boolean doNotify)
{
Log.i(Email.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + folderName);
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + folderName, null, new Runnable()
{
public void run()
{
LocalFolder localFolder = null;
Folder remoteFolder = null;
try
{
LocalStore localStore = (LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
remoteFolder = remoteStore.getFolder(folderName);
localFolder= (LocalFolder) localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
remoteFolder.open(OpenMode.READ_WRITE);
downloadMessages(account, remoteFolder, localFolder, messages);
int unreadCount = 0;
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
unreadCount++;
}
}
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
int unreadMessageCount = account.getUnreadMessageCount(mApplication, mApplication);
if (doNotify && unreadCount > 0)
{
notifyAccount(mApplication, account, unreadMessageCount);
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folderName);
l.accountStatusChanged(account, unreadMessageCount);
}
}
catch (Exception e)
{
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try
{
localFolder.setStatus(errorMessage);
}
catch (Exception se)
{
Log.e(Email.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed( account, folderName, errorMessage);
}
addErrorMessage(account, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close(false);
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to close localFolder", e);
}
}
if (remoteFolder != null)
{
try
{
remoteFolder.close(false);
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to close remoteFolder", e);
}
}
latch.countDown();
}
}
});
try
{
latch.await();
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Interrupted while awaiting latch release", e);
}
Log.i(Email.LOG_TAG, "Latch released");
}
enum MemorizingState { STARTED, FINISHED, FAILED };
class Memory
{
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
Memory(Account nAccount, String nFolderName)
{
account = nAccount;
folderName = nFolderName;
}
String getKey()
{
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName)
{
return taccount.getDescription() + ":" + tfolderName;
}
class MemorizingListener extends MessagingListener
{
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName)
{
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null)
{
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
public synchronized void synchronizeMailboxStarted(Account account, String folder) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
}
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message) {
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other)
{
if (other != null)
{
Memory syncStarted = null;
Memory sendStarted = null;
for (Memory memory : memories.values())
{
if (memory.syncingState != null)
{
switch (memory.syncingState)
{
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null)
{
switch (memory.sendingState)
{
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null)
{
switch (memory.pushingState)
{
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
}
}
}
if (syncStarted != null)
{
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
}
if (sendStarted != null)
{
other.sendPendingMessagesStarted(sendStarted.account);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active) {
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
public synchronized void sendPendingMessagesStarted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
}
public synchronized void sendPendingMessagesCompleted(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
public synchronized void sendPendingMessagesFailed(Account account) {
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
}
class MessageContainer
{
Message message;
boolean last;
}
} |
package com.clavain.checks;
import java.util.List;
/**
*
* @author enricokern
*/
public class ReturnServiceCheck {
private Integer returnValue;
private List<String> output;
private Integer user_id;
private Integer cid;
private Integer checktime;
private Integer downTimeConfirmedAt;
private Integer lastDownTimeConfirm;
private String checktype;
private String checkname;
private Integer interval;
private Integer notifydown = 0;
private Integer notifyagain = 0;
private Integer notifyifup = 0;
private Integer notifyflap = 0;
private String json;
/**
* @return the returnValue
*/
public Integer getReturnValue() {
return returnValue;
}
/**
* @param aReturnValue the returnValue to set
*/
public void setReturnValue(Integer aReturnValue) {
returnValue = aReturnValue;
}
/**
* @return the output
*/
public List<String> getOutput() {
return output;
}
/**
* @param aOutput the output to set
*/
public void setOutput(List<String> aOutput) {
output = aOutput;
}
public ReturnServiceCheck(Integer p_iReturnValue,List<String> p_returnOutput)
{
returnValue = p_iReturnValue;
output = p_returnOutput;
}
/**
* @return the user_id
*/
public Integer getUser_id() {
return user_id;
}
/**
* @param user_id the user_id to set
*/
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
/**
* @return the cid
*/
public Integer getCid() {
return cid;
}
/**
* @param cid the cid to set
*/
public void setCid(Integer cid) {
this.cid = cid;
}
/**
* @return the checktime
*/
public Integer getChecktime() {
return checktime;
}
/**
* @param checktime the checktime to set
*/
public void setChecktime(Integer checktime) {
this.checktime = checktime;
}
/**
* @return the downTimeConfirmedAt
*/
public Integer getDownTimeConfirmedAt() {
return downTimeConfirmedAt;
}
/**
* @param downTimeConfirmedAt the downTimeConfirmedAt to set
*/
public void setDownTimeConfirmedAt(Integer downTimeConfirmedAt) {
this.downTimeConfirmedAt = downTimeConfirmedAt;
}
/**
* @return the lastDownTimeConfirm
*/
public Integer getLastDownTimeConfirm() {
return lastDownTimeConfirm;
}
/**
* @param lastDownTimeConfirm the lastDownTimeConfirm to set
*/
public void setLastDownTimeConfirm(Integer lastDownTimeConfirm) {
this.lastDownTimeConfirm = lastDownTimeConfirm;
}
/**
* @return the checktype
*/
public String getChecktype() {
return checktype;
}
/**
* @param checktype the checktype to set
*/
public void setChecktype(String checktype) {
this.checktype = checktype;
}
/**
* @return the checkname
*/
public String getCheckname() {
return checkname;
}
/**
* @param checkname the checkname to set
*/
public void setCheckname(String checkname) {
this.checkname = checkname;
}
/**
* @return the interval
*/
public Integer getInterval() {
return interval;
}
/**
* @param interval the interval to set
*/
public void setInterval(Integer interval) {
this.interval = interval;
}
/**
* @return the notifydown
*/
public Integer getNotifydown() {
return notifydown;
}
/**
* @param notifydown the notifydown to set
*/
public void setNotifydown(Integer notifydown) {
this.notifydown = notifydown;
}
/**
* @return the notifyagain
*/
public Integer getNotifyagain() {
return notifyagain;
}
/**
* @param notifyagain the notifyagain to set
*/
public void setNotifyagain(Integer notifyagain) {
this.notifyagain = notifyagain;
}
/**
* @return the notifyifup
*/
public Integer getNotifyifup() {
return notifyifup;
}
/**
* @param notifyifup the notifyifup to set
*/
public void setNotifyifup(Integer notifyifup) {
this.notifyifup = notifyifup;
}
/**
* @return the notifyflap
*/
public Integer getNotifyflap() {
return notifyflap;
}
/**
* @param notifyflap the notifyflap to set
*/
public void setNotifyflap(Integer notifyflap) {
this.notifyflap = notifyflap;
}
/**
* @return the json
*/
public String getJson() {
return json;
}
/**
* @param json the json to set
*/
public void setJson(String json) {
this.json = json;
}
} |
package com.example.visionapp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class ResultsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
protected void onResume() {
super.onResume();
try {
getRtpi();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getRtpi() throws Exception {
String stopNumber = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
stopNumber = extras.getString("rtpi stop");
}
System.out.println(stopNumber);
Document doc = sendGet(stopNumber);
String[][] results = parseDoc(doc);
TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
for (int i = 0; i < results.length; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < results[i].length; j++) {
TextView t = new TextView(this);
t.setText(" " + results[i][j] + " ");
row.addView(t);
}
table.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
}
private Document sendGet(String stopNumber) throws Exception {
String url = "http://rtpi.ie/Text/WebDisplay.aspx?stopRef=" + ("00000" + stopNumber).substring(stopNumber.length());
URL obj;
StringBuffer response = null;
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Document doc = Jsoup.parse(response.toString());
return doc;
}
private String[][] parseDoc(Document doc) {
String result = doc.getElementsByClass("webDisplayTable").toString();
String[] parsed = result.split("<tr");
String[][] results = new String[parsed.length - 2][];
for (int i = 1; i < parsed.length - 1; i++) {
results[i - 1] = parsed[i].split("<td");
}
String[][] splitResults = new String[results.length-1][3];
for (int i = 0; i < splitResults.length; i++) {
for (int j = 0; j < 3; j++) {
splitResults[i][j] = results[i+1][j+1];
if (j == 2) {
splitResults[i][j] = splitResults[i][j].substring(33, splitResults[i][j].length() - 9);
}
else {
splitResults[i][j] = splitResults[i][j].substring(19, splitResults[i][j].length() - 9);
}
}
}
return splitResults;
}
public void goBack(View view) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results,
container, false);
return rootView;
}
}
} |
package com.ibm.ServerWizard2.view;
import java.util.Vector;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.wb.swt.SWTResourceManager;
import com.ibm.ServerWizard2.ServerWizard2;
import com.ibm.ServerWizard2.controller.TargetWizardController;
import com.ibm.ServerWizard2.model.Connection;
import com.ibm.ServerWizard2.model.ConnectionEndpoint;
import com.ibm.ServerWizard2.model.Field;
import com.ibm.ServerWizard2.model.Target;
import com.ibm.ServerWizard2.utility.GithubFile;
public class MainDialog extends Dialog {
private TableViewer viewer;
private Tree tree;
private TreeColumn columnName;
private Text txtInstanceName;
private Combo combo;
private Menu popupMenu;
private Composite container;
private TreeItem selectedEndpoint;
private String currentPath;
private Target targetForConnections;
private ConnectionEndpoint source;
private ConnectionEndpoint dest;
private TargetWizardController controller;
// Buttons
private Button btnAddTarget;
private Button btnCopyInstance;
private Button btnDefaults;
private Button btnDeleteTarget;
private Button btnSave;
private Button btnOpen;
private Button btnClone;
private Button btnOpenLib;
private Button btnDeleteConnection;
private Button btnSaveAs;
// document state
private Boolean dirty = false;
public String mrwFilename = "";
private Button btnRunChecks;
private SashForm sashForm;
private SashForm sashForm_1;
private Composite compositeBus;
private Label lblInstanceType;
private Composite compositeInstance;
private Composite composite;
private Composite buttonRow1;
private Vector<Field> attributes;
private Combo cmbBusses;
private Label lblChooseBus;
private Label lblSelectedCard;
private Boolean busMode = false;
private TabFolder tabFolder;
private TabItem tbtmAddInstances;
private TabItem tbtmAddBusses;
private Combo cmbCards;
private Boolean targetFound = false;
private List listBusses;
private Label lblBusDirections;
private Label lblInstanceDirections;
private Composite compositeDir;
private Button btnHideBusses;
private Button btnShowHidden;
private AttributeEditingSupport attributeEditor;
private Label label;
private Label label_1;
/**
* Create the dialog.
*
* @param parentShell
*/
public MainDialog(Shell parentShell) {
super(parentShell);
setShellStyle(SWT.BORDER | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.APPLICATION_MODAL);
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("ServerWiz2");
}
public void setController(TargetWizardController t) {
controller = t;
}
/**
* Create contents of the dialog.
*
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
container = (Composite) super.createDialogArea(parent);
container.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
GridLayout gl_container = new GridLayout(1, false);
gl_container.verticalSpacing = 0;
container.setLayout(gl_container);
composite = new Composite(container, SWT.NONE);
RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL);
rl_composite.spacing = 20;
rl_composite.wrap = false;
rl_composite.fill = true;
composite.setLayout(rl_composite);
GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
gd_composite.widthHint = 918;
gd_composite.heightHint = 154;
composite.setLayoutData(gd_composite);
sashForm_1 = new SashForm(container, SWT.BORDER | SWT.VERTICAL);
GridData gd_sashForm_1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
gd_sashForm_1.heightHint = 375;
gd_sashForm_1.widthHint = 712;
sashForm_1.setLayoutData(gd_sashForm_1);
buttonRow1 = new Composite(container, SWT.NONE);
GridData gd_buttonRow1 = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
gd_buttonRow1.widthHint = 866;
buttonRow1.setLayoutData(gd_buttonRow1);
GridLayout rl_buttonRow1 = new GridLayout(18, false);
buttonRow1.setLayout(rl_buttonRow1);
this.createButtonsForButtonBar2(buttonRow1);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
new Label(buttonRow1, SWT.NONE);
sashForm = new SashForm(sashForm_1, SWT.NONE);
// Target Instances View
tree = new Tree(sashForm, SWT.BORDER | SWT.VIRTUAL);
tree.setHeaderVisible(true);
tree.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
columnName = new TreeColumn(tree, 0);
columnName.setText("Instances");
columnName
.setToolTipText("To add a new instance, choose parent instance. A list of child instances will appear in Instance Type combo.\r\n"
+ "Select and Instance type. You can optionally enter a custom name. Then click 'Add Instance' button.");
columnName.setResizable(true);
// Create attribute table
viewer = new TableViewer(sashForm_1, SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.BORDER);
this.createAttributeTable();
sashForm_1.setWeights(new int[] { 1, 1 });
// Tab folders
tabFolder = new TabFolder(composite, SWT.NONE);
tabFolder.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
tabFolder.setLayoutData(new RowData(SWT.DEFAULT, 119));
tbtmAddInstances = new TabItem(tabFolder, SWT.NONE);
tbtmAddInstances.setText("Instances");
// Add instances tab
compositeInstance = new Composite(tabFolder, SWT.BORDER);
tbtmAddInstances.setControl(compositeInstance);
compositeInstance.setLayout(new GridLayout(3, false));
lblInstanceType = new Label(compositeInstance, SWT.NONE);
lblInstanceType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblInstanceType.setText("Instance Type:");
lblInstanceType.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
combo = new Combo(compositeInstance, SWT.READ_ONLY);
GridData gd_combo = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gd_combo.widthHint = 167;
combo.setLayoutData(gd_combo);
combo.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnAddTarget = new Button(compositeInstance, SWT.NONE);
btnAddTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnAddTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnAddTarget.setText("Add Instance");
btnAddTarget.setEnabled(false);
Label lblName = new Label(compositeInstance, SWT.NONE);
lblName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
lblName.setText("Custom Name:");
txtInstanceName = new Text(compositeInstance, SWT.BORDER);
GridData gd_txtInstanceName = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gd_txtInstanceName.widthHint = 175;
txtInstanceName.setLayoutData(gd_txtInstanceName);
txtInstanceName.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnDeleteTarget = new Button(compositeInstance, SWT.NONE);
btnDeleteTarget.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnDeleteTarget.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnDeleteTarget.setText("Delete Instance");
btnShowHidden = new Button(compositeInstance, SWT.CHECK);
btnShowHidden.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
GridData gd_btnShowHidden = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnShowHidden.heightHint = 20;
btnShowHidden.setLayoutData(gd_btnShowHidden);
btnShowHidden.setText(" Show Hidden");
btnCopyInstance = new Button(compositeInstance, SWT.NONE);
btnCopyInstance.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
btnCopyInstance.setText("Copy Node or Connector");
btnCopyInstance.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnCopyInstance.setEnabled(false);
btnDefaults = new Button(compositeInstance, SWT.NONE);
btnDefaults.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
btnDefaults.setText("Restore Defaults");
btnDefaults.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnDefaults.setEnabled(false);
// Add Busses Tab
tbtmAddBusses = new TabItem(tabFolder, SWT.NONE);
tbtmAddBusses.setText("Busses");
compositeBus = new Composite(tabFolder, SWT.BORDER);
tbtmAddBusses.setControl(compositeBus);
compositeBus.setLayout(new GridLayout(2, false));
lblChooseBus = new Label(compositeBus, SWT.NONE);
lblChooseBus.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
lblChooseBus.setAlignment(SWT.RIGHT);
GridData gd_lblChooseBus = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
gd_lblChooseBus.widthHint = 88;
lblChooseBus.setLayoutData(gd_lblChooseBus);
lblChooseBus.setText("Select Bus:");
cmbBusses = new Combo(compositeBus, SWT.READ_ONLY);
cmbBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
cmbBusses.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1));
cmbBusses.add("NONE");
cmbBusses.setData(null);
cmbBusses.select(0);
lblSelectedCard = new Label(compositeBus, SWT.NONE);
lblSelectedCard.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
lblSelectedCard.setAlignment(SWT.RIGHT);
GridData gd_lblSelectedCard = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
gd_lblSelectedCard.widthHint = 93;
lblSelectedCard.setLayoutData(gd_lblSelectedCard);
lblSelectedCard.setText("Select Card:");
cmbCards = new Combo(compositeBus, SWT.READ_ONLY);
cmbCards.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
cmbCards.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnDeleteConnection = new Button(compositeBus, SWT.NONE);
btnDeleteConnection.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
btnDeleteConnection.setText("Delete Connection");
btnDeleteConnection.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnHideBusses = new Button(compositeBus, SWT.CHECK);
btnHideBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnHideBusses.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
btnHideBusses.setText("Show only busses of selected type");
btnHideBusses.setSelection(true);
StackLayout stackLayout = new StackLayout();
compositeDir = new Composite(composite, SWT.NONE);
compositeDir.setLayout(stackLayout);
compositeDir.setLayoutData(new RowData(382, SWT.DEFAULT));
lblInstanceDirections = new Label(compositeDir, SWT.NONE);
lblInstanceDirections.setFont(SWTResourceManager.getFont("Arial", 8, SWT.NORMAL));
lblInstanceDirections.setText("Select 'chip' to create a new part or 'sys-' to create a system\r\n"
+ "1. Select parent instance in Instance Tree\r\n"
+ "2. Select new instance type in dropdown\r\n"
+ "3. (Optional) Enter custom name\r\n" + "4. Click \"Add Instance\"");
lblInstanceDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
stackLayout.topControl = this.lblInstanceDirections;
lblBusDirections = new Label(compositeDir, SWT.NONE);
lblBusDirections.setFont(SWTResourceManager.getFont("Arial", 8, SWT.NORMAL));
lblBusDirections.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
lblBusDirections
.setText("Steps for adding a new connection:\r\n"
+ "1. Select a bus type from dropdown\r\n"
+ "2. Select the card on which the bus is on from dropdown\r\n"
+ "3. Navigate to connection source in Instances Tree view on left\r\n"
+ "4. Right-click on source and select \"Set Source\"\r\n"
+ "5. Navigate to connection destination\r\n6. Right-click on destination and select \"Add Connection\"");
listBusses = new List(sashForm, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
listBusses.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
this.addEvents();
this.setDirtyState(false);
// load file if passed on command line
if (!mrwFilename.isEmpty()) {
controller.readXML(mrwFilename);
setFilename(mrwFilename);
}
for (Target t : controller.getBusTypes()) {
cmbBusses.add(t.getType());
cmbBusses.setData(t.getType(), t);
}
attributes = new Vector<Field>();
this.initInstanceMode();
sashForm.setWeights(new int[] { 1, 1 });
columnName.pack();
return container;
}
protected void createButtonsForButtonBar(Composite parent) {
parent.setEnabled(false);
GridLayout layout = (GridLayout)parent.getLayout();
layout.marginHeight = 0;
}
protected void createButtonsForButtonBar2(Composite row1) {
row1.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
Button btnNew = createButton(row1, IDialogConstants.NO_ID, "New", false);
GridData gd_btnNew = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnNew.widthHint = 70;
btnNew.setLayoutData(gd_btnNew);
btnNew.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnNew.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (dirty) {
if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename
+ "has been modified. Ignore changes?")) {
return;
}
ServerWizard2.LOGGER.info("Discarding changes");
}
try {
controller.initModel();
setFilename("");
initInstanceMode();
setDirtyState(false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnOpen = createButton(row1, IDialogConstants.NO_ID, "Open...", false);
GridData gd_btnOpen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnOpen.widthHint = 70;
btnOpen.setLayoutData(gd_btnOpen);
btnOpen.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnOpen.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (dirty) {
if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename
+ "has been modified. Ignore changes?")) {
return;
}
ServerWizard2.LOGGER.info("Discarding changes");
}
Button b = (Button) e.getSource();
FileDialog fdlg = new FileDialog(b.getShell(), SWT.OPEN);
String ext[] = { "*.xml" };
fdlg.setFilterExtensions(ext);
String filename = fdlg.open();
if (filename == null) {
return;
}
Boolean dirty = controller.readXML(filename);
setFilename(filename);
initInstanceMode();
setDirtyState(dirty);
}
});
btnOpen.setToolTipText("Loads XML from file");
btnSave = createButton(row1, IDialogConstants.NO_ID, "Save", false);
GridData gd_btnSave = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnSave.widthHint = 70;
btnSave.setLayoutData(gd_btnSave);
btnSave.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String filename = mrwFilename;
if (mrwFilename.isEmpty()) {
Button b = (Button) e.getSource();
FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE);
String ext[] = { "*.xml" };
fdlg.setFilterExtensions(ext);
fdlg.setOverwrite(true);
filename = fdlg.open();
if (filename == null) {
return;
}
}
controller.writeXML(filename);
setFilename(filename);
setDirtyState(false);
}
});
btnSave.setText("Save");
btnSaveAs = createButton(row1, IDialogConstants.NO_ID, "Save As...", false);
GridData gd_btnSaveAs = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnSaveAs.widthHint = 70;
btnSaveAs.setLayoutData(gd_btnSaveAs);
btnSaveAs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.getSource();
FileDialog fdlg = new FileDialog(b.getShell(), SWT.SAVE);
String ext[] = { "*.xml" };
fdlg.setFilterExtensions(ext);
fdlg.setOverwrite(true);
String filename = fdlg.open();
if (filename == null) {
return;
}
controller.writeXML(filename);
setFilename(filename);
setDirtyState(false);
}
});
btnSaveAs.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnSaveAs.setEnabled(true);
label = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL);
GridData gd_sep = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_sep.heightHint = 30;
gd_sep.widthHint = 30;
label.setLayoutData(gd_sep);
btnClone = createButton(row1, IDialogConstants.NO_ID, "Manage Library", false);
GridData gd_btnClone = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnClone.widthHint = 110;
btnClone.setLayoutData(gd_btnClone);
btnClone.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnClone.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
GitDialog dlg = new GitDialog(btnClone.getShell());
dlg.open();
}
});
btnClone.setToolTipText("Retrieves Library from github");
btnOpenLib = createButton(row1, IDialogConstants.NO_ID, "Open Lib", false);
GridData gd_btnOpenLib = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnOpenLib.widthHint = 90;
btnOpenLib.setLayoutData(gd_btnOpenLib);
btnOpenLib.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnOpenLib.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.getSource();
DirectoryDialog fdlg = new DirectoryDialog(b.getShell(), SWT.OPEN);
fdlg.setFilterPath(ServerWizard2.getWorkingDir());
String libPath = fdlg.open();
if (libPath == null) {
return;
}
controller.loadLibrary(libPath);
}
});
btnOpenLib.setToolTipText("Loads External Library");
btnRunChecks = createButton(row1, IDialogConstants.NO_ID, "Export HTML", false);
GridData gd_btnRunChecks = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnRunChecks.widthHint = 90;
btnRunChecks.setLayoutData(gd_btnRunChecks);
btnRunChecks.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
String tempFile = System.getProperty("java.io.tmpdir")
+ System.getProperty("file.separator") + "~temp.xml";
controller.writeXML(tempFile);
String htmlFilename = mrwFilename;
htmlFilename = htmlFilename.replace(".xml", "") + ".html";
controller.runChecks(tempFile,htmlFilename);
}
});
btnRunChecks.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
Button btnForceUpdate = createButton(row1, IDialogConstants.NO_ID, "Force Update", false);
GridData gd_btnForceUpdate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnForceUpdate.widthHint = 90;
btnForceUpdate.setLayoutData(gd_btnForceUpdate);
btnForceUpdate.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnForceUpdate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
GithubFile.removeUpdateFile(true);
}
});
label_1 = new Label(buttonRow1, SWT.SEPARATOR | SWT.VERTICAL);
GridData gd_sep2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_sep2.heightHint = 30;
gd_sep2.widthHint = 30;
label_1.setLayoutData(gd_sep2);
Button btnExit = createButton(row1, IDialogConstants.CLOSE_ID, "Exit", false);
GridData gd_btnExit = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnExit.widthHint = 80;
btnExit.setLayoutData(gd_btnExit);
btnExit.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
btnExit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.getSource();
b.getShell().close();
}
});
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return new Point(933, 796);
}
// Utility helpers
private Target getSelectedTarget() {
if (tree.getSelectionCount() > 0) {
return (Target) tree.getSelection()[0].getData();
}
return null;
}
private void initBusMode() {
busMode = true;
this.lblBusDirections.setEnabled(true);
this.lblBusDirections.setVisible(true);
this.lblInstanceDirections.setVisible(false);
this.lblInstanceDirections.setEnabled(false);
// update card combo
cmbCards.removeAll();
this.targetForConnections = null;
for (Target target : controller.getConnectionCapableTargets()) {
cmbCards.add(target.getName());
cmbCards.setData(target.getName(), target);
}
if (cmbCards.getItemCount() > 0) {
cmbCards.select(-1);
}
for (TreeItem item : tree.getItems()) {
Target target = (Target) item.getData();
controller.hideBusses(target);
}
this.source = null;
this.dest = null;
this.selectedEndpoint = null;
refreshInstanceTree();
refreshConnections();
attributes.clear();
viewer.setInput(attributes);
viewer.refresh();
this.updateView();
}
private void initInstanceMode() {
tabFolder.setSelection(0);
busMode = false;
this.lblInstanceDirections.setEnabled(true);
this.lblInstanceDirections.setVisible(true);
this.lblBusDirections.setEnabled(false);
this.lblBusDirections.setVisible(false);
this.targetForConnections = null;
this.refreshInstanceTree();
this.listBusses.removeAll();
refreshConnections();
attributes.clear();
viewer.setInput(attributes);
viewer.refresh();
this.updateView();
}
private void updateChildCombo(Target targetInstance) {
btnAddTarget.setEnabled(false);
Vector<Target> v = controller.getChildTargets(targetInstance);
combo.removeAll();
if (v != null) {
for (Target target : v) {
combo.add(target.getType());
combo.setData(target.getType(), target);
}
if (combo.getItemCount() > 0) {
combo.select(0);
}
btnAddTarget.setEnabled(true);
}
}
/*
* Updates button enabled states based on if target is selected
* Also updates attribute table based on selected target
*/
private void updateView() {
Target targetInstance = getSelectedTarget();
if (targetInstance == null) {
btnAddTarget.setEnabled(false);
btnDeleteTarget.setEnabled(false);
btnCopyInstance.setEnabled(false);
btnDefaults.setEnabled(false);
updateChildCombo(null);
return;
}
updatePopupMenu(targetInstance);
updateChildCombo(targetInstance);
//A target is selected so show the associated attributes
TreeItem item = tree.getSelection()[0];
ConnectionEndpoint ep = this.getEndpoint(item, null);
attributes = controller.getAttributesAndGlobals(targetInstance, "/"+ep.getName());
viewer.setInput(attributes);
viewer.refresh();
if (targetInstance.isSystem()) {
btnDeleteTarget.setEnabled(false);
} else {
btnDeleteTarget.setEnabled(true);
}
if (targetInstance.isNode() || targetInstance.isConnector()) {
btnCopyInstance.setEnabled(true);
} else {
btnCopyInstance.setEnabled(false);
}
btnDefaults.setEnabled(true);
}
/*
* Creates right-click popup menu for adding connections
*
*/
private void updatePopupMenu(Target selectedTarget) {
if (selectedTarget == null || tree.getSelectionCount()==0) {
return;
}
if (popupMenu != null) {
popupMenu.dispose();
}
popupMenu = new Menu(tree);
if (busMode) {
if (cmbBusses.getSelectionIndex() > 0) {
if (targetForConnections != null && selectedTarget.getAttribute("CLASS").equals("UNIT")) {
if (selectedTarget.isOutput()) {
MenuItem srcItem = new MenuItem(popupMenu, SWT.NONE);
srcItem.setText("Set Source");
srcItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
source = getEndpoint(true);
}
});
}
}
if (source != null && selectedTarget.isInput()) {
MenuItem connItem = new MenuItem(popupMenu, SWT.NONE);
connItem.setText("Add Connection");
connItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
dest = getEndpoint(false);
addConnection(false);
}
});
MenuItem cableItem = new MenuItem(popupMenu, SWT.NONE);
cableItem.setText("Add Cable");
cableItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
dest = getEndpoint(false);
addConnection(true);
}
});
}
} else {
targetForConnections = null;
source = null;
dest = null;
}
}
TreeItem item = tree.getSelection()[0];
TreeItem parentItem = item.getParentItem();
if (parentItem != null) {
Target configParentTarget = (Target) parentItem.getData();
if (configParentTarget.attributeExists("IO_CONFIG_SELECT")) {
MenuItem deconfigItem = new MenuItem(popupMenu, SWT.NONE);
deconfigItem.setText("Deconfig");
deconfigItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setConfig(false);
}
});
MenuItem configItem = new MenuItem(popupMenu, SWT.NONE);
configItem.setText("Select Config");
configItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setConfig(true);
}
});
}
}
tree.setMenu(popupMenu);
}
public void setConfig(boolean config) {
TreeItem item = tree.getSelection()[0];
Target target = (Target) item.getData();
TreeItem parentItem = item.getParentItem();
if (parentItem == null) {
ServerWizard2.LOGGER.warning(target.getName() + " parent is null");
return;
}
TreeItem grandParentItem = parentItem.getParentItem();
Target configParentTarget = (Target) parentItem.getData();
String configNum = target.getAttribute("IO_CONFIG_NUM");
if (configNum.isEmpty()) {
ServerWizard2.LOGGER.warning(target.getName() + " IO_CONFIG_NUM attribute is empty");
return;
}
ConnectionEndpoint ep = getEndpoint(parentItem,null);
String path = "/"+ep.getName();
if (config) {
controller.setGlobalSetting(path, "IO_CONFIG_SELECT", configNum);
} else {
controller.setGlobalSetting(path, "IO_CONFIG_SELECT", "0");
}
for (TreeItem childItem : parentItem.getItems()) {
clearTree(childItem);
}
currentPath="/"+ep.getPath();
currentPath=currentPath.substring(0, currentPath.length()-1);
this.updateInstanceTree(configParentTarget, grandParentItem, parentItem);
}
private ConnectionEndpoint getEndpoint(TreeItem item, String stopCard) {
ConnectionEndpoint endpoint = new ConnectionEndpoint();
Target target = (Target) item.getData();
endpoint.setTargetName(target.getName());
Boolean done = false;
Boolean found = false;
TreeItem parentItem = item.getParentItem();
while (!done) {
if (parentItem==null) {
done=true;
} else {
Target parentTarget = (Target) parentItem.getData();
String parentName = parentTarget.getName();
if (parentName.equals(stopCard)) {
done = true;
found = true;
} else {
endpoint.setPath(parentName + "/" + endpoint.getPath());
parentItem = parentItem.getParentItem();
}
}
}
if (!found && stopCard != null) {
MessageDialog.openError(null, "Connection Error", "The connection must start and end on or below selected card.");
endpoint=null;
}
return endpoint;
}
private ConnectionEndpoint getEndpoint(boolean setBold) {
TreeItem item = tree.getSelection()[0];
ConnectionEndpoint endpoint = getEndpoint(item,cmbCards.getText());
if (setBold && endpoint != null) {
setEndpointState(item);
}
return endpoint;
}
public void setEndpointState(TreeItem item) {
if (item != selectedEndpoint && selectedEndpoint != null) {
this.setFontStyle(selectedEndpoint, SWT.BOLD, false);
}
this.setFontStyle(item, SWT.BOLD | SWT.ITALIC, true);
selectedEndpoint = item;
}
private void clearTreeAll() {
if (tree.getItemCount() > 0) {
clearTree(tree.getItem(0));
}
tree.removeAll();
}
private void clearTree(TreeItem treeitem) {
for (int i = 0; i < treeitem.getItemCount(); i++) {
clearTree(treeitem.getItem(i));
}
treeitem.removeAll();
treeitem.dispose();
}
private void refreshInstanceTree() {
currentPath="";
targetFound = false;
for (Target target : controller.getRootTargets()) {
this.updateInstanceTree(target, null);
}
if (controller.getRootTargets().size() == 0) {
this.clearTreeAll();
}
btnAddTarget.setEnabled(false);
}
public void updateInstanceTree(Target target, TreeItem parentItem) {
this.updateInstanceTree(target, parentItem, null);
}
private void updateInstanceTree(Target target, TreeItem parentItem, TreeItem item) {
if (target == null) {
return;
}
if (target.isHidden()) {
return;
}
if (parentItem==null) {
this.clearTreeAll();
}
boolean hideBus = false;
String name = target.getName();
String lastPath = currentPath;
currentPath=currentPath+"/"+name;
if (busMode) {
if (!target.isSystem() && !cmbBusses.getText().equals("NONE")) {
if (target.isBusHidden(cmbBusses.getText())) {
hideBus = true;
if (btnHideBusses.getSelection()) {
currentPath=lastPath;
return;
}
}
}
if (parentItem != null) {
if (controller.isGlobalSettings(lastPath, "IO_CONFIG_SELECT")) {
Field cnfgSelect = controller.getGlobalSetting(lastPath, "IO_CONFIG_SELECT");
if (!cnfgSelect.value.isEmpty() && !cnfgSelect.value.equals("0")) {
String cnfg = target.getAttribute("IO_CONFIG_NUM");
if (!cnfg.equals(cnfgSelect.value)) {
hideBus = true;
if (btnHideBusses.getSelection()) {
currentPath=lastPath;
return;
}
}
}
}
}
if (!hideBus) {
String sch = target.getAttribute("SCHEMATIC_INTERFACE");
if (!sch.isEmpty()) {
name = name + " (" + sch + ")";
}
if (target.isInput() && target.isOutput()) {
name = name + " <=>";
} else if (target.isInput()) {
name = name + " <=";
} else if (target.isOutput()) {
name = name + " =>";
}
}
}
Vector<Target> children = controller.getVisibleChildren(target,this.btnShowHidden.getSelection());
TreeItem treeitem = item;
if (item == null) {
if (parentItem == null) {
treeitem = new TreeItem(tree, SWT.VIRTUAL | SWT.BORDER);
} else {
treeitem = new TreeItem(parentItem, SWT.VIRTUAL | SWT.BORDER);
}
}
treeitem.setText(name);
treeitem.setData(target);
if (target.isPluggable()) {
this.setFontStyle(treeitem, SWT.ITALIC, true);
}
if (children != null) {
for (int i = 0; i < children.size(); i++) {
Target childTarget = children.get(i);
updateInstanceTree(childTarget, treeitem);
}
}
if (target == targetForConnections && busMode) {
this.setFontStyle(treeitem, SWT.BOLD, true);
if (!targetFound) {
tree.select(treeitem);
for (TreeItem childItem : treeitem.getItems()) {
tree.showItem(childItem);
}
targetFound = true;
}
}
currentPath=lastPath;
}
private void addConnection(Connection conn) {
listBusses.add(conn.getName());
listBusses.setData(conn.getName(), conn);
}
private void refreshConnections() {
this.source=null;
this.dest=null;
listBusses.removeAll();
if (cmbBusses == null) {
return;
}
Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText());
if (targetForConnections == null) {
return;
}
if (busTarget == null) {
for (Target tmpBusTarget : targetForConnections.getBusses().keySet()) {
for (Connection conn : targetForConnections.getBusses().get(tmpBusTarget)) {
addConnection(conn);
}
}
} else {
for (Connection conn : targetForConnections.getBusses().get(busTarget)) {
addConnection(conn);
}
}
}
private void addConnection(Boolean cabled) {
Target busTarget = (Target) cmbBusses.getData(cmbBusses.getText());
Connection conn = targetForConnections.addConnection(busTarget, source, dest, cabled);
this.addConnection(conn);
setDirtyState(true);
}
private void deleteConnection() {
if (targetForConnections == null || listBusses.getSelectionCount() == 0) {
return;
}
Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]);
controller.deleteConnection(targetForConnections, conn.busTarget, conn);
this.refreshConnections();
setDirtyState(true);
}
private void setFontStyle(TreeItem item, int style, boolean selected) {
if (item.isDisposed()) {
return;
}
FontData[] fD = item.getFont().getFontData();
fD[0].setStyle(selected ? style : 0);
Font newFont = new Font(this.getShell().getDisplay(), fD[0]);
item.setFont(newFont);
}
@Override
public boolean close() {
if (dirty) {
if (!MessageDialog.openConfirm(null, "Save Resource", mrwFilename
+ "has been modified. Ignore changes?")) {
return false;
}
ServerWizard2.LOGGER.info("Discarding changes and exiting...");
}
clearTreeAll();
for (Control c : container.getChildren()) {
c.dispose();
}
return super.close();
}
public void setDirtyState(Boolean dirty) {
this.dirty = dirty;
if (this.btnSave != null) {
this.btnSave.setEnabled(dirty);
}
if (dirty) {
this.getShell().setText("ServerWiz2 - " + this.mrwFilename + " *");
} else {
this.getShell().setText("ServerWiz2 - " + this.mrwFilename);
}
}
public void setFilename(String filename) {
this.mrwFilename = filename;
if (btnSave != null) {
this.btnSave.setEnabled(true);
}
this.getShell().setText("ServerWiz2 - " + this.mrwFilename);
}
private void addEvents() {
btnShowHidden.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
refreshInstanceTree();
}
});
tabFolder.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
if (tabFolder.getSelection()[0]==tbtmAddBusses) {
initBusMode();
} else {
initInstanceMode();
}
}
});
tree.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateView();
}
});
tree.addListener(SWT.Expand, new Listener() {
public void handleEvent(Event e) {
final TreeItem treeItem = (TreeItem) e.item;
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if (!treeItem.isDisposed()) {
treeItem.getParent().getColumns()[0].pack();
}
}
});
}
});
btnAddTarget.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Target chk = (Target) combo.getData(combo.getText());
if (chk != null) {
TreeItem selectedItem = null;
Target parentTarget = null;
if (tree.getSelectionCount() > 0) {
selectedItem = tree.getSelection()[0];
parentTarget = (Target) selectedItem.getData();
}
if (chk.getType().equals("chip") || chk.getType().equals("targetoverride")) {
ServerWizard2.LOGGER.info("Entering model creation mode");
attributeEditor.setIgnoreReadonly();
controller.setModelCreationMode();
tbtmAddBusses.dispose();
}
String nameOverride = txtInstanceName.getText();
controller.addTargetInstance(chk, parentTarget, selectedItem, nameOverride);
txtInstanceName.setText("");
if (tree.getSelectionCount() > 0) {
selectedItem.setExpanded(true);
}
columnName.pack();
setDirtyState(true);
}
}
});
btnDeleteTarget.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TreeItem treeitem = tree.getSelection()[0];
if (treeitem == null) {
return;
}
controller.deleteTarget((Target) treeitem.getData());
clearTree(treeitem);
setDirtyState(true);
}
});
btnCopyInstance.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
TreeItem selectedItem = tree.getSelection()[0];
if (selectedItem == null) {
return;
}
Target target = (Target) selectedItem.getData();
Target parentTarget = (Target) selectedItem.getParentItem().getData();
Target newTarget = controller.copyTargetInstance(target, parentTarget, true);
updateInstanceTree(newTarget, selectedItem.getParentItem());
TreeItem t = selectedItem.getParentItem();
tree.select(t.getItem(t.getItemCount() - 1));
setDirtyState(true);
}
});
btnDefaults.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
TreeItem selectedItem = tree.getSelection()[0];
if (selectedItem == null) {
return;
}
if (!MessageDialog.openConfirm(null, "Restore Defaults", "Are you sure you want to restore default attribute values on this target and all of it's children?")) {
return;
}
ServerWizard2.LOGGER.info("Restoring Defaults");
Target target = (Target) selectedItem.getData();
controller.deepCopyAttributes(target);
setDirtyState(true);
}
});
cmbCards.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Target t = (Target) cmbCards.getData(cmbCards.getText());
targetForConnections = t;
refreshInstanceTree();
refreshConnections();
}
});
cmbBusses.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
refreshInstanceTree();
refreshConnections();
}
});
btnDeleteConnection.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
deleteConnection();
}
});
listBusses.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
if (listBusses.getSelectionCount() > 0) {
Connection conn = (Connection) listBusses.getData(listBusses.getSelection()[0]);
attributes = controller.getAttributesAndGlobals(conn.busTarget, "");
viewer.setInput(attributes);
viewer.refresh();
}
}
});
btnHideBusses.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
refreshInstanceTree();
refreshConnections();
}
});
}
private void createAttributeTable() {
Table table = viewer.getTable();
ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE);
table.setHeaderVisible(true);
table.setLinesVisible(true);
table.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL));
table.addListener(SWT.CHANGED, new Listener() {
public void handleEvent(Event event) {
setDirtyState(true);
}
});
final TableViewerColumn colName = new TableViewerColumn(viewer, SWT.NONE);
colName.getColumn().setWidth(256);
colName.getColumn().setText("Attribute");
colName.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Field f = (Field) element;
return f.attributeName;
}
});
final TableViewerColumn colField = new TableViewerColumn(viewer, SWT.NONE);
colField.getColumn().setWidth(100);
colField.getColumn().setText("Field");
colField.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Field f = (Field) element;
if (f.attributeName.equals(f.name)) {
return "";
}
return f.name;
}
});
final TableViewerColumn colValue = new TableViewerColumn(viewer, SWT.NONE);
colValue.getColumn().setWidth(100);
colValue.getColumn().setText("Value");
colValue.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Field f = (Field) element;
return f.value;
}
});
attributeEditor = new AttributeEditingSupport(viewer);
colValue.setEditingSupport(attributeEditor);
final TableViewerColumn colDesc = new TableViewerColumn(viewer, SWT.NONE);
colDesc.getColumn().setWidth(350);
colDesc.getColumn().setText("Description");
colDesc.setLabelProvider(new ColumnLabelProvider() {
public String getToolTipText(Object element) {
Field f = (Field) element;
return f.desc;
}
@Override
public String getText(Object element) {
Field f = (Field) element;
String desc = f.desc.replace("\n", "");
return desc;
}
});
final TableViewerColumn colGroup = new TableViewerColumn(viewer, SWT.NONE);
colGroup.getColumn().setWidth(120);
colGroup.getColumn().setText("Group");
colGroup.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Field f = (Field) element;
return f.group;
}
});
viewer.setContentProvider(ArrayContentProvider.getInstance());
}
} |
package com.irccloud.android;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@SuppressLint("UseSparseArrays")
public class EventsDataSource {
public class Event {
int cid;
int bid;
long eid;
String timestamp;
String type;
String msg;
String hostmask;
String from;
String nick;
String old_nick;
String server;
String diff;
String html;
boolean highlight;
boolean self;
int color;
int bg_color;
JsonObject ops;
long group_eid;
int row_type;
String group_msg;
}
public class comparator implements Comparator<Event> {
public int compare(Event e1, Event e2) {
long l1 = e1.eid, l2 = e2.eid;
if(l1 == l2)
return 0;
else if(l1 > l2)
return 1;
else return -1;
}
}
private HashMap<Integer,TreeMap<Long, Event>> events;
private static EventsDataSource instance = null;
public long highest_eid = -1;
public static EventsDataSource getInstance() {
if(instance == null)
instance = new EventsDataSource();
return instance;
}
public EventsDataSource() {
events = new HashMap<Integer,TreeMap<Long, Event>>();
}
public void clear() {
synchronized(events) {
events.clear();
}
}
public Event addEvent(IRCCloudJSONObject event) {
synchronized(events) {
if(!events.containsKey(event.bid()))
events.put(event.bid(), new TreeMap<Long,Event>());
Event e = new Event();
e.cid = event.cid();
e.bid = event.bid();
e.eid = event.eid();
e.type = event.type();
e.msg = event.getString("msg");
e.hostmask = event.getString("hostmask");
e.from = event.getString("from");
if(event.has("newnick"))
e.nick = event.getString("newnick");
else
e.nick = event.getString("nick");
e.old_nick = event.getString("oldnick");
e.server = event.getString("server");
e.diff = event.getString("diff");
e.highlight = event.getBoolean("highlight");
e.self = event.getBoolean("self");
e.ops = event.getJsonObject("ops");
e.color = R.color.row_message_label;
e.bg_color = R.color.message_bg;
e.row_type = 0;
e.html = null;
e.group_msg = null;
if(e.from != null)
e.from = TextUtils.htmlEncode(e.from);
if(e.msg != null)
e.msg = TextUtils.htmlEncode(e.msg);
if(e.type.equalsIgnoreCase("socket_closed")) {
e.row_type = MessageViewFragment.ROW_SOCKETCLOSED;
e.bg_color = R.drawable.socketclosed_bg;
} else if(e.type.equalsIgnoreCase("buffer_me_msg")) {
e.from = "* <i>" + e.from + "</i>";
e.msg = "<i>" + e.msg + "</i>";
} else if(e.type.equalsIgnoreCase("too_fast")) {
e.from = "";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("no_bots")) {
e.from = "";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("nickname_in_use")) {
e.from = event.getString("nick");
e.msg = "is already in use";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("unhandled_line") || e.type.equalsIgnoreCase("unparsed_line")) {
e.from = "";
e.msg = "";
if(event.has("command"))
e.msg = event.getString("command") + " ";
if(event.has("raw"))
e.msg += event.getString("raw");
else
e.msg += event.getString("msg");
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("connecting_cancelled")) {
e.from = "";
e.msg = "Cancelled";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("connecting_failed")) {
e.from = "";
e.msg = "Failed to connect: " + event.getString("reason");
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("quit_server")) {
e.from = "";
e.msg = "⇐ You disconnected";
e.color = R.color.timestamp;
} else if(e.type.equalsIgnoreCase("self_details")) {
e.from = "";
e.msg = "Your hostmask: <b>" + event.getString("usermask") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("myinfo")) {
e.from = "";
e.msg = "Host: " + event.getString("server") + "\n";
e.msg += "IRCd: " + event.getString("version") + "\n";
e.msg += "User modes: " + event.getString("user_modes") + "\n";
e.msg += "Channel modes: " + event.getString("channel_modes") + "\n";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("wait")) {
e.from = "";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("user_mode")) {
e.from = "";
e.msg = "Your user mode is: <b>" + event.getString("diff") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("your_unique_id")) {
e.from = "";
e.msg = "Your unique ID is: <b>" + event.getString("unique_id") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("kill")) {
e.from = "";
e.msg = "You were killed";
if(event.has("from"))
e.msg += " by " + event.getString("from");
if(event.has("killer_hostmask"))
e.msg += " (" + event.getString("killer_hostmask") + ")";
if(event.has("reason"))
e.msg += ": " + event.getString("reason");
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("banned")) {
e.from = "";
e.msg = "You were banned";
if(event.has("server"))
e.msg += " from " + event.getString("server");
if(event.has("reason"))
e.msg += ": " + event.getString("reason");
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("channel_topic")) {
e.from = event.getString("author");
e.msg = "set the topic: " + event.getString("topic");
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("channel_mode")) {
e.from = "";
e.msg = "Channel mode set to: <b>" + event.getString("diff") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("channel_mode_is")) {
e.from = "";
if(event.getString("diff") != null && event.getString("diff").length() > 0)
e.msg = "Channel mode is: <b>" + event.getString("diff") + "</b>";
else
e.msg = "No channel mode";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("kicked_channel") || e.type.equalsIgnoreCase("you_kicked_channel")) {
e.from = "← " + event.getString("nick");
e.msg = "was kicked by " + event.getString("kicker") + " (" + event.getString("kicker_hostmask") + ")";
e.color = R.color.timestamp;
} else if(e.type.equalsIgnoreCase("channel_mode_list_change")) {
e.msg = "set mode: <b>" + event.getString("diff") + "</b>";
e.color = R.color.timestamp;
} else if(e.type.equalsIgnoreCase("motd_response") || e.type.equalsIgnoreCase("server_motd")) {
JsonArray lines = event.getJsonArray("lines");
e.from = "";
if(lines != null) {
e.msg = "<pre>";
for(int i = 0; i < lines.size(); i++) {
e.msg += TextUtils.htmlEncode(lines.get(i).getAsString()).replace(" ", " ") + "<br/>";
}
e.msg += "</pre>";
}
e.bg_color = R.color.self;
} else if(e.type.equalsIgnoreCase("notice")) {
e.bg_color = R.color.notice;
} else if(e.type.toLowerCase().startsWith("server_")) {
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("inviting_to_channel")) {
e.from = "";
e.msg = "You invited " + event.getString("recipient") + " to join " + event.getString("channel");
e.bg_color = R.color.notice;
}
if(event.has("value")) {
e.msg = event.getString("value") + " " + e.msg;
}
if(event.has("highlight") && event.getBoolean("highlight"))
e.bg_color = R.color.highlight;
if(event.has("self") && event.getBoolean("self"))
e.bg_color = R.color.self;
if(e.msg != null && e.msg .length() > 0)
e.msg = ColorFormatter.irc_to_html(e.msg);
events.get(event.bid()).put(e.eid, e);
if(highest_eid < event.eid())
highest_eid = event.eid();
return e;
}
}
public Event getEvent(long eid, int bid) {
synchronized(events) {
if(events.containsKey(bid))
return events.get(bid).get(eid);
}
return null;
}
public void deleteEvent(long eid, int bid) {
synchronized(events) {
if(events.containsKey(bid) && events.get(bid).containsKey(eid))
events.get(bid).remove(eid);
}
}
public void deleteEventsForBuffer(int bid) {
synchronized(events) {
if(events.containsKey(bid))
events.remove(bid);
}
}
public TreeMap<Long,Event> getEventsForBuffer(int bid) {
synchronized(events) {
if(events.containsKey(bid)) {
return events.get(bid);
}
}
return null;
}
public int getUnreadCountForBuffer(int bid, long last_seen_eid, String buffer_type) {
int count = 0;
synchronized(events) {
if(events.containsKey(bid)) {
Iterator<Event> i = events.get(bid).values().iterator();
while(i.hasNext()) {
Event e = i.next();
try {
if(e.eid > last_seen_eid && isImportant(e, buffer_type))
count++;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
return count;
}
private boolean isImportant(Event e, String buffer_type) {
if(e == null) {
Log.w("IRCCloud", "isImportant: NULL event");
return false;
}
String type = e.type;
if(type == null) {
Log.w("IRCCloud", "isImportant: NULL type");
return false;
}
return (type.equals("buffer_msg") || type.equals("buffer_me_msg")
|| (type.equals("notice") && buffer_type != null && (!buffer_type.equals("console") || !(e.server != null && !e.server.equals("undefined")))));
}
public synchronized int getHighlightCountForBuffer(int bid, long last_seen_eid, String buffer_type) {
int count = 0;
synchronized(events) {
if(events.containsKey(bid)) {
Iterator<Event> i = events.get(bid).values().iterator();
while(i.hasNext()) {
Event e = i.next();
try {
if(e.eid > last_seen_eid && isImportant(e, buffer_type) && (e.highlight || buffer_type.equalsIgnoreCase("conversation")))
count++;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
return count;
}
} |
package com.lurencun.http;
import com.lurencun.http.assist.ThreadPoolManager;
/**
* @author :
* @email : chenyoca@gmail.com
* @date : 2012-10-22
* @desc : An asynchronous multithread http connection framework.
*/
public class AsyncHttpConnection {
public final static String VERSION = "1.0.3";
private AsyncHttpConnection(){}
private static class SingletonProvider {
private static AsyncHttpConnection instance = new AsyncHttpConnection();
}
public static AsyncHttpConnection getInstance(){
return SingletonProvider.instance;
}
private final ThreadPoolManager threadPoolMng = new ThreadPoolManager();
/**
* Send a 'get' request to url with params, response on callback
* @param url
* @param params
* @param callback
* @return request id
*
*/
public int get(String url,ParamsWrapper params,ResponseCallback callback){
return get(url, params, null,callback);
}
/**
* Send a 'get' request to url with params & <b>TOKEN</b> , response on callback. The <b>TOKEN</b> object
* will be back to callback <i>ResponseCallback.onResponse(InputStream response,URL url,Object token)</i>
* as an identify of this request. You can put a object like '12345' to mark your request.
* @param url
* @param params
* @param token
* @param callback
* @return request id
*
*/
public int get(String url,ParamsWrapper params,Object token,ResponseCallback callback){
verifyParams(url,callback);
return sendRequest(RequestInvoker.METHOD_GET,url,params,token,callback);
}
/**
* Send a 'post' request to url with params, response on callback
* @param url
* @param params
* @param callback
* @return request id
*
*/
public int post(String url,ParamsWrapper params,ResponseCallback callback){
return post(url, params, null,callback);
}
/**
* Send a 'post' request to url with params & <b>TOKEN</b> , response on callback. The <b>TOKEN</b> object
* will be back to callback <i>ResponseCallback.onResponse(InputStream response,URL url,Object token)</i>
* as an identify of this request. You can put a object like '12345' to mark your request.
* @param url
* @param params
* @param token
* @param callback
* @return request id
*
*/
public int post(String url,ParamsWrapper params,Object token,ResponseCallback callback){
verifyParams(url,callback);
return sendRequest(RequestInvoker.METHOD_POST,url,params,token,callback);
}
/**
* Destory async http connection. All the requests(finished or not) will be interrupt immediately.
*/
public void destory(){
threadPoolMng.destory();
}
private void verifyParams(String url,ResponseCallback callback){
if(callback == null) throw new IllegalArgumentException("ResponseCallback cannot be null");
if(url == null) throw new IllegalArgumentException("Connection url cannot be null");
}
private int sendRequest(String method,String url,ParamsWrapper params,Object token,ResponseCallback handler){
if(url == null) return ThreadPoolManager.INALID_REQUEST;
return threadPoolMng.submit(InvokerFactory.obtain(method, url, params, token, handler));
}
} |
package com.trendrr.strest.server;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.DynMap;
import com.trendrr.oss.DynMapFactory;
import com.trendrr.oss.Reflection;
import com.trendrr.strest.server.routing.MatchedRoute;
import com.trendrr.strest.server.routing.RouteMatcher;
import com.trendrr.strest.server.routing.UriMapping;
/**
*
* handles the conversion from a route to a class.
*
* @author dustin
*
*/
public class RouteLookup {
protected Log log = LogFactory.getLog(RouteLookup.class);
RouteMatcher matcher = new RouteMatcher();
public void addRoute(String route, Class<StrestController> cls) {
matcher.addMapping(new UriMapping(route, cls));
}
/**
* Finds the controller based on the URI param.
*
* Also parses any params on the uri
* @param uri
* @return
*/
public StrestController find(String uri) {
if (uri.startsWith("http:
//sometimes the host shows up in the uri
uri.replaceFirst("http\\:\\/\\/[^\\/]+\\/", "/");
}
int queryIndex = uri.indexOf('?');
if (queryIndex != -1) {
uri = uri.substring(0, queryIndex);
}
MatchedRoute route = matcher.find(uri);
if (route == null)
return null;
Class cls = route.getMapping().getCls();
if (cls == null)
return null;
try {
StrestController controller = (StrestController)Reflection.defaultInstance(cls);
controller.params.putAll(route.getParams());
return controller;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} |
package com.trendrr.strest.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.Reflection;
import com.trendrr.strest.server.routing.MatchedRoute;
import com.trendrr.strest.server.routing.RouteMatcher;
import com.trendrr.strest.server.routing.UriMapping;
/**
*
* handles the conversion from a route to a class.
*
* @author dustin
*
*/
public class RouteLookup {
protected Log log = LogFactory.getLog(RouteLookup.class);
RouteMatcher matcher = new RouteMatcher();
public void addRoute(String route, Class<StrestController> cls) {
matcher.addMapping(new UriMapping(route, cls));
}
/**
* Finds the controller based on the URI param.
*
* Also parses any params on the uri
* @param uri
* @return
*/
public StrestController find(String uri) {
if (uri.startsWith("http:
//sometimes the host shows up in the uri
uri.replaceFirst("http\\:\\/\\/[^\\/]+\\/", "/");
}
int queryIndex = uri.indexOf('?');
if (queryIndex != -1) {
uri = uri.substring(0, queryIndex);
}
MatchedRoute route = matcher.find(uri);
if (route == null)
return null;
Class cls = route.getMapping().getCls();
if (cls == null)
return null;
try {
StrestController controller = (StrestController)Reflection.defaultInstance(cls);
controller.params.putAll(route.getParams());
return controller;
} catch (Exception e) {
log.error("Caught" ,e);
}
return null;
}
} |
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.SOAPException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.lang.Constants;
import jolie.Interpreter;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.JolieGWTConverter;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.protocols.SequentialCommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.InputOperation;
import jolie.runtime.InvalidIdException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.xml.XmlUtils;
import joliex.gwt.client.JolieService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
*/
public class HttpProtocol extends SequentialCommProtocol
{
private static class Parameters {
private static String DEBUG = "debug";
}
private String inputId = null;
final private Transformer transformer;
final private DocumentBuilderFactory docBuilderFactory;
final private DocumentBuilder docBuilder;
final private URI uri;
private boolean received = false;
final public static String CRLF = new String( new char[] { 13, 10 } );
public String name()
{
return "http";
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
Transformer transformer,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
) {
super( configurationPath );
this.uri = uri;
this.transformer = transformer;
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$";
private static void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() );
StringBuilder cookieSB = new StringBuilder();
String domain;
// TODO check for cookie expiration
for( Value v : cookieVec ) {
domain = v.getChildren( "domain" ).first().strValue();
if ( domain.isEmpty() ||
(!domain.isEmpty() && hostname.endsWith( domain )) ) {
cookieSB.append(
v.getChildren( "name" ).first().strValue() + "=" +
v.getChildren( "value" ).first().strValue() + "; "
);
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder.append( "Cookie: " );
headerBuilder.append( cookieSB );
headerBuilder.append( CRLF );
}
}
private static void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() );
// TODO check for cookie expiration
for( Value v : cookieVec ) {
headerBuilder.append( "Set-Cookie: " +
v.getFirstChild( "name" ).strValue() + "=" +
v.getFirstChild( "value" ).strValue() + "; " +
"expires=" + v.getFirstChild( "expires" ).strValue() + "; " +
"path=" + v.getFirstChild( "path" ).strValue() + "; " +
"domain=" + v.getFirstChild( "domain" ).strValue() +
( (v.getFirstChild( "secure" ).intValue() > 0) ? "; secure" : "" ) +
CRLF
);
}
}
private String requestFormat = null;
private static CharSequence parseAlias( String alias, Value value )
{
int offset = 0;
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
currKey = alias.substring( m.start()+2, m.end()-1 );
currStrValue = value.getFirstChild( currKey ).strValue();
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
return result;
}
private String send_getCharset( CommMessage message )
{
String charset = null;
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.CHARSET.token().content() ) ) {
charset = message.value().getFirstChild( jolie.lang.Constants.Predefined.CHARSET.token().content() ).strValue();
} else if ( hasParameter( "charset" ) ) {
charset = getStringParameter( "charset" );
}
return charset;
}
private String send_getFormat( CommMessage message )
{
String format = "xml";
if ( received && requestFormat != null ) {
format = requestFormat;
requestFormat = null;
} else if ( message.value().hasChildren( jolie.lang.Constants.Predefined.FORMAT.token().content() ) ) {
format = message.value().getFirstChild( jolie.lang.Constants.Predefined.FORMAT.token().content() ).strValue();
} else if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
return format;
}
private class EncodedContent {
private ByteArray content = null;
private String contentType = null;
}
private EncodedContent send_encodeContent( CommMessage message, String charset, String format )
throws IOException
{
if ( charset == null ) {
charset = "UTF8";
}
EncodedContent ret = new EncodedContent();
if ( "xml".equals( format ) ) {
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( received ) ? "Response" : "") );
doc.appendChild( root );
valueToDocument( message.value(), root, doc );
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toByteArray() );
ret.contentType = "text/xml";
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray)message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
ret.contentType = "text/html";
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" + BOUNDARY + CRLF );
builder.append( "Content-Disposition: form-data; name=\"" + entry.getKey() + '\"' + CRLF + CRLF );
builder.append( entry.getValue().first().strValue() + CRLF );
}
}
builder.append( "--" + BOUNDARY + "--" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
Entry< String, ValueVector > entry;
StringBuilder builder = new StringBuilder();
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() + "=" + URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
}
return ret;
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
String redirect = message.value().getFirstChild( Constants.Predefined.REDIRECT.token().content() ).strValue();
if ( redirect.isEmpty() ) {
headerBuilder.append( "HTTP/1.1 200 OK" + CRLF );
} else {
headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF );
headerBuilder.append( "Location: " + redirect + CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
}
private void send_appendRequestMethod( StringBuilder headerBuilder )
{
if ( hasParameter( "method" ) ) {
headerBuilder.append( getStringParameter( "method" ).toUpperCase() );
} else {
headerBuilder.append( "GET" );
}
}
private void send_appendRequestPath( CommMessage message, StringBuilder headerBuilder )
{
if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
if ( uri.toString().endsWith( "/" ) == false ) {
headerBuilder.append( '/' );
}
if (
hasParameter( "aliases" ) &&
getParameterFirstValue( "aliases" ).hasChildren( message.operationName() )
) {
headerBuilder.append(
parseAlias(
getParameterFirstValue( "aliases" ).getFirstChild( message.operationName() ).strValue(),
message.value()
)
);
} else {
headerBuilder.append( message.operationName() );
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " + userpass + CRLF );
}
}
private void send_appendRequestHeaders( CommMessage message, StringBuilder headerBuilder )
{
send_appendRequestMethod( headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, headerBuilder );
headerBuilder.append( " HTTP/1.1" + CRLF );
headerBuilder.append( "Host: " + uri.getHost() + CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
{
String param;
if ( checkBooleanParameter( "keepAlive" ) ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + CRLF );
}
if ( encodedContent.content != null ) {
param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TYPE.token().content() ).strValue();
if ( !param.isEmpty() ) {
encodedContent.contentType = param;
}
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( CRLF );
param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TRANSFER_ENCODING.token().content() ).strValue();
if ( !param.isEmpty() ) {
headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent )
{
if ( checkBooleanParameter( "debug" ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString() );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
String charset = send_getCharset( message );
String format = send_getFormat( message );
EncodedContent encodedContent = send_encodeContent( message, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( received ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
received = false;
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, headerBuilder );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( CRLF );
send_logDebugInfo( headerBuilder, encodedContent );
inputId = message.operationName();
if ( charset == null ) {
charset = "UTF8";
}
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null ) {
ostream.write( encodedContent.content.getBytes() );
ostream.write( CRLF.getBytes( charset ) );
}
ostream.flush();
}
private void parseXML( HttpMessage message, Value value )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseForm( HttpMessage message, Value value )
throws IOException
{
String line = new String( message.content(), "UTF8" );
String[] s, pair;
s = line.split( "&" );
for( int i = 0; i < s.length; i++ ) {
pair = s[i].split( "=", 2 );
value.getChildren( pair[0] ).first().setValue( pair[1] );
}
}
private static void parseMultiPartFormData( HttpMessage message, Value value )
throws IOException
{
MultiPartFormDataParser parser = new MultiPartFormDataParser( message, value );
parser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private static void recv_checkForSetCookie( HttpMessage message, Value value )
{
ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() );
Value currValue;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );
}
}
private static void recv_checkForCookies( HttpMessage message, Value value )
{
ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() );
Value v;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
v = Value.create();
v.getNewChild( "name" ).setValue( entry.getKey() );
v.getNewChild( "value" ).setValue( entry.getValue() );
cookieVec.add( v );
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
if ( message.requestPath() != null ) {
try {
Value qsValue = value.getFirstChild( Constants.Predefined.QUERY_STRING.token().content() );
String qs = message.requestPath().split( "\\?" )[1];
String[] params = qs.split( "&" );
for( String param : params ) {
String[] kv = param.split( "=" );
qsValue.getNewChild( kv[0] ).setValue( kv[1] );
}
} catch( ArrayIndexOutOfBoundsException e ) {}
}
}
// Print debug information about a received message
private static void recv_logDebugInfo( HttpMessage message )
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.httpCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
debugSB.append( "--> Message content\n" );
if ( message.content() != null )
debugSB.append( new String( message.content() ) );
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
String format = "xml";
if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
String type = message.getProperty( "content-type" ).split( ";" )[0];
if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value );
} else if ( "text/xml".equals( type ) || "rest".equals( format ) ) {
parseXML( message, decodedMessage.value );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value );
requestFormat = "text/x-gwt-rpc";
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value );
} else {
decodedMessage.value.setValue( new String( message.content() ) );
}
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
decodedMessage.operationName = message.requestPath().split( "\\?" )[0];
}
InputOperation op = null;
try {
op = Interpreter.getInstance().getInputOperation( decodedMessage.operationName );
} catch( InvalidIdException e ) {}
if ( op == null || !channel().parentListener().canHandleInputOperation( op ) ) {
String defaultOpId = getParameterVector( "default" ).first().strValue();
if ( defaultOpId.length() > 0 ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getChildren( "operation" ).first().setValue( decodedMessage.operationName );
decodedMessage.operationName = defaultOpId;
}
}
}
private static void recv_checkForMessageProperties( HttpMessage message, Value messageValue )
{
recv_checkForCookies( message, messageValue );
String property;
if ( (property=message.getProperty( "user-agent" )) != null ) {
messageValue.getNewChild( Constants.Predefined.USER_AGENT.token().content() ).setValue( property );
}
}
private class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpMessage message = new HttpParser( istream ).parse();
HttpUtils.recv_checkForChannelClosing( message, channel() );
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message );
}
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage );
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( inputId, "/", decodedMessage.value );
received = false;
} else if ( !message.isError() ) {
recv_parseQueryString( message, decodedMessage.value );
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage.value );
//TODO support resourcePath
retVal = new CommMessage( decodedMessage.operationName, "/", decodedMessage.value );
received = true;
}
return retVal;
}
} |
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.lang.Constants;
import jolie.Interpreter;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.JolieGWTConverter;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.protocols.SequentialCommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.InputOperation;
import jolie.runtime.InvalidIdException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.xml.XmlUtils;
import joliex.gwt.client.JolieService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
*/
public class HttpProtocol extends SequentialCommProtocol
{
private static class Parameters {
private static String DEBUG = "debug";
}
private String inputId = null;
final private Transformer transformer;
final private DocumentBuilderFactory docBuilderFactory;
final private DocumentBuilder docBuilder;
final private URI uri;
private boolean received = false;
final public static String CRLF = new String( new char[] { 13, 10 } );
public String name()
{
return "http";
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
TransformerFactory transformerFactory,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
)
throws TransformerConfigurationException
{
super( configurationPath );
this.uri = uri;
this.transformer = transformerFactory.newTransformer();
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$";
private static void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() );
StringBuilder cookieSB = new StringBuilder();
String domain;
// TODO check for cookie expiration
for( Value v : cookieVec ) {
domain = v.getChildren( "domain" ).first().strValue();
if ( domain.isEmpty() ||
(!domain.isEmpty() && hostname.endsWith( domain )) ) {
cookieSB.append(
v.getChildren( "name" ).first().strValue() + "=" +
v.getChildren( "value" ).first().strValue() + "; "
);
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder.append( "Cookie: " );
headerBuilder.append( cookieSB );
headerBuilder.append( CRLF );
}
}
private static void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() );
// TODO check for cookie expiration
for( Value v : cookieVec ) {
headerBuilder.append( "Set-Cookie: " +
v.getFirstChild( "name" ).strValue() + "=" +
v.getFirstChild( "value" ).strValue() + "; " +
"expires=" + v.getFirstChild( "expires" ).strValue() + "; " +
"path=" + v.getFirstChild( "path" ).strValue() + "; " +
"domain=" + v.getFirstChild( "domain" ).strValue() +
( (v.getFirstChild( "secure" ).intValue() > 0) ? "; secure" : "" ) +
CRLF
);
}
}
private String requestFormat = null;
private static CharSequence parseAlias( String alias, Value value, String charset )
throws IOException
{
int offset = 0;
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
currKey = alias.substring( m.start()+2, m.end()-1 );
currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset );
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
return result;
}
private String send_getCharset( CommMessage message )
{
String charset = "UTF8";
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.CHARSET.token().content() ) ) {
charset = message.value().getFirstChild( jolie.lang.Constants.Predefined.CHARSET.token().content() ).strValue();
} else if ( hasParameter( "charset" ) ) {
charset = getStringParameter( "charset" );
}
return charset;
}
private String send_getFormat( CommMessage message )
{
String format = "xml";
if ( received && requestFormat != null ) {
format = requestFormat;
requestFormat = null;
} else if ( message.value().hasChildren( jolie.lang.Constants.Predefined.FORMAT.token().content() ) ) {
format = message.value().getFirstChild( jolie.lang.Constants.Predefined.FORMAT.token().content() ).strValue();
} else if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
return format;
}
private class EncodedContent {
private ByteArray content = null;
private String contentType = null;
}
private EncodedContent send_encodeContent( CommMessage message, String charset, String format )
throws IOException
{
if ( charset == null ) {
charset = "UTF8";
}
EncodedContent ret = new EncodedContent();
if ( "xml".equals( format ) ) {
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( received ) ? "Response" : "") );
doc.appendChild( root );
valueToDocument( message.value(), root, doc );
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toByteArray() );
ret.contentType = "text/xml";
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray)message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
ret.contentType = "text/html";
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" + BOUNDARY + CRLF );
builder.append( "Content-Disposition: form-data; name=\"" + entry.getKey() + '\"' + CRLF + CRLF );
builder.append( entry.getValue().first().strValue() + CRLF );
}
}
builder.append( "--" + BOUNDARY + "--" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
Entry< String, ValueVector > entry;
StringBuilder builder = new StringBuilder();
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() + "=" + URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
}
return ret;
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
String redirect = message.value().getFirstChild( Constants.Predefined.REDIRECT.token().content() ).strValue();
if ( redirect.isEmpty() ) {
headerBuilder.append( "HTTP/1.1 200 OK" + CRLF );
} else {
headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF );
headerBuilder.append( "Location: " + redirect + CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
}
private void send_appendRequestMethod( StringBuilder headerBuilder )
{
if ( hasParameter( "method" ) ) {
headerBuilder.append( getStringParameter( "method" ).toUpperCase() );
} else {
headerBuilder.append( "GET" );
}
}
private void send_appendRequestPath( CommMessage message, StringBuilder headerBuilder, String charset )
throws IOException
{
if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
/*if ( uri.toString().endsWith( "/" ) == false ) {
headerBuilder.append( '/' );
}*/
if (
hasParameter( "aliases" ) &&
getParameterFirstValue( "aliases" ).hasChildren( message.operationName() )
) {
headerBuilder.append(
parseAlias(
getParameterFirstValue( "aliases" ).getFirstChild( message.operationName() ).strValue(),
message.value(),
charset
)
);
} else {
headerBuilder.append( message.operationName() );
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " + userpass + CRLF );
}
}
private void send_appendRequestHeaders( CommMessage message, StringBuilder headerBuilder, String charset )
throws IOException
{
send_appendRequestMethod( headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, headerBuilder, charset );
headerBuilder.append( " HTTP/1.1" + CRLF );
headerBuilder.append( "Host: " + uri.getHost() + CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
{
String param;
if ( checkBooleanParameter( "keepAlive" ) || channel().toBeClosed() ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + CRLF );
}
if ( encodedContent.content != null ) {
param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TYPE.token().content() ).strValue();
if ( !param.isEmpty() ) {
encodedContent.contentType = param;
}
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( CRLF );
param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TRANSFER_ENCODING.token().content() ).strValue();
if ( !param.isEmpty() ) {
headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent )
{
if ( checkBooleanParameter( "debug" ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString() );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
String charset = send_getCharset( message );
String format = send_getFormat( message );
EncodedContent encodedContent = send_encodeContent( message, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( received ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
received = false;
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, headerBuilder, charset );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( CRLF );
send_logDebugInfo( headerBuilder, encodedContent );
inputId = message.operationName();
if ( charset == null ) {
charset = "UTF8";
}
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null ) {
ostream.write( encodedContent.content.getBytes() );
ostream.write( CRLF.getBytes( charset ) );
}
}
private void parseXML( HttpMessage message, Value value )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseForm( HttpMessage message, Value value )
throws IOException
{
String line = new String( message.content(), "UTF8" );
String[] s, pair;
s = line.split( "&" );
for( int i = 0; i < s.length; i++ ) {
pair = s[i].split( "=", 2 );
value.getChildren( pair[0] ).first().setValue( pair[1] );
}
}
private static void parseMultiPartFormData( HttpMessage message, Value value )
throws IOException
{
MultiPartFormDataParser parser = new MultiPartFormDataParser( message, value );
parser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private static void recv_checkForSetCookie( HttpMessage message, Value value )
{
ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() );
Value currValue;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );
}
}
private static void recv_checkForCookies( HttpMessage message, Value value )
{
ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() );
Value v;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
v = Value.create();
v.getNewChild( "name" ).setValue( entry.getKey() );
v.getNewChild( "value" ).setValue( entry.getValue() );
cookieVec.add( v );
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
if ( message.requestPath() != null ) {
try {
Value qsValue = value.getFirstChild( Constants.Predefined.QUERY_STRING.token().content() );
String qs = message.requestPath().split( "\\?" )[1];
String[] params = qs.split( "&" );
for( String param : params ) {
String[] kv = param.split( "=" );
qsValue.getNewChild( kv[0] ).setValue( kv[1] );
}
} catch( ArrayIndexOutOfBoundsException e ) {}
}
}
// Print debug information about a received message
private void recv_logDebugInfo( HttpMessage message )
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.httpCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
if (
getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0
&& message.content() != null
) {
debugSB.append( "--> Message content\n" );
debugSB.append( new String( message.content() ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
String format = "xml";
if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
String type = message.getProperty( "content-type" ).split( ";" )[0];
if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value );
} else if ( "text/xml".equals( type ) || "rest".equals( format ) ) {
parseXML( message, decodedMessage.value );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value );
requestFormat = "text/x-gwt-rpc";
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value );
} else {
decodedMessage.value.setValue( new String( message.content() ) );
}
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
decodedMessage.operationName = message.requestPath().split( "\\?" )[0];
}
InputOperation op = null;
try {
op = Interpreter.getInstance().getInputOperation( decodedMessage.operationName );
} catch( InvalidIdException e ) {}
if ( op == null || !channel().parentListener().canHandleInputOperation( op ) ) {
String defaultOpId = getParameterVector( "default" ).first().strValue();
if ( defaultOpId.length() > 0 ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getChildren( "operation" ).first().setValue( decodedMessage.operationName );
decodedMessage.operationName = defaultOpId;
}
}
}
private static void recv_checkForMessageProperties( HttpMessage message, Value messageValue )
{
recv_checkForCookies( message, messageValue );
String property;
if ( (property=message.getProperty( "user-agent" )) != null ) {
messageValue.getNewChild( Constants.Predefined.USER_AGENT.token().content() ).setValue( property );
}
}
private class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpMessage message = new HttpParser( istream ).parse();
if ( hasParameter( "keepAlive" ) ) {
channel().setToBeClosed( checkBooleanParameter( "keepAlive" ) == false );
} else {
HttpUtils.recv_checkForChannelClosing( message, channel() );
}
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message );
}
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage );
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( inputId, "/", decodedMessage.value );
received = false;
} else if ( !message.isError() ) {
recv_parseQueryString( message, decodedMessage.value );
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage.value );
//TODO support resourcePath
retVal = new CommMessage( decodedMessage.operationName, "/", decodedMessage.value );
received = true;
}
return retVal;
}
} |
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.Interpreter;
import jolie.lang.NativeType;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.json.JsonUtils;
import joliex.gwt.server.JolieGWTConverter;
import jolie.net.http.Method;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.ports.Interface;
import jolie.net.protocols.CommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import jolie.util.LocationParser;
import jolie.xml.XmlUtils;
import joliex.gwt.client.JolieService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
*/
public class HttpProtocol extends CommProtocol
{
private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes();
//private static final byte[] INTERNAL_SERVER_ERROR_HEADER = "HTTP/1.1 500 Internal Server error".getBytes();
private static class Parameters {
private static String DEBUG = "debug";
private static String COOKIES = "cookies";
private static String METHOD = "method";
private static String ALIAS = "alias";
private static String MULTIPART_HEADERS = "multipartHeaders";
private static String CONCURRENT = "concurrent";
private static class MultiPartHeaders {
private static String FILENAME = "filename";
}
}
private static class Headers {
private static String JOLIE_MESSAGE_ID = "X-Jolie-MessageID";
}
private String inputId = null;
private final Transformer transformer;
private final DocumentBuilderFactory docBuilderFactory;
private final DocumentBuilder docBuilder;
private final URI uri;
private final boolean inInputPort;
private MultiPartFormDataParser multiPartFormDataParser = null;
public final static String CRLF = new String( new char[] { 13, 10 } );
public String name()
{
return "http";
}
public boolean isThreadSafe()
{
return checkBooleanParameter( Parameters.CONCURRENT );
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
TransformerFactory transformerFactory,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
)
throws TransformerConfigurationException
{
super( configurationPath );
this.uri = uri;
this.inInputPort = inInputPort;
this.transformer = transformerFactory.newTransformer();
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
public String getMultipartHeaderForPart( String operationName, String partName )
{
if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) {
Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS );
if ( v.hasChildren( partName ) ) {
v = v.getFirstChild( partName );
if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) {
v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME );
return v.strValue();
}
}
}
return null;
}
private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$";
private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
String domain;
StringBuilder cookieSB = new StringBuilder();
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "";
if ( domain.isEmpty() || hostname.endsWith( domain ) ) {
cookieSB
.append( entry.getKey() )
.append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( ";" );
}
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder
.append( "Cookie: " )
.append( cookieSB )
.append( CRLF );
}
}
}
private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
headerBuilder
.append( "Set-Cookie: " )
.append( entry.getKey() ).append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( "; expires=" )
.append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" )
.append( "; domain=" )
.append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" )
.append( "; path=" )
.append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" );
if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) {
headerBuilder.append( "; secure" );
}
headerBuilder.append( CRLF );
}
}
}
}
private String requestFormat = null;
private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( value.children().isEmpty() == false ) {
headerBuilder.append( '?' );
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
headerBuilder
.append( entry.getKey() )
.append( '=' )
.append( URLEncoder.encode( entry.getValue().first().strValue(), charset ) )
.append( '&' );
}
}
}
private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
int offset = 0;
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
if ( m.group( 1 ) == null ) { // We have to use URLEncoder
currKey = alias.substring( m.start() + 2, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = URLEncoder.encode( value.strValue(), charset );
} else {
currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset );
}
} else { // We have to insert the string raw
currKey = alias.substring( m.start() + 3, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = value.strValue();
} else {
currStrValue = value.getFirstChild( currKey ).strValue();
}
}
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
headerBuilder.append( result );
}
private String getCharset()
{
String charset = "UTF-8";
if ( hasParameter( "charset" ) ) {
charset = getStringParameter( "charset" );
}
return charset;
}
private String send_getFormat()
{
String format = "xml";
if ( inInputPort && requestFormat != null ) {
format = requestFormat;
requestFormat = null;
} else if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
return format;
}
private static class EncodedContent {
private ByteArray content = null;
private String contentType = "";
}
private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format )
throws IOException
{
EncodedContent ret = new EncodedContent();
if ( inInputPort == false && method == Method.GET ) {
// We are building a GET request
return ret;
}
if ( "xml".equals( format ) ) {
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") );
doc.appendChild( root );
if ( message.isFault() ) {
Element faultElement = doc.createElement( message.fault().faultName() );
root.appendChild( faultElement );
valueToDocument( message.fault().value(), faultElement, doc );
} else {
valueToDocument( message.value(), root, doc );
}
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toByteArray() );
ret.contentType = "text/xml";
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray)message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
ret.contentType = "text/html";
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" ).append( BOUNDARY ).append( CRLF );
builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ).append( CRLF ).append( CRLF );
builder.append( entry.getValue().first().strValue() ).append( CRLF );
}
}
builder.append( "--" + BOUNDARY + "--" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "application/x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
Entry< String, ValueVector > entry;
StringBuilder builder = new StringBuilder();
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() )
.append( "=" )
.append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
ret.contentType = "text/x-gwt-rpc";
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
} else if ( "json".equals( format ) ) {
ret.contentType = "application/json";
StringBuilder jsonStringBuilder = new StringBuilder();
JsonUtils.valueToJsonString( message.value(), jsonStringBuilder );
ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) );
}
return ret;
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
String redirect = getStringParameter( "redirect" );
if ( redirect.isEmpty() ) {
headerBuilder.append( "HTTP/1.1 200 OK" + CRLF );
} else {
headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF );
headerBuilder.append( "Location: " + redirect + CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
headerBuilder.append( "Server: JOLIE" ).append( CRLF );
StringBuilder cacheControlHeader = new StringBuilder();
if ( hasParameter( "cacheControl" ) ) {
Value cacheControl = getParameterFirstValue( "cacheControl" );
if ( cacheControl.hasChildren( "maxAge" ) ) {
cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() );
}
}
if ( cacheControlHeader.length() > 0 ) {
headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF );
}
}
private void send_appendRequestMethod( Method method, StringBuilder headerBuilder )
{
headerBuilder.append( method.id() );
}
private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS );
if ( alias.isEmpty() ) {
headerBuilder.append( message.operationName() );
} else {
send_appendParsedAlias( alias, message.value(), charset, headerBuilder );
}
if ( method == Method.GET ) {
send_appendQuerystring( message.value(), charset, headerBuilder );
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF );
}
}
private Method send_getRequestMethod( CommMessage message )
throws IOException
{
try {
Method method;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ) {
method = Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() );
} else if ( hasParameter( Parameters.METHOD ) ) {
method = Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() );
} else {
method = Method.POST;
}
return method;
} catch( Method.UnsupportedMethodException e ) {
throw new IOException( e );
}
}
private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
send_appendRequestMethod( method, headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, method, headerBuilder, charset );
headerBuilder.append( " HTTP/1.1" + CRLF );
headerBuilder.append( "Host: " + uri.getHost() + CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
{
String param;
if ( checkBooleanParameter( "keepAlive" ) == false || channel().toBeClosed() ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + CRLF );
}
if ( checkBooleanParameter( Parameters.CONCURRENT ) ) {
headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF );
}
if ( encodedContent.content != null ) {
String contentType = getStringParameter( "contentType" );
if ( contentType.length() > 0 ) {
encodedContent.contentType = contentType;
}
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( CRLF );
param = getStringParameter( "contentTransferEncoding" );
if ( !param.isEmpty() ) {
headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent )
{
if ( checkBooleanParameter( "debug" ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString() );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
Method method = send_getRequestMethod( message );
String charset = getCharset();
String format = send_getFormat();
EncodedContent encodedContent = send_encodeContent( message, method, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( inInputPort ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, method, headerBuilder, charset );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( CRLF );
send_logDebugInfo( headerBuilder, encodedContent );
inputId = message.operationName();
/*if ( charset == null ) {
charset = "UTF8";
}*/
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null ) {
ostream.write( encodedContent.content.getBytes() );
ostream.write( CRLF.getBytes( charset ) );
}
}
private void parseXML( HttpMessage message, Value value )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseJson( HttpMessage message, Value value )
throws IOException
{
JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value );
}
private static void parseForm( HttpMessage message, Value value, String charset )
throws IOException
{
String line = new String( message.content(), "UTF8" );
String[] s, pair;
s = line.split( "&" );
for( int i = 0; i < s.length; i++ ) {
pair = s[i].split( "=", 2 );
value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) );
}
}
private void parseMultiPartFormData( HttpMessage message, Value value )
throws IOException
{
multiPartFormDataParser = new MultiPartFormDataParser( message, value );
multiPartFormDataParser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private void recv_checkForSetCookie( HttpMessage message, Value value )
throws IOException
{
if ( hasParameter( Parameters.COOKIES ) ) {
String type;
Value cookies = getParameterFirstValue( Parameters.COOKIES );
Value cookieConfig;
Value v;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
if ( cookies.hasChildren( cookie.name() ) ) {
cookieConfig = cookies.getFirstChild( cookie.name() );
if ( cookieConfig.isString() ) {
v = value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( cookie.value(), v, type );
}
}
/*currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );*/
}
}
}
private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword )
throws IOException
{
NativeType type = NativeType.fromString( typeKeyword );
if ( NativeType.INT == type ) {
try {
value.setValue( new Integer( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.STRING == type ) {
value.setValue( cookieValue );
} else if ( NativeType.DOUBLE == type ) {
try {
value.setValue( new Double( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else {
value.setValue( cookieValue );
}
}
private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value cookies = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) {
cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookies = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookies != null ) {
Value v;
String type;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
if ( cookies.hasChildren( entry.getKey() ) ) {
Value cookieConfig = cookies.getFirstChild( entry.getKey() );
if ( cookieConfig.isString() ) {
v = decodedMessage.value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( entry.getValue(), v, type );
}
}
}
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
String queryString = message.requestPath() == null ? "" : message.requestPath();
String[] kv = queryString.split( "\\?" );
if ( kv.length > 1 ) {
queryString = kv[1];
String[] params = queryString.split( "&" );
for( String param : params ) {
kv = param.split( "=", 2 );
if ( kv.length > 1 ) {
value.getFirstChild( kv[0] ).setValue( kv[1] );
}
}
}
}
/*
* Prints debug information about a received message
*/
private void recv_logDebugInfo( HttpMessage message )
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.httpCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
if (
getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0
&& message.content() != null
) {
debugSB.append( "--> Message content\n" );
debugSB.append( new String( message.content() ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset )
throws IOException
{
requestFormat = null;
String format = "xml";
if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
String type = message.getProperty( "content-type" ).split( ";" )[0];
if ( "text/html".equals( type ) ) {
decodedMessage.value.setValue( new String( message.content() ) );
} else if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value, charset );
} else if ( "text/xml".equals( type ) ) {
parseXML( message, decodedMessage.value );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value );
requestFormat = "text/x-gwt-rpc";
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value );
} else if ( "application/octet-stream".equals( type ) ) {
decodedMessage.value.setValue( new ByteArray( message.content() ) );
} else if ( "application/json".equals( type ) ) {
parseJson( message, decodedMessage.value );
} else if ( "xml".equals( format ) || "rest".equals( format ) ) {
parseXML( message, decodedMessage.value );
} else if ( "json".equals( format ) ) {
parseJson( message, decodedMessage.value );
} else {
decodedMessage.value.setValue( new String( message.content() ) );
}
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
String requestPath = message.requestPath().split( "\\?" )[0];
decodedMessage.operationName = requestPath;
Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName );
if ( m.find() ) {
int resourceStart = m.end();
if ( m.find() ) {
decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() );
decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() );
}
}
}
if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) {
String defaultOpId = getStringParameter( "default" );
if ( defaultOpId.length() > 0 ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName );
Value cookies = decodedMessage.value.getFirstChild( "cookies" );
for( Entry< String, String > cookie : message.cookies().entrySet() ) {
cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() );
}
decodedMessage.operationName = defaultOpId;
}
}
}
private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage )
{
if ( multiPartFormDataParser != null ) {
String target;
for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) {
if ( entry.getValue().filename() != null ) {
target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() );
if ( target != null ) {
decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() );
}
}
}
multiPartFormDataParser = null;
}
}
private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
recv_checkForCookies( message, decodedMessage );
recv_checkForMultiPartHeaders( decodedMessage );// message, decodedMessage );
String property;
if (
(property=message.getProperty( "user-agent" )) != null &&
hasParameter( "userAgent" )
) {
getParameterFirstValue( "userAgent" ).setValue( property );
}
}
private static class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
private String resourcePath = "/";
private long id = CommMessage.GENERIC_ID;
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpMessage message = new HttpParser( istream ).parse();
if ( message.isSupported() == false ) {
ostream.write( NOT_IMPLEMENTED_HEADER );
ostream.write( CRLF.getBytes() );
ostream.write( CRLF.getBytes() );
ostream.flush();
return null;
}
String charset = getCharset();
if ( message.getProperty( "connection" ) != null ) {
HttpUtils.recv_checkForChannelClosing( message, channel() );
} else if ( hasParameter( "keepAlive" ) ) {
channel().setToBeClosed( checkBooleanParameter( "keepAlive" ) == false );
}
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message );
}
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage, charset );
}
if ( checkBooleanParameter( Parameters.CONCURRENT ) ) {
String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID );
if ( messageId != null ) {
try {
decodedMessage.id = Long.parseLong( messageId );
} catch( NumberFormatException e ) {}
}
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null );
} else if ( message.isError() == false ) {
if ( message.isGet() ) {
recv_parseQueryString( message, decodedMessage.value );
}
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage );
retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null );
}
if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null
&& channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) {
try {
// The message is for this service
Interface iface = channel().parentPort().getInterface();
OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() );
if ( oneWayTypeDescription != null && message.isResponse() == false ) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast( retVal.value() );
} else {
RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() );
if ( retVal.isFault() ) {
Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() );
if ( faultType != null ) {
faultType.cast( retVal.value() );
}
} else {
if ( message.isResponse() ) {
rrTypeDescription.responseType().cast( retVal.value() );
} else {
rrTypeDescription.requestType().cast( retVal.value() );
}
}
}
} catch( TypeCastingException e ) {
// TODO: do something here?
}
}
return retVal;
}
} |
package lombok.javac.apt;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import lombok.Lombok;
import lombok.core.DiagnosticsReceiver;
import lombok.javac.JavacTransformer;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.jvm.ClassWriter;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.processing.JavacFiler;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
/**
* This Annotation Processor is the standard injection mechanism for lombok-enabling the javac compiler.
*
* To actually enable lombok in a javac compilation run, this class should be in the classpath when
* running javac; that's the only requirement.
*/
@SupportedAnnotationTypes("*")
public class LombokProcessor extends AbstractProcessor {
private ProcessingEnvironment processingEnv;
private JavacProcessingEnvironment javacProcessingEnv;
private JavacFiler javacFiler;
private JavacTransformer transformer;
private Trees trees;
private boolean lombokDisabled = false;
/** {@inheritDoc} */
@Override public void init(ProcessingEnvironment procEnv) {
super.init(procEnv);
if (System.getProperty("lombok.disable") != null) {
lombokDisabled = true;
return;
}
this.processingEnv = procEnv;
this.javacProcessingEnv = getJavacProcessingEnvironment(procEnv);
this.javacFiler = getJavacFiler(procEnv.getFiler());
placePostCompileAndDontMakeForceRoundDummiesHook();
trees = Trees.instance(javacProcessingEnv);
transformer = new JavacTransformer(procEnv.getMessager(), trees);
SortedSet<Long> p = transformer.getPriorities();
if (p.isEmpty()) {
this.priorityLevels = new long[] {0L};
this.priorityLevelsRequiringResolutionReset = new HashSet<Long>();
} else {
this.priorityLevels = new long[p.size()];
int i = 0;
for (Long prio : p) this.priorityLevels[i++] = prio;
this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset();
}
}
private static final String JPE = "com.sun.tools.javac.processing.JavacProcessingEnvironment";
private static final Field javacProcessingEnvironment_discoveredProcs = getFieldAccessor(JPE, "discoveredProcs");
private static final Field discoveredProcessors_procStateList = getFieldAccessor(JPE + "$DiscoveredProcessors", "procStateList");
private static final Field processorState_processor = getFieldAccessor(JPE + "$processor", "processor");
private static final Field getFieldAccessor(String typeName, String fieldName) {
try {
Class<?> c = Class.forName(typeName);
Field f = c.getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchFieldException e) {
return null;
}
}
// The intent of this method is to have lombok emit a warning if it's not 'first in line'. However, pragmatically speaking, you're always looking at one of two cases:
// (A) The other processor(s) running before lombok require lombok to have run or they crash. So, they crash, and unfortunately we are never even init-ed; the warning is never emitted.
// (B) The other processor(s) don't care about it at all. So, it doesn't actually matter that lombok isn't first.
// Hence, for now, no warnings.
@SuppressWarnings("unused")
private String listAnnotationProcessorsBeforeOurs() {
try {
Object discoveredProcessors = javacProcessingEnvironment_discoveredProcs.get(this.javacProcessingEnv);
ArrayList<?> states = (ArrayList<?>) discoveredProcessors_procStateList.get(discoveredProcessors);
if (states == null || states.isEmpty()) return null;
if (states.size() == 1) return processorState_processor.get(states.get(0)).getClass().getName();
int idx = 0;
StringBuilder out = new StringBuilder();
for (Object processState : states) {
idx++;
String name = processorState_processor.get(processState).getClass().getName();
if (out.length() > 0) out.append(", ");
out.append("[").append(idx).append("] ").append(name);
}
return out.toString();
} catch (Exception e) {
return null;
}
}
private void placePostCompileAndDontMakeForceRoundDummiesHook() {
stopJavacProcessingEnvironmentFromClosingOurClassloader();
forceMultipleRoundsInNetBeansEditor();
Context context = javacProcessingEnv.getContext();
disablePartialReparseInNetBeansEditor(context);
try {
Method keyMethod = Context.class.getDeclaredMethod("key", Class.class);
keyMethod.setAccessible(true);
Object key = keyMethod.invoke(context, JavaFileManager.class);
Field htField = Context.class.getDeclaredField("ht");
htField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Object,Object> ht = (Map<Object,Object>) htField.get(context);
final JavaFileManager originalFiler = (JavaFileManager) ht.get(key);
if (!(originalFiler instanceof InterceptingJavaFileManager)) {
final Messager messager = processingEnv.getMessager();
DiagnosticsReceiver receiver = new MessagerDiagnosticsReceiver(messager);
JavaFileManager newFilerManager = new InterceptingJavaFileManager(originalFiler, receiver);
ht.put(key, newFilerManager);
Field filerFileManagerField = JavacFiler.class.getDeclaredField("fileManager");
filerFileManagerField.setAccessible(true);
filerFileManagerField.set(javacFiler, newFilerManager);
replaceFileManagerJdk9(context, newFilerManager);
}
} catch (Exception e) {
throw Lombok.sneakyThrow(e);
}
}
private void replaceFileManagerJdk9(Context context, JavaFileManager newFiler) {
try {
JavaCompiler compiler = (JavaCompiler) JavaCompiler.class.getDeclaredMethod("instance", Context.class).invoke(null, context);
try {
Field fileManagerField = JavaCompiler.class.getDeclaredField("fileManager");
fileManagerField.setAccessible(true);
fileManagerField.set(compiler, newFiler);
}
catch (Exception e) {}
try {
Field writerField = JavaCompiler.class.getDeclaredField("writer");
writerField.setAccessible(true);
ClassWriter writer = (ClassWriter) writerField.get(compiler);
Field fileManagerField = ClassWriter.class.getDeclaredField("fileManager");
fileManagerField.setAccessible(true);
fileManagerField.set(writer, newFiler);
}
catch (Exception e) {}
}
catch (Exception e) {
}
}
private void forceMultipleRoundsInNetBeansEditor() {
try {
Field f = JavacProcessingEnvironment.class.getDeclaredField("isBackgroundCompilation");
f.setAccessible(true);
f.set(javacProcessingEnv, true);
} catch (NoSuchFieldException e) {
// only NetBeans has it
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private void disablePartialReparseInNetBeansEditor(Context context) {
try {
Class<?> cancelServiceClass = Class.forName("com.sun.tools.javac.util.CancelService");
Method cancelServiceInstace = cancelServiceClass.getDeclaredMethod("instance", Context.class);
Object cancelService = cancelServiceInstace.invoke(null, context);
if (cancelService == null) return;
Field parserField = cancelService.getClass().getDeclaredField("parser");
parserField.setAccessible(true);
Object parser = parserField.get(cancelService);
Field supportsReparseField = parser.getClass().getDeclaredField("supportsReparse");
supportsReparseField.setAccessible(true);
supportsReparseField.set(parser, false);
} catch (ClassNotFoundException e) {
// only NetBeans has it
} catch (NoSuchFieldException e) {
// only NetBeans has it
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private static ClassLoader wrapClassLoader(final ClassLoader parent) {
return new ClassLoader() {
public Class<?> loadClass(String name) throws ClassNotFoundException {
return parent.loadClass(name);
}
public String toString() {
return parent.toString();
}
public URL getResource(String name) {
return parent.getResource(name);
}
public Enumeration<URL> getResources(String name) throws IOException {
return parent.getResources(name);
}
public InputStream getResourceAsStream(String name) {
return parent.getResourceAsStream(name);
}
public void setDefaultAssertionStatus(boolean enabled) {
parent.setDefaultAssertionStatus(enabled);
}
public void setPackageAssertionStatus(String packageName, boolean enabled) {
parent.setPackageAssertionStatus(packageName, enabled);
}
public void setClassAssertionStatus(String className, boolean enabled) {
parent.setClassAssertionStatus(className, enabled);
}
public void clearAssertionStatus() {
parent.clearAssertionStatus();
}
};
}
private void stopJavacProcessingEnvironmentFromClosingOurClassloader() {
try {
Field f = JavacProcessingEnvironment.class.getDeclaredField("processorClassLoader");
f.setAccessible(true);
ClassLoader unwrapped = (ClassLoader) f.get(javacProcessingEnv);
if (unwrapped == null) return;
ClassLoader wrapped = wrapClassLoader(unwrapped);
f.set(javacProcessingEnv, wrapped);
} catch (NoSuchFieldException e) {
// Some versions of javac have this (and call close on it), some don't. I guess this one doesn't have it.
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private final IdentityHashMap<JCCompilationUnit, Long> roots = new IdentityHashMap<JCCompilationUnit, Long>();
private long[] priorityLevels;
private Set<Long> priorityLevelsRequiringResolutionReset;
/** {@inheritDoc} */
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (lombokDisabled) return false;
if (roundEnv.processingOver()) return false;
// We have: A sorted set of all priority levels: 'priorityLevels'
// Step 1: Take all CUs which aren't already in the map. Give them the first priority level.
String randomModuleName = null;
for (Element element : roundEnv.getRootElements()) {
if (randomModuleName == null) randomModuleName = getModuleNameFor(element);
JCCompilationUnit unit = toUnit(element);
if (unit == null) continue;
if (roots.containsKey(unit)) continue;
roots.put(unit, priorityLevels[0]);
}
while (true) {
// Step 2: For all CUs (in the map, not the roundEnv!), run them across all handlers at their current prio level.
for (long prio : priorityLevels) {
List<JCCompilationUnit> cusForThisRound = new ArrayList<JCCompilationUnit>();
for (Map.Entry<JCCompilationUnit, Long> entry : roots.entrySet()) {
Long prioOfCu = entry.getValue();
if (prioOfCu == null || prioOfCu != prio) continue;
cusForThisRound.add(entry.getKey());
}
transformer.transform(prio, javacProcessingEnv.getContext(), cusForThisRound);
}
// Step 3: Push up all CUs to the next level. Set level to null if there is no next level.
Set<Long> newLevels = new HashSet<Long>();
for (int i = priorityLevels.length - 1; i >= 0; i
Long curLevel = priorityLevels[i];
Long nextLevel = (i == priorityLevels.length - 1) ? null : priorityLevels[i + 1];
List<JCCompilationUnit> cusToAdvance = new ArrayList<JCCompilationUnit>();
for (Map.Entry<JCCompilationUnit, Long> entry : roots.entrySet()) {
if (curLevel.equals(entry.getValue())) {
cusToAdvance.add(entry.getKey());
newLevels.add(nextLevel);
}
}
for (JCCompilationUnit unit : cusToAdvance) {
roots.put(unit, nextLevel);
}
}
newLevels.remove(null);
// Step 4: If ALL values are null, quit. Else, either do another loop right now or force a resolution reset by forcing a new round in the annotation processor.
if (newLevels.isEmpty()) return false;
newLevels.retainAll(priorityLevelsRequiringResolutionReset);
if (!newLevels.isEmpty()) {
// Force a new round to reset resolution. The next round will cause this method (process) to be called again.
forceNewRound(randomModuleName, javacFiler);
return false;
}
// None of the new levels need resolution, so just keep going.
}
}
private int dummyCount = 0;
private void forceNewRound(String randomModuleName, JavacFiler filer) {
if (!filer.newFiles()) {
try {
String name = "lombok.dummy.ForceNewRound" + (dummyCount++);
if (randomModuleName != null) name = randomModuleName + "/" + name;
JavaFileObject dummy = filer.createSourceFile(name);
Writer w = dummy.openWriter();
w.close();
} catch (Exception e) {
e.printStackTrace();
processingEnv.getMessager().printMessage(Kind.WARNING,
"Can't force a new processing round. Lombok won't work.");
}
}
}
private String getModuleNameFor(Element element) {
while (element != null) {
if (element.getKind().name().equals("MODULE")) {
String n = element.getSimpleName().toString().trim();
return n.isEmpty() ? null : n;
}
Element n = element.getEnclosingElement();
if (n == element) return null;
element = n;
}
return null;
}
private JCCompilationUnit toUnit(Element element) {
TreePath path = trees == null ? null : trees.getPath(element);
if (path == null) return null;
return (JCCompilationUnit) path.getCompilationUnit();
}
/**
* We just return the latest version of whatever JDK we run on. Stupid? Yeah, but it's either that or warnings on all versions but 1.
*/
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
/**
* This class casts the given processing environment to a JavacProcessingEnvironment. In case of
* gradle incremental compilation, the delegate ProcessingEnvironment of the gradle wrapper is returned.
*/
public JavacProcessingEnvironment getJavacProcessingEnvironment(Object procEnv) {
if (procEnv instanceof JavacProcessingEnvironment) {
return (JavacProcessingEnvironment) procEnv;
}
// try to find a "delegate" field in the object, and use this to try to obtain a JavacProcessingEnvironment
for (Class<?> procEnvClass = procEnv.getClass(); procEnvClass != null; procEnvClass = procEnvClass.getSuperclass()) {
try {
return getJavacProcessingEnvironment(tryGetDelegateField(procEnvClass, procEnv));
} catch (final Exception e) {
// delegate field was not found, try on superclass
}
}
processingEnv.getMessager().printMessage(Kind.WARNING,
"Can't get the delegate of the gradle IncrementalProcessingEnvironment. Lombok won't work.");
return null;
}
/**
* This class returns the given filer as a JavacFiler. In case the case that the filer is no
* JavacFiler (e.g. the Gradle IncrementalFiler), its "delegate" field is used to get the JavacFiler
* (directly or through a delegate field again)
*/
public JavacFiler getJavacFiler(Object filer) {
if (filer instanceof JavacFiler) {
return (JavacFiler) filer;
}
// try to find a "delegate" field in the object, and use this to check for a JavacFiler
for (Class<?> filerClass = filer.getClass(); filerClass != null; filerClass = filerClass.getSuperclass()) {
try {
return getJavacFiler(tryGetDelegateField(filerClass, filer));
} catch (final Exception e) {
// delegate field was not found, try on superclass
}
}
processingEnv.getMessager().printMessage(Kind.WARNING,
"Can't get a JavacFiler from " + filer.getClass().getName() + ". Lombok won't work.");
return null;
}
private Object tryGetDelegateField(Class<?> delegateClass, Object instance) throws Exception {
Field field = delegateClass.getDeclaredField("delegate");
field.setAccessible(true);
return field.get(instance);
}
} |
package kbasesearchengine.search;
import java.lang.reflect.Array;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Optional;
import kbasesearchengine.common.GUID;
import kbasesearchengine.system.SearchObjectType;
import kbasesearchengine.tools.Utils;
/** Data about an object in the search system. Contains a minimum of the object GUID, and may
* contain more fields depending on the specification of which fields to include.
* @author gaprice@lbl.gov
*
*/
public class ObjectData {
private final GUID guid;
private final Optional<GUID> parentGuid;
private final Optional<String> objectName;
private final Optional<SearchObjectType> type;
private final Optional<String> creator;
private final Optional<String> copier;
private final Optional<String> module;
private final Optional<String> method;
private final Optional<String> commitHash;
private final Optional<String> moduleVersion;
private final Optional<String> md5;
private final Optional<Instant> timestamp;
private final Optional<Object> parentData;
private final Optional<Object> data;
private final Map<String, String> keyProps;
private final Map<String, ArrayList> highlight;
private ObjectData(
final GUID guid,
final String objectName,
final SearchObjectType type,
final String creator,
final String copier,
final String module,
final String method,
final String commitHash,
final String moduleVersion,
final String md5,
final Instant timestamp,
final Object parentData,
final Object data,
final Map<String, String> keyProps,
final Map<String, ArrayList> highlight) {
this.guid = guid;
if (parentData != null) {
this.parentGuid = Optional.fromNullable(new GUID(guid, null, null));
} else {
this.parentGuid = Optional.absent();
}
this.objectName = Optional.fromNullable(objectName);
this.type = Optional.fromNullable(type);
this.creator = Optional.fromNullable(creator);
this.copier = Optional.fromNullable(copier);
this.module = Optional.fromNullable(module);
this.method = Optional.fromNullable(method);
this.commitHash = Optional.fromNullable(commitHash);
this.moduleVersion = Optional.fromNullable(moduleVersion);
this.md5 = Optional.fromNullable(md5);
this.timestamp = Optional.fromNullable(timestamp);
this.parentData = Optional.fromNullable(parentData);
this.data = Optional.fromNullable(data);
this.keyProps = Collections.unmodifiableMap(keyProps);
this.highlight = Collections.unmodifiableMap(highlight);
}
/** Get the object's GUID.
* @return the GUID.
*/
public GUID getGUID() {
return guid;
}
/** Get the parent object's GUID (e.g. the object guid without the subobject type or id).
* Only present if the parent object's data is present (see {@link #getParentData()}).
* @return the parent GUID.
*/
public Optional<GUID> getParentGUID() {
return parentGuid;
}
/** Get the name of the object, if present.
* @return the object name.
*/
public Optional<String> getObjectName() {
return objectName;
}
/** Get the type of the object, if present.
* @return the object type.
*/
public Optional<SearchObjectType> getType() {
return type;
}
/** Get the username of the creator of the object, if present.
* @return the object's creator.
*/
public Optional<String> getCreator() {
return creator;
}
/** Get the username of copier of the object, if present.
* @return the user that copied the object.
*/
public Optional<String> getCopier() {
return copier;
}
/** Get the name of the software module used to create the object, if present.
* @return the module name.
*/
public Optional<String> getModule() {
return module;
}
/** Get the name of the software method used to create the object, if present.
* @return the method name.
*/
public Optional<String> getMethod() {
return method;
}
/** Get the commit hash of the software used to create the object, if present.
* @return the commit hash.
*/
public Optional<String> getCommitHash() {
return commitHash;
}
/** Get the version of the software module used to create the object, if present.
* @return the module version.
*/
public Optional<String> getModuleVersion() {
return moduleVersion;
}
/** Get the md5 digest of the object, if present.
* @return the md5.
*/
public Optional<String> getMd5() {
return md5;
}
/** Get the timestamp of the creation of the object, if present.
* @return the timestamp.
*/
public Optional<Instant> getTimestamp() {
return timestamp;
}
/** Get the data associated with the parent of the object, if present. If present, the
* parent GUID will also be available (see {@link #getParentGUID()}).
* @return the parent object data.
*/
public Optional<Object> getParentData() {
return parentData;
}
/** Get the data associated with the object, if present.
* @return the object data.
*/
public Optional<Object> getData() {
return data;
}
/** Get the properties extracted from the object data and stored as searchable keys in the
* search system.
* @return the key properties.
*/
public Map<String, String> getKeyProperties() {
return keyProps;
}
/** Get hits that matched the query as highlighted snips corresponding to fields.
* @return the all fields with highlighting matches.
*/
public Map<String, ArrayList> getHighlight() { return highlight; }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((commitHash == null) ? 0 : commitHash.hashCode());
result = prime * result + ((copier == null) ? 0 : copier.hashCode());
result = prime * result + ((creator == null) ? 0 : creator.hashCode());
result = prime * result + ((data == null) ? 0 : data.hashCode());
result = prime * result + ((guid == null) ? 0 : guid.hashCode());
result = prime * result
+ ((keyProps == null) ? 0 : keyProps.hashCode());
result = prime * result + ((md5 == null) ? 0 : md5.hashCode());
result = prime * result + ((method == null) ? 0 : method.hashCode());
result = prime * result + ((module == null) ? 0 : module.hashCode());
result = prime * result
+ ((moduleVersion == null) ? 0 : moduleVersion.hashCode());
result = prime * result
+ ((objectName == null) ? 0 : objectName.hashCode());
result = prime * result
+ ((parentData == null) ? 0 : parentData.hashCode());
result = prime * result
+ ((parentGuid == null) ? 0 : parentGuid.hashCode());
result = prime * result
+ ((timestamp == null) ? 0 : timestamp.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((highlight == null) ? 0 : highlight.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ObjectData other = (ObjectData) obj;
if (commitHash == null) {
if (other.commitHash != null) {
return false;
}
} else if (!commitHash.equals(other.commitHash)) {
return false;
}
if (copier == null) {
if (other.copier != null) {
return false;
}
} else if (!copier.equals(other.copier)) {
return false;
}
if (creator == null) {
if (other.creator != null) {
return false;
}
} else if (!creator.equals(other.creator)) {
return false;
}
if (data == null) {
if (other.data != null) {
return false;
}
} else if (!data.equals(other.data)) {
return false;
}
if (guid == null) {
if (other.guid != null) {
return false;
}
} else if (!guid.equals(other.guid)) {
return false;
}
if (keyProps == null) {
if (other.keyProps != null) {
return false;
}
} else if (!keyProps.equals(other.keyProps)) {
return false;
}
if (md5 == null) {
if (other.md5 != null) {
return false;
}
} else if (!md5.equals(other.md5)) {
return false;
}
if (method == null) {
if (other.method != null) {
return false;
}
} else if (!method.equals(other.method)) {
return false;
}
if (module == null) {
if (other.module != null) {
return false;
}
} else if (!module.equals(other.module)) {
return false;
}
if (moduleVersion == null) {
if (other.moduleVersion != null) {
return false;
}
} else if (!moduleVersion.equals(other.moduleVersion)) {
return false;
}
if (objectName == null) {
if (other.objectName != null) {
return false;
}
} else if (!objectName.equals(other.objectName)) {
return false;
}
if (parentData == null) {
if (other.parentData != null) {
return false;
}
} else if (!parentData.equals(other.parentData)) {
return false;
}
if (parentGuid == null) {
if (other.parentGuid != null) {
return false;
}
} else if (!parentGuid.equals(other.parentGuid)) {
return false;
}
if (timestamp == null) {
if (other.timestamp != null) {
return false;
}
} else if (!timestamp.equals(other.timestamp)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
if (highlight == null) {
if (other.highlight != null) {
return false;
}
} else if (!highlight.equals(other.highlight)) {
return false;
}
return true;
}
/** Get a builder for an {@link ObjectData} instance.
* @param guid the GUID fro the object.
* @return a new builder.
*/
public static Builder getBuilder(final GUID guid) {
return new Builder(guid);
}
/** An {@link ObjectData} builder.
* @author gaprice@lbl.gov
*
*/
public static class Builder {
private final GUID guid;
private String objectName;
private SearchObjectType type;
private String creator;
private String copier;
private String module;
private String method;
private String commitHash;
private String moduleVersion;
private String md5;
private Instant timestamp;
private Object parentData;
private Object data;
private Map<String, String> keyProps = new HashMap<>();
private Map<String, ArrayList> highlight = new HashMap<>();
private Builder(final GUID guid) {
Utils.nonNull(guid, "guid");
this.guid = guid;
}
/** Build the new ObjectData.
* @return the object data.
*/
public ObjectData build() {
return new ObjectData(guid, objectName, type, creator, copier, module, method,
commitHash, moduleVersion, md5, timestamp, parentData, data, keyProps, highlight);
}
/** Set the object name in the builder. Replaces any previous object name. Nulls and
* whitespace only names are ignored.
* @param objectName the object name.
* @return this builder.
*/
public Builder withNullableObjectName(final String objectName) {
if (!Utils.isNullOrEmpty(objectName)) {
this.objectName = objectName;
}
return this;
}
/** Set the object type in the builder. Replaces any previous type. Null is ignored.
* @param type the object type.
* @return this builder.
*/
public Builder withNullableType(final SearchObjectType type) {
if (type != null) {
this.type = type;
}
return this;
}
/** Set the creator's user name in the builder. Replaces any previous creator. Nulls and
* whitespace only names are ignored.
* @param creator the creator's user name.
* @return this builder.
*/
public Builder withNullableCreator(final String creator) {
if (!Utils.isNullOrEmpty(creator)) {
this.creator = creator;
}
return this;
}
/** Set the user name of the user that copied the object in the builder.
* Replaces any previous copier name. Nulls and whitespace only names are ignored.
* @param copier the copier's user name.
* @return this builder.
*/
public Builder withNullableCopier(final String copier) {
if (!Utils.isNullOrEmpty(copier)) {
this.copier = copier;
}
return this;
}
/** Set the name of the software module used to create the object in the builder.
* Replaces any previous module name. Nulls and whitespace only names are ignored.
* @param module the module name.
* @return this builder.
*/
public Builder withNullableModule(final String module) {
if (!Utils.isNullOrEmpty(module)) {
this.module = module;
}
return this;
}
/** Set the name of the software method used to create the object in the builder.
* Replaces any previous object name. Nulls and whitespace only names are ignored.
* @param method the method name.
* @return this builder.
*/
public Builder withNullableMethod(final String method) {
if (!Utils.isNullOrEmpty(method)) {
this.method = method;
}
return this;
}
/** Set the commit hash of the software module used to create the object in the builder.
* Replaces any previous hash. Nulls and whitespace only hashes are ignored.
* @param commitHash the commit hash.
* @return this builder.
*/
public Builder withNullableCommitHash(final String commitHash) {
if (!Utils.isNullOrEmpty(commitHash)) {
this.commitHash = commitHash;
}
return this;
}
/** Set the version of the software module used to create the object in the builder.
* Replaces any previous version. Nulls and whitespace only versions are ignored.
* @param moduleVersion the module version.
* @return this builder.
*/
public Builder withNullableModuleVersion(final String moduleVersion) {
if (!Utils.isNullOrEmpty(moduleVersion)) {
this.moduleVersion = moduleVersion;
}
return this;
}
/** Set the MD5 digest of the object.
* Replaces any previous MD5s. Nulls and whitespace only MD5s are ignored.
* @param md5 the MD5.
* @return this builder.
*/
public Builder withNullableMD5(final String md5) {
if (!Utils.isNullOrEmpty(md5)) {
this.md5 = md5;
}
return this;
}
/** Set the object's creation timestamp. in the builder. Replaces any previous timestamp.
* Null is ignored.
* @param timestamp the timestamp.
* @return this builder.
*/
public Builder withNullableTimestamp(final Instant timestamp) {
if (timestamp != null) {
this.timestamp = timestamp;
}
return this;
}
/** Set the data of the parent object in the builder. Replaces any previous parent data.
* Null is ignored. If the parent data is present, the parent GUID
* (see {@link ObjectData#getParentGUID()}) will be available.
* @param parentData the parent object's data.
* @return this builder.
*/
public Builder withNullableParentData(final Object parentData) {
if (parentData != null) {
this.parentData = parentData;
}
return this;
}
/** Set the data of the object in the builder. Replaces any previous data.
* Null is ignored.
* @param data the object's data.
* @return this builder.
*/
public Builder withNullableData(final Object data) {
if (data != null) {
this.data = data;
}
return this;
}
/** Adds a searchable key and value to the builder. Keys must be non-null and consist of at
* least one non-whitespace character. Adding a duplicate key will overwrite the value of
* the previous key.
* @param key the key.
* @param property the value.
* @return this builder.
*/
public Builder withKeyProperty(final String key, final String property) {
Utils.notNullOrEmpty(key, "key cannot be null or whitespace");
keyProps.put(key, property);
return this;
}
/** Adds the highlight fields to the object.
* @param highlight the map of fields returned from elasticsearch.
* @return this builder.
*/
public Builder withNullableHighlight(final String field, final ArrayList highlight) {
Utils.notNullOrEmpty(field, "field cannot be null or whitespace");
Utils.noNulls(highlight, "highlight cannot be null");
if(highlight.size() > 0){
this.highlight.put(field, highlight);
}
return this;
}
}
} |
package dataforms.app.dao.enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dataforms.app.field.enumeration.EnumTypeCodeField;
import dataforms.app.field.enumeration.EnumTypeNameField;
import dataforms.dao.Dao;
import dataforms.dao.JDBCConnectableObject;
import dataforms.dao.Query;
import dataforms.dao.SubQuery;
import dataforms.dao.Table;
import dataforms.dao.TableList;
import dataforms.field.base.Field.MatchType;
import dataforms.field.base.FieldList;
import dataforms.field.sqlfunc.AliasField;
import dataforms.field.sqlfunc.SqlField;
// TODO:EnumGrpupTable
/**
*
* <pre>
* <select>
* </pre>
*
*/
public class EnumDao extends Dao {
/**
* Logger.
*/
//private static Logger log = Logger.getLogger(EnumDao.class.getName());
/**
*
* @param obj JDBC
* @throws Exception
*/
public EnumDao(final JDBCConnectableObject obj) throws Exception {
super(obj);
}
private static class EnumTypeQuery extends Query {
public EnumTypeQuery() {
EnumOptionTable mtbl = new EnumOptionTable();
this.setDistinct(true);
this.setFieldList(new FieldList(mtbl.getEnumTypeCodeField()));
this.setMainTable(mtbl);
}
}
private static class EnumGroupQuery extends Query {
/**
*
* @param data
*/
public EnumGroupQuery(final Map<String, Object> data) {
EnumGroupTable mtbl = new EnumGroupTable();
EnumTypeNameTable mntbl = new EnumTypeNameTable();
this.setFieldList(new FieldList(
new AliasField("value", mtbl.getEnumTypeCodeField())
, new AliasField("name", mntbl.getEnumTypeNameField())
));
this.setMainTable(mtbl);
this.setJoinTableList(new TableList(new SubQuery(new EnumTypeQuery()), mntbl));
this.setQueryFormFieldList(new FieldList(mtbl.getEnumGroupCodeField(), mntbl.getLangCodeField()));
this.setQueryFormData(data);
this.setOrderByFieldList(new FieldList(mtbl.getSortOrderField()));
}
}
/**
*
* @param enumGroupCode
* @param langCode
* @return
* @throws Exception
*/
public List<Map<String, Object>> getTypeList(final String enumGroupCode, final String langCode) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
EnumGroupTable.Entity e = new EnumGroupTable.Entity(data);
EnumTypeNameTable.Entity ne = new EnumTypeNameTable.Entity(data);
/*
data.put("enumGroupCode", enumGroupCode);
data.put("langCode", langCode);
*/
e.setEnumGroupCode(enumGroupCode);
ne.setLangCode(langCode);
EnumGroupQuery mq = new EnumGroupQuery(data);
List<Map<String, Object>> list = this.executeQuery(mq);
if (list.size() == 0) {
//data.put("langCode", "default");
ne.setLangCode("default");
list = this.executeQuery(mq);
}
return list;
}
private static class OptionQuery extends Query {
/**
* .
* @param data .
*/
public OptionQuery(final Map<String, Object> data) {
EnumOptionTable mtbl = new EnumOptionTable();
EnumOptionNameTable mntbl = new EnumOptionNameTable();
this.setFieldList(new FieldList(
new AliasField("value", mtbl.getEnumOptionCodeField())
, new AliasField("name", mntbl.getEnumOptionNameField())
));
this.setMainTable(mtbl);
this.setJoinTableList(new TableList(mntbl));
this.setQueryFormFieldList(new FieldList(mtbl.getEnumTypeCodeField(), mtbl.getEnumOptionCodeField(), mntbl.getLangCodeField()));
this.setQueryFormData(data);
this.setOrderByFieldList(new FieldList(mtbl.getSortOrderField()));
}
}
/**
*
* @param enumTypeCode
* @param langCode
* @return
* @throws Exception
*/
public List<Map<String, Object>> getOptionList(final String enumTypeCode, final String langCode) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
EnumOptionTable.Entity e = new EnumOptionTable.Entity(data);
EnumOptionNameTable.Entity ne = new EnumOptionNameTable.Entity(data);
/* data.put("enumTypeCode", enumTypeCode);
data.put("langCode", langCode);
*/ e.setEnumTypeCode(enumTypeCode);
ne.setLangCode(langCode);
OptionQuery mq = new OptionQuery(data);
List<Map<String, Object>> list = this.executeQuery(mq);
if (list.size() == 0) {
//data.put("langCode", "default");
ne.setLangCode("default");
list = this.executeQuery(mq);
}
return list;
}
/**
*
* @param enumTypeCode
* @param enumOptionCode
* @param langCode
* @return
* @throws Exception
*/
public String getOptionName(final String enumTypeCode, final String enumOptionCode, final String langCode) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
EnumOptionNameTable.Entity e = new EnumOptionNameTable.Entity(data);
e.setEnumTypeCode(enumTypeCode);
e.setEnumOptionCode(enumOptionCode);
e.setLangCode(langCode);
OptionQuery query = new OptionQuery(data);
Map<String, Object> rec = this.executeRecordQuery(query);
if (rec != null) {
String optname = (String) rec.get("name");
return optname;
} else {
return null;
}
}
public static class EnumTypeCodeQuery extends Query {
public EnumTypeCodeQuery() {
this.setDistinct(true);
EnumOptionTable table = new EnumOptionTable();
this.setFieldList(new FieldList(table.getEnumTypeCodeField()));
this.setMainTable(table);
}
}
/**
*
*
* <pre>
* langCode
*
* </pre>
*
*/
public static class EnumTypeNameQuery extends Query {
public EnumTypeNameQuery() {
EnumTypeNameTable dt = new EnumTypeNameTable();
dt.setAlias("dt");
EnumTypeNameTable ct = new EnumTypeNameTable();
ct.setAlias("ct");
SubQuery table = new SubQuery(new EnumTypeCodeQuery()) {
@Override
public String getJoinCondition(final Table joinTable, final String alias) {
if ("dt".equals(alias)) {
return this.getLinkFieldCondition(EnumGroupTable.Entity.ID_ENUM_TYPE_CODE, joinTable, alias, EnumTypeNameTable.Entity.ID_ENUM_TYPE_CODE)
+ " and dt.lang_code='default'";
}
if ("ct".equals(alias)) {
return this.getLinkFieldCondition(EnumGroupTable.Entity.ID_ENUM_TYPE_CODE, joinTable, alias, EnumTypeNameTable.Entity.ID_ENUM_TYPE_CODE)
+ " and ct.lang_code=:lang_code";
}
return super.getJoinCondition(joinTable, alias);
}
};
FieldList flist = new FieldList();
flist.addAll(table.getFieldList());
flist.add(new SqlField(new EnumTypeNameField(), "(case when ct.enum_type_name is not null then ct.enum_type_name else dt.enum_type_name end)"));
this.setFieldList(flist);
this.setMainTable(table);
this.setLeftJoinTableList(new TableList(dt, ct));
}
}
/**
* EnumTypeCode
* @param text
* @param langCode
* @return
* @throws Exception
*/
public List<Map<String, Object>> queryEnumTypeAutocomplateList(final String text, final String langCode) throws Exception {
EnumTypeNameQuery query = new EnumTypeNameQuery();
FieldList flist = new FieldList();
flist.addField(new EnumTypeCodeField()).setMatchType(MatchType.PART);
query.setQueryFormFieldList(flist);
EnumTypeNameTable.Entity e = new EnumTypeNameTable.Entity();
e.setEnumTypeCode(text);
e.setLangCode(langCode);
query.setQueryFormData(e.getMap());
return this.executeQuery(query);
}
/**
*
*
* @param enumTypeCode
* @param langCode
* @return
* @throws Exception
*/
public Map<String, Object> queryEnumType(final String enumTypeCode, final String langCode) throws Exception {
EnumTypeNameQuery query = new EnumTypeNameQuery();
query.setQueryFormFieldList(new FieldList(query.getFieldList().get(EnumTypeNameTable.Entity.ID_ENUM_TYPE_CODE)));
EnumTypeNameTable.Entity e = new EnumTypeNameTable.Entity();
e.setEnumTypeCode(enumTypeCode);
e.setLangCode(langCode);
query.setQueryFormData(e.getMap());
Map<String, Object> ret = this.executeRecordQuery(query);
if (ret == null) {
EnumTypeNameTable.Entity re = new EnumTypeNameTable.Entity();
re.setEnumTypeCode(enumTypeCode);
re.setEnumTypeName("");
ret = re.getMap();
}
return ret;
}
} |
package de.hs_mannheim.IB.SS15.OOT;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import de.hs_mannheim.IB.SS15.OOT.ExaminerDeleteGUI;
public class SubjectGUI extends JFrame implements ActionListener {
// Swing
private JScrollPane scrollSubjectTable;
private JPanel south;
private JButton btnAddSubject;
private JButton btnRemoveSubject;
private JButton btnAddExaminer;
private JButton btnRemoveExaminer;
private GUI mainGUI;
private SubjectDataModel dataModel;
private JTable jTable;
public SubjectGUI(GUI gui) {
this.mainGUI = gui;
setTitle("Fächer");
createLayout();
pack();
// setSize(400, 200);
setLocationRelativeTo(gui);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnAddSubject) {
String name = JOptionPane.showInputDialog(this, "Name des Fachs:", "Fach hinzufügen", JOptionPane.PLAIN_MESSAGE);
if (name != null) {
String abbreviation = JOptionPane.showInputDialog(this, "Kürzel des Fachs:", "Fach hinzufügen", JOptionPane.PLAIN_MESSAGE);
if (abbreviation != null) {
try {
mainGUI.getBackend().createSubject(name, abbreviation);
dataModel.updateData();
} catch (Exception error) {
JOptionPane.showMessageDialog(this, error.getMessage(), "Fach hinzufügen", JOptionPane.ERROR_MESSAGE);
}
}
}
} else if (e.getSource() == btnRemoveSubject) {
ArrayList<Subject> subjects = mainGUI.getBackend().getSubjects();
if (subjects.size() > 0) {
Subject selectedSubject = (Subject) JOptionPane.showInputDialog(this, "Name des Fachs:", "Fach entfernen", JOptionPane.QUESTION_MESSAGE, null, subjects.toArray(), subjects.get(0));
if (selectedSubject != null) {
for (int i = 0; i < subjects.size(); i++) {
if (subjects.get(i).equals(selectedSubject)) {
subjects.remove(i);
dataModel.updateData();
return;
}
}
}
} else {
JOptionPane.showMessageDialog(this, "Es sind noch keine Fächer vorhanden.", "Fach entfernen", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource() == btnAddExaminer) {
new ExaminerGUI(mainGUI);
} else if (e.getSource() == btnRemoveExaminer) {
new ExaminerDeleteGUI(mainGUI);
}
private void createLayout() {
// set Layout
getContentPane().setLayout(new BorderLayout());
// CENTER Panel
createTable();
// SOUTH Panel
createSouthButtons();
getContentPane().add(south, BorderLayout.SOUTH);
}
private void createTable() {
dataModel = new SubjectDataModel(mainGUI);
jTable = new JTable(dataModel);
scrollSubjectTable = new JScrollPane(jTable);
getContentPane().add(scrollSubjectTable, BorderLayout.CENTER);
}
private void createSouthButtons() {
south = new JPanel();
south.setLayout(new GridLayout(1, 4));
btnAddSubject = new JButton("Fach hinzufügen");
btnAddSubject.addActionListener(this);
south.add(btnAddSubject);
btnRemoveSubject = new JButton("Fach löschen");
btnRemoveSubject.addActionListener(this);
south.add(btnRemoveSubject);
btnAddExaminer = new JButton("Prüfer/Beisitzer hinzufügen");
btnAddExaminer.addActionListener(this);
south.add(btnAddExaminer);
btnRemoveExaminer = new JButton("Prüfer/Beisitzer löschen");
btnRemoveExaminer.addActionListener(this);
south.add(btnRemoveExaminer);
}
}
class SubjectDataModel extends AbstractTableModel {
private GUI mainGUI;
private ArrayList<Subject> subjects;
private final int COLUMS = 3;
SubjectDataModel(GUI mainGUI) {
this.mainGUI = mainGUI;
updateData();
}
public void updateData() {
subjects = mainGUI.getBackend().getSubjects();
fireTableDataChanged(); // Notifies all listeners that all cell values in the table's rows may have changed.
}
@Override
public int getRowCount() {
return subjects.size();
}
@Override
public int getColumnCount() {
return COLUMS;
}
@Override
public String getColumnName(int col) {
if (col == 0) {
return "Name";
} else if (col == 1) {
return "Abkürzung";
} else {
return "Anzahl der Studenten";
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return subjects.get(rowIndex).getName();
} else if (columnIndex == 1) {
return subjects.get(rowIndex).getAbbreviation();
} else {
return subjects.get(rowIndex).getAmountOfExaminees();
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col == 0) {
subjects.get(row).setName(value.toString());
} else if (col == 1) {
subjects.get(row).setAbbreviation(value.toString());
}
fireTableCellUpdated(row, col);
}
@Override
public boolean isCellEditable(int row, int col) {
if (col == 0 || col == 1) {
return true;
}
return false;
}
} |
package de.invation.code.toval.file;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import de.invation.code.toval.os.OSType;
import de.invation.code.toval.os.OSUtils;
import de.invation.code.toval.validate.ParameterException;
import de.invation.code.toval.validate.ParameterException.ErrorCode;
import de.invation.code.toval.validate.Validate;
public class FileUtils {
public static final boolean DEFAULT_OPEN_STORED_STREAM_FILES = false;
public static String ensureAbsolutePath(String file){
Path path = Paths.get(file);
if(path.isAbsolute())
return file;
Path base = Paths.get("");
Path effectivePath = base.resolve(path).toAbsolutePath();
return effectivePath.normalize().toString();
}
public static File writeStream(InputStream stream, String outputDirectory, String fileName) throws Exception{
return writeStream(stream, new File(outputDirectory), fileName);
}
public static File writeStream(InputStream stream, File outputDirectory, String fileName) throws Exception{
return writeStream(stream, outputDirectory, fileName, DEFAULT_OPEN_STORED_STREAM_FILES);
}
public static File writeStream(InputStream stream, String outputDirectory, String fileName, boolean open) throws Exception{
return writeStream(stream, new File(outputDirectory), fileName, open);
}
public static File writeStream(InputStream stream, File outputDirectory, String fileName, boolean open) throws Exception{
Validate.directory(outputDirectory);
Validate.fileName(fileName);
File documentFile = new File(outputDirectory, fileName);
try {
OutputStream outStream = new FileOutputStream(documentFile);
byte[] buffer = new byte[1];
while (stream.read(buffer) > 0) {
outStream.write(buffer);
}
outStream.close();
} catch(Exception e1){
throw new Exception("Cannot store stream content in output directory '" + outputDirectory.getAbsolutePath() + "'", e1);
}
if(open){
openFile(documentFile);
}
return documentFile;
}
public static void openFile(String file) throws Exception{
openFile(new File(file));
}
public static void openFile(File file) throws Exception{
Validate.exists(file);
if(Desktop.isDesktopSupported()){
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException e1) {
throw new Exception("File cannot be opened", e1);
}
}
}
public static void openFiles(Collection<File> files) throws Exception{
for(File file: files)
openFile(file);
}
public static List<File> getFilesInDirectory(String directory) throws IOException {
return getFilesInDirectory(directory, false);
}
public static List<File> getFilesInDirectory(String directory, boolean recursive) throws IOException {
return getFilesInDirectory(directory, null, recursive);
}
public static List<File> getFilesInDirectory(String directory, String acceptedEnding) throws IOException {
return getFilesInDirectory(directory, acceptedEnding, false);
}
public static List<File> getFilesInDirectory(String directory, String acceptedEnding, boolean recursive) throws IOException {
return getFilesInDirectory(directory, true, true, acceptedEnding, recursive);
}
public static List<File> getFilesInDirectory(String directory, boolean onlyFiles, boolean onlyVisibleFiles, final String acceptedEnding) throws IOException {
return getFilesInDirectory(directory, onlyFiles, onlyVisibleFiles, acceptedEnding, false);
}
public static List<File> getFilesInDirectory(String directory, boolean onlyFiles, boolean onlyVisibleFiles, final String acceptedEnding, boolean recursive) throws IOException {
return getFilesInDirectory(directory, onlyFiles, onlyVisibleFiles, new HashSet<>(Arrays.asList(acceptedEnding)), recursive);
}
public static List<File> getFilesInDirectory(String directory, boolean onlyFiles, boolean onlyVisibleFiles, final Set<String> acceptedEndings) throws IOException {
return getFilesInDirectory(directory, onlyFiles, onlyVisibleFiles, acceptedEndings, false);
}
public static List<File> getFilesInDirectory(String directory, boolean onlyFiles, boolean onlyVisibleFiles, final Set<String> acceptedEndings, boolean recursive) throws IOException {
// if(!dir.exists())
// throw new ParameterException(ErrorCode.INCOMPATIBILITY, "Invalid or non-existing file path.");
// if(!dir.isDirectory())
// throw new ParameterException(ErrorCode.INCOMPATIBILITY, "File is not a directory.");
File dir = Validate.directory(directory);
List<File> result = new ArrayList<>();
List<File> subDirectories = new ArrayList<>();
File[] filesInDirectory = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
File fileInDirectory = new File(dir, fileName);
if(!fileInDirectory.isFile()){
if(fileInDirectory.isDirectory())
subDirectories.add(fileInDirectory);
return !onlyFiles;
}
if(fileInDirectory.isHidden() && onlyVisibleFiles)
return false;
if (acceptedEndings != null && !acceptedEndings.isEmpty()) {
boolean hasAcceptedEnding = false;
for (String acceptedEnding : acceptedEndings) {
if (fileName.endsWith(".".concat(acceptedEnding))) {
hasAcceptedEnding = true;
break;
}
}
return hasAcceptedEnding;
} else {
return true;
}
}
});
result.addAll(Arrays.asList(filesInDirectory));
if(recursive){
for(File subDirectory: subDirectories){
result.addAll(getFilesInDirectory(subDirectory.getAbsolutePath(), onlyFiles, onlyVisibleFiles, acceptedEndings, recursive));
}
}
return result;
}
public static List<String> getFileNamesInDirectory(String directory) throws IOException {
return getFileNamesInDirectory(directory, false);
}
public static List<String> getFileNamesInDirectory(String directory, Set<String> acceptedEndings) throws IOException {
return getFileNamesInDirectory(directory, false, acceptedEndings);
}
public static List<String> getFileNamesInDirectory(String directory, boolean absolutePath) throws IOException {
return getFileNamesInDirectory(directory, true, true, absolutePath, null);
}
public static List<String> getFileNamesInDirectory(String directory, boolean absolutePath, Set<String> acceptedEndings) throws IOException {
return getFileNamesInDirectory(directory, true, true, absolutePath, acceptedEndings);
}
public static List<String> getFileNamesInDirectory(String directory, boolean onlyFiles, boolean onlyVisibleFiles, boolean absolutePath, Set<String> acceptedEndings) throws IOException {
List<File> files = getFilesInDirectory(directory, onlyFiles, onlyVisibleFiles, acceptedEndings);
List<String> result = new ArrayList<>();
for (File file : files) {
if (absolutePath) {
result.add(file.getAbsolutePath());
} else {
result.add(file.getName());
}
}
return result;
}
public static List<File> getSubdirectories(String directory) throws IOException {
Validate.directory(directory);
File dir = new File(directory);
if (!dir.exists()) {
throw new ParameterException(ErrorCode.INCOMPATIBILITY, "Invalid or non-existing directory.");
}
List<File> result = new ArrayList<>();
File[] files = dir.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
if (!files[i].isDirectory()) {
continue;
}
result.add(files[i]);
}
return result;
}
public static void deleteFile(String fileName) throws Exception {
deleteFile(new File(fileName));
}
public static void deleteFile(File file) throws Exception {
deleteFile(file, false);
}
public static void deleteFile(String fileName, boolean followLinks) throws Exception {
deleteFile(new File(fileName), followLinks);
}
public static void deleteFile(File file, boolean followLinks) throws Exception {
if (!file.exists()) {
throw new IllegalArgumentException("No such file or directory: " + file.getAbsolutePath());
}
if (!file.canWrite()) {
throw new IllegalArgumentException("Write protection: " + file.getAbsolutePath());
}
if (file.isDirectory()) {
throw new IllegalArgumentException("File is a directory: " + file.getAbsolutePath());
}
boolean success;
if (followLinks) {
success = file.delete();
} else {
success = removeLinkOnly(file);
}
if (!success) {
throw new IllegalArgumentException("Unspecified deletion error: " + file.getAbsolutePath());
}
}
public static boolean removeLinkOnly(File file) throws Exception {
if (file == null) {
return false;
}
OSType os = OSUtils.getCurrentOS();
String[] command = new String[1];
String path = file.getPath();
switch (os) {
case OS_WINDOWS:
command[0] = "del \"" + path + "\"";
break;
default:
command[0] = "rm \"" + path + "\"";
break;
}
OSUtils.getOSUtils().runCommand(command, null, null);
return true;
}
public static void deleteDirectory(String dirName, boolean recursive) throws Exception {
deleteDirectory(dirName, recursive, false);
}
public static void deleteDirectory(String dirName, boolean recursive, boolean followLinks) throws Exception {
File file = new File(dirName);
if (!file.exists()) {
throw new IllegalArgumentException("No such file or directory: " + dirName);
}
if (!file.canWrite()) {
throw new IllegalArgumentException("Write protection: " + dirName);
}
if (!file.isDirectory()) {
throw new IllegalArgumentException("No directory: " + dirName);
}
String[] files = file.list();
if (files != null && files.length > 0) {
if (!recursive) {
throw new IllegalArgumentException("Cannot delete non-empty directory in non-recursive mode: " + dirName);
}
for (int i = 0; i < files.length; i++) {
File childFile = new File(file.getPath() + "/" + files[i]);
if (childFile.isDirectory()) {
deleteDirectory(childFile.getAbsolutePath(), recursive, followLinks);
} else {
deleteFile(childFile.getAbsolutePath(), followLinks);
}
}
}
boolean success = file.delete();
if (!success) {
throw new IllegalArgumentException("Unspecified deletion error: " + dirName);
}
}
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
public static String getPath(File f) {
return getPath(f.getAbsolutePath());
}
public static String getPath(String absolutePath) {
return absolutePath.substring(0, absolutePath.lastIndexOf(File.separator) + 1);
}
public static String getFile(File f) {
return getFile(f.getAbsolutePath());
}
public static String getFile(String absolutePath) {
if (absolutePath.endsWith(File.separator)) {
return "";
}
return absolutePath.substring(absolutePath.lastIndexOf(File.separator) + 1, absolutePath.length());
}
public static String getFileWithoutEnding(File f) {
return getFileWithoutEnding(f.getAbsolutePath());
}
public static String getFileWithoutEnding(String absolutePath) {
return separateFileNameFromEnding(getFile(absolutePath));
}
public static String separateFileNameFromEnding(File f) {
String name = f.getName();
if (name.contains(".")) {
return name.substring(0, name.lastIndexOf('.'));
}
return name;
}
public static String separateFileNameFromEnding(String file) {
if (file.contains(".")) {
return file.substring(0, file.lastIndexOf('.'));
}
return file;
}
public static String getDirName(File dir) {
return getDirName(dir.getAbsolutePath());
}
public static String getDirName(String file) {
File dir = new File(file);
Validate.directory(dir);
String sep = System.getProperty("file.separator");
if (file.endsWith(sep)) {
if (file.length() == 1) {
return "";
}
char[] chars = file.toCharArray();
int index = file.length() - 2;
while (index >= 0) {
if (chars[index] == sep.charAt(0)) {
break;
}
index
}
if (index == 0 && chars[0] != sep.charAt(0)) {
return file.substring(0, file.length() - 1);
}
return file.substring(index + 1, file.length() - 1);
} else {
return file.substring(file.lastIndexOf(sep) + 1);
}
}
public static void copy(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
public static File writeFile(String path, String fileName, String content) throws IOException {
FileWriter writer = new FileWriter(path, fileName);
writer.write(content);
writer.closeFile();
return writer.getFile();
}
public static String readStringFromFile(String fileName) throws IOException {
FileReader reader = new FileReader(fileName);
StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line).append(FileWriter.DEFAULT_EOL_STRING);
}
reader.closeFile();
return stringBuffer.toString();
}
public static List<String> readLinesFromFile(String fileName) throws IOException {
FileReader reader = new FileReader(fileName);
List<String> lines = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.closeFile();
return lines;
}
public static long getLineCount(String fileName, String encodingName) throws IOException {
long linesCount = 0;
File file = new File(fileName);
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(file);
Charset encoding = Charset.forName(encodingName);
Reader fileReader = new InputStreamReader(fileIn, encoding);
int bufferSize = 4096;
Reader reader = new BufferedReader(fileReader, bufferSize);
char[] buffer = new char[bufferSize];
int prevChar = -1;
int readCount = reader.read(buffer);
while (readCount != -1) {
for (int i = 0; i < readCount; i++) {
int nextChar = buffer[i];
switch (nextChar) {
case '\r': {
linesCount++;
break;
}
case '\n': {
if (prevChar == '\r') {
} else {
linesCount++;
}
break;
}
}
prevChar = nextChar;
}
readCount = reader.read(buffer);
}
if (prevChar != -1) {
switch (prevChar) {
case '\r':
case '\n': {
break;
}
default: {
linesCount++;
}
}
}
} catch (IOException e) {
throw e;
} finally {
if (fileIn != null) {
fileIn.close();
}
}
return linesCount;
}
} |
package de.lmu.ifi.dbs.elki.algorithm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.datastore.DataStore;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil;
import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.distance.DistanceUtil;
import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancefunction.SpatialPrimitiveDistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance;
import de.lmu.ifi.dbs.elki.index.tree.LeafEntry;
import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialEntry;
import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialIndexTree;
import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialNode;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress;
import de.lmu.ifi.dbs.elki.logging.progress.IndefiniteProgress;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.utilities.datastructures.heap.Heap;
import de.lmu.ifi.dbs.elki.utilities.datastructures.heap.KNNHeap;
import de.lmu.ifi.dbs.elki.utilities.datastructures.heap.KNNList;
import de.lmu.ifi.dbs.elki.utilities.documentation.Description;
import de.lmu.ifi.dbs.elki.utilities.documentation.Title;
import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.pairs.FCPair;
/**
* Joins in a given spatial database to each object its k-nearest neighbors.
* This algorithm only supports spatial databases based on a spatial index
* structure.
*
* @author Elke Achtert
* @param <V> the type of FeatureVector handled by this Algorithm
* @param <D> the type of Distance used by this Algorithm
* @param <N> the type of node used in the spatial index structure
* @param <E> the type of entry used in the spatial node
*/
@Title("K-Nearest Neighbor Join")
@Description("Algorithm to find the k-nearest neighbors of each object in a spatial database")
public class KNNJoin<V extends NumberVector<V, ?>, D extends Distance<D>, N extends SpatialNode<N, E>, E extends SpatialEntry> extends AbstractDistanceBasedAlgorithm<V, D, DataStore<KNNList<D>>> {
/**
* The logger for this class.
*/
private static final Logging logger = Logging.getLogger(KNNJoin.class);
/**
* Parameter that specifies the k-nearest neighbors to be assigned, must be an
* integer greater than 0. Default value: 1.
*/
public static final OptionID K_ID = OptionID.getOrCreateOptionID("knnjoin.k", "Specifies the k-nearest neighbors to be assigned.");
/**
* The k parameter
*/
int k;
/**
* Constructor.
*
* @param distanceFunction Distance function
* @param k k parameter
*/
public KNNJoin(DistanceFunction<? super V, D> distanceFunction, int k) {
super(distanceFunction);
this.k = k;
}
@SuppressWarnings("unchecked")
public WritableDataStore<KNNList<D>> run(Database database, Relation<V> relation) throws IllegalStateException {
if(!(getDistanceFunction() instanceof SpatialPrimitiveDistanceFunction)) {
throw new IllegalStateException("Distance Function must be an instance of " + SpatialPrimitiveDistanceFunction.class.getName());
}
Collection<SpatialIndexTree<N, E>> indexes = ResultUtil.filterResults(database, SpatialIndexTree.class);
if(indexes.size() != 1) {
throw new AbortException("KNNJoin found " + indexes.size() + " spatial indexes, expected exactly one.");
}
// FIXME: Ensure were looking at the right relation!
SpatialIndexTree<N, E> index = indexes.iterator().next();
SpatialPrimitiveDistanceFunction<V, D> distFunction = (SpatialPrimitiveDistanceFunction<V, D>) getDistanceFunction();
DistanceQuery<V, D> distq = database.getDistanceQuery(relation, distFunction);
DBIDs ids = relation.getDBIDs();
WritableDataStore<KNNHeap<D>> knnHeaps = DataStoreUtil.makeStorage(ids, DataStoreFactory.HINT_TEMP | DataStoreFactory.HINT_HOT, KNNHeap.class);
try {
// data pages of s
List<E> ps_candidates = new ArrayList<E>(index.getLeaves());
FiniteProgress progress = logger.isVerbose() ? new FiniteProgress(this.getClass().getName(), relation.size(), logger) : null;
IndefiniteProgress pageprog = logger.isVerbose() ? new IndefiniteProgress("Number of processed data pages", logger) : null;
if(logger.isDebuggingFine()) {
logger.debugFine("# ps = " + ps_candidates.size());
}
// data pages of r
List<E> pr_candidates = ps_candidates;
if(logger.isDebuggingFine()) {
logger.debugFine("# pr = " + pr_candidates.size());
}
int processed = 0;
for(E pr_entry : pr_candidates) {
N pr = index.getNode(pr_entry);
D pr_knn_distance = distq.infiniteDistance();
if(logger.isDebuggingFinest()) {
logger.debugFinest("
}
// create for each data object a knn list
for(int j = 0; j < pr.getNumEntries(); j++) {
knnHeaps.put(((LeafEntry) pr.getEntry(j)).getDBID(), new KNNHeap<D>(k, distq.infiniteDistance()));
}
// Self-join first, as this is expected to improve most.
pr_knn_distance = processDataPages(distq, pr, pr, knnHeaps);
// TODO: bulk-load heap, even faster.
Heap<FCPair<D, E>> heap = new Heap<FCPair<D, E>>(ps_candidates.size());
for(E ps_entry : ps_candidates) {
if(ps_entry.equals(pr_entry)) {
continue;
}
D distance = distFunction.minDist(pr_entry, ps_entry);
heap.add(new FCPair<D, E>(distance, ps_entry));
}
// Use a heap, for partial sorting only:
while(heap.size() > 0) {
FCPair<D, E> pair = heap.poll();
// Stop
if(pair.first.compareTo(pr_knn_distance) > 0) {
heap.clear();
break;
}
N ps = index.getNode(pair.second);
pr_knn_distance = processDataPages(distq, pr, ps, knnHeaps);
}
if(logger.isDebuggingFine()) {
logger.debugFine("
}
processed += pr.getNumEntries();
if(progress != null && pageprog != null) {
progress.setProcessed(processed, logger);
pageprog.incrementProcessed(logger);
}
}
if(pageprog != null) {
pageprog.setCompleted(logger);
}
WritableDataStore<KNNList<D>> knnLists = DataStoreUtil.makeStorage(ids, DataStoreFactory.HINT_STATIC, KNNList.class);
for(DBID id : ids) {
knnLists.put(id, knnHeaps.get(id).toKNNList());
}
return knnLists;
}
catch(Exception e) {
throw new IllegalStateException(e);
}
}
/**
* Processes the two data pages pr and ps and determines the k-nearest
* neighbors of pr in ps.
*
* @param distQ the distance to use
* @param pr the first data page
* @param ps the second data page
* @param knnLists the knn lists for each data object
* @param pr_knn_distance the current knn distance of data page pr
* @return the k-nearest neighbor distance of pr in ps
*/
private D processDataPages(DistanceQuery<V, D> distQ, N pr, N ps, WritableDataStore<KNNHeap<D>> knnLists) {
D pr_knn_distance = null;
// TODO: optimize for double?
for(int i = 0; i < pr.getNumEntries(); i++) {
DBID r_id = ((LeafEntry) pr.getEntry(i)).getDBID();
KNNHeap<D> knnList = knnLists.get(r_id);
for(int j = 0; j < ps.getNumEntries(); j++) {
DBID s_id = ((LeafEntry) ps.getEntry(j)).getDBID();
D distance = distQ.distance(r_id, s_id);
knnList.add(distance, s_id);
}
// set kNN distance of r
if(pr_knn_distance == null) {
pr_knn_distance = knnList.getKNNDistance();
}
else {
pr_knn_distance = DistanceUtil.max(knnList.getKNNDistance(), pr_knn_distance);
}
}
return pr_knn_distance;
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD);
}
@Override
protected Logging getLogger() {
return logger;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer<V extends NumberVector<V, ?>, D extends Distance<D>, N extends SpatialNode<N, E>, E extends SpatialEntry> extends AbstractPrimitiveDistanceBasedAlgorithm.Parameterizer<V, D> {
protected int k;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
IntParameter kP = new IntParameter(K_ID, 1);
kP.addConstraint(new GreaterConstraint(0));
if(config.grab(kP)) {
k = kP.getValue();
}
}
@Override
protected KNNJoin<V, D, N, E> makeInstance() {
return new KNNJoin<V, D, N, E>(distanceFunction, k);
}
}
} |
package de.st_ddt.crazyplugin.data;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public abstract class PlayerData<S extends PlayerData<S>> implements PlayerDataInterface<S>
{
protected final String name;
public PlayerData(final String name)
{
super();
this.name = name;
}
@Override
public void show(final CommandSender target)
{
target.sendMessage(getShortInfo(new String[0]));
}
@Override
public void show(final CommandSender target, final String... args)
{
target.sendMessage(getShortInfo(args));
}
@Override
public String getShortInfo(final String... args)
{
return toString();
}
@Override
public Player getPlayer()
{
return Bukkit.getPlayerExact(getName());
}
@Override
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(getName());
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isOnline()
{
final Player player = getPlayer();
if (player == null)
return false;
return player.isOnline();
}
@Override
public String toString()
{
return "PlayerData " + getName();
}
} |
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import ca.mun.managment.StudentListGenerator;
import ca.mun.team.ProjectMember;
import ca.mun.team.Team;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
//Set Layout Manager
getContentPane().setLayout(new BorderLayout());
//Creating the panel to be implemented to the south
Panel southPanel = new Panel();
BorderLayout southLayout = new BorderLayout();
southPanel.setLayout(southLayout);
//panel for forcing students together
final Panel forcePanel = new Panel();
GridLayout forceLayout = new GridLayout(4,4);
forcePanel.setLayout(forceLayout);
forcePanel.setVisible(false);
southPanel.add(forcePanel,BorderLayout.NORTH); //adding the forcePanel to the southPanel
//Creating the panel for student/group outputs (CENTER)
Panel outputPanel = new Panel();
GridLayout outputLayout = new GridLayout(0,2);
outputPanel.setLayout(outputLayout);
//Output for student (scrolls)
final JTextArea textArea = new JTextArea("List of students");
JScrollPane scrollPane1 = new JScrollPane(textArea);
outputPanel.add(scrollPane1);
textArea.setLineWrap(true);
textArea.setEditable(false);
//Output for student groups (scrolls)
final JTextArea groupTextArea = new JTextArea("Optimal groups");
JScrollPane scrollPane2 = new JScrollPane(groupTextArea);
outputPanel.add(scrollPane2);
groupTextArea.setLineWrap(true);
groupTextArea.setEditable(false);
//Adding the panel to the window
getContentPane().add(outputPanel, BorderLayout.CENTER);
//Creating the Panel (NORTH)
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
GridLayout panelLayout = new GridLayout(3,2);
panel.setLayout(panelLayout);
//Adding components for the north panel
//Class Name
JLabel textArea1 = new JLabel("Class Name: ");
panel.add(textArea1);
final JTextField classNameInput = new JTextField();
panel.add(classNameInput);
//Group Size
JLabel textArea2 = new JLabel("Group Size: ");
panel.add(textArea2);
final JTextField groupSizeInput = new JTextField();
panel.add(groupSizeInput);
//Professor
JLabel textArea3 = new JLabel("Prof Name: ");
panel.add(textArea3);
final JLabel profNameText = new JLabel();
panel.add(profNameText);
//Buttons to start generating groups/importing class into JLabel
//importing and displaying text from file (or database, if needed)
JButton displayClassButton = new JButton("Load Class");
displayClassButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//checks if both class name and group size are filled in
if (classNameInput.getText().trim().length() == 0 || groupSizeInput.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(getContentPane(), "Please enter values for both class name and group size."); }
String text = groupSizeInput.getText();
//checks if the group size is an actual numeric value. If not, students will not be generated
if (isNumeric(text) != true) {
JOptionPane.showMessageDialog(getContentPane(), "Please enter a numberic value for the specified group size."); }
//if they are, set static variable and choose a file
else {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String fileName = f.getAbsolutePath();
try {
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
textArea.read(br, null);
br.close();
textArea.requestFocus();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
try {
String className = classNameInput.getText();
int groupSize = Integer.parseInt(groupSizeInput.getText());
String classInput = textArea.getText();
Controller.setGroupSize(groupSize); //sets the size of the groups
Controller.setString(classInput); //sets the String of students
Controller.setClassName(className); //sets the name of the class (ie. 3716)
Controller.createProject(); //calls the controller to create a new project
}
catch(Exception e) {}
profNameText.setText(StudentListGenerator.profName);
//here, we call to populate the forcePanel (since our project now has members within it)
ArrayList<ProjectMember> list = (ArrayList<ProjectMember>) Controller.project.getListOfMembers();
JLabel label1 = new JLabel("Student 1: ");
forcePanel.add(label1);
JComboBox combo1 = new JComboBox();
forcePanel.add(combo1);
JLabel label2 = new JLabel("Student 2: ");
forcePanel.add(label2);
JComboBox combo2 = new JComboBox();
forcePanel.add(combo2);
JRadioButton forceTogether = new JRadioButton("Force together");
JRadioButton forceApart = new JRadioButton("Force apart");
ButtonGroup group = new ButtonGroup();
group.add(forceTogether);
group.add(forceApart);
forcePanel.add(forceTogether);
forcePanel.add(forceApart);
JButton force = new JButton("Perform operation");
forcePanel.add(force);
//populating the JComboBoxes (for student selection)
for (int i = 0; i < list.size(); i++)
combo1.addItem(list.get(i).getName());
for (int i = 0; i < list.size(); i++)
combo2.addItem(list.get(i).getName());
}
});
//Button to generate optimal teams and output within the groupTextArea
JButton generateButton = new JButton("Generate Groups");
generateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(Controller.project == null) {
JOptionPane.showMessageDialog(getContentPane(), "Please enter a class before generating groups"); }
else if(Controller.project.getListOfMembers().size() < Controller.project.getSizeOfTeams()) {
JOptionPane.showMessageDialog(getContentPane(), "Please enter a smaller group size and reload the class."); }
else {
ArrayList<Team> list = new ArrayList<Team>();
if (Controller.project != null ) { //checking if a project has been created already (has a class been loaded into the system?)
list = (ArrayList<Team>) Controller.generateGroups(); } //generate groups using this project and store them in an ArrayList
groupTextArea.setText("");
//printing all the students within the groups and displaying them in the groupTextArea
for(Team t : list){
int i = Integer.parseInt(t.getNumber());
i = i+1;
groupTextArea.append("\n" + "Team: " + i + "\n");
for(Object m : t) {
ProjectMember mem = (ProjectMember)m;
groupTextArea.append(mem.getName() + "\n");
}
}
}
}
});
//Button to handle the forcing of groups by the professor
final JButton forceStudentsButton = new JButton("Set forced groups");
forceStudentsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (Controller.project == null) {
JOptionPane.showMessageDialog(getContentPane(), "Please load a class before you try to force groups.");
}
else {
if (forceStudentsButton.getText() == "Set forced groups") {
forcePanel.setVisible(true);
forceStudentsButton.setText("Close");
}
else if (forceStudentsButton.getText() == "Close") {
forcePanel.setVisible(false);
forceStudentsButton.setText("Set forced groups");
}
}
}
});
//Adding button panel to southPanel
JPanel buttonPanel = new JPanel();
buttonPanel.add(displayClassButton);
buttonPanel.add(generateButton);
buttonPanel.add(forceStudentsButton);
southPanel.add(buttonPanel, BorderLayout.SOUTH);
getContentPane().add(southPanel, BorderLayout.SOUTH);
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
} |
package li.aop;
import li.ioc.Ioc;
import li.test.BaseTest;
import org.junit.Test;
public class AopTest extends BaseTest {
@Test
public void testAop() {
final Account account = Ioc.get(Account.class);
account.list(null);
}
@Test
public void testAop2() {
User user = Ioc.get(User.class);
System.out.println(user.sayHi("abc", "xyz"));
}
public static void main(String[] args) throws Exception {
final Account account = Ioc.get(Account.class);
account.list(null);
for (int i = 0; i < 100; i++) {
Thread.sleep(300);
new Thread() {
public void run() {
for (; true;) {
final Account account = Ioc.get(Account.class);
account.list(null);
}
}
}.start();
}
}
} |
package rhomobile.mapview;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.rubyext.WebView;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class MapViewScreen extends MainScreen {
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("MapViewScreen");
private static final int PAN_MODE = 1;
private static final int ZOOM_MODE = 2;
private static final int MIN_MOVE_STEP = 1;
private static final int MAX_MOVE_STEP = 8;
private static final int MOVE_TIMEOUT_DOUBLING = 300;
// Sensivity of annotations area (in pixels)
private static final int ANNOTATION_SENSIVITY_AREA_RADIUS = 16;
private static final MapProvider[] providers = {
new GoogleMapProvider(),
new ESRIMapProvider()
};
private MapViewParent parent;
private MapProvider mapProvider;
private RhoMapField mapField;
private GeoCoding mapGeoCoding;
private Vector annotations = new Vector();
private Annotation mSelectedAnnotation;
private int mode;
private long prevMoveTime = 0;
private int prevDx = 0;
private int prevDy = 0;
private Bitmap mapPinImage;
private boolean mTouchDown = false;
private int mTouchX;
private int mTouchY;
private class PanModeMenuItem extends MenuItem {
private MapViewScreen screen;
public PanModeMenuItem(MapViewScreen scr, int ordinal, int priority) {
super("Pan mode", ordinal, priority);
screen = scr;
}
public void run() {
screen.setMode(MapViewScreen.PAN_MODE);
}
};
private class ZoomModeMenuItem extends MenuItem {
private MapViewScreen screen;
public ZoomModeMenuItem(MapViewScreen scr, int ordinal, int priority) {
super("Zoom mode", ordinal, priority);
screen = scr;
}
public void run() {
screen.setMode(MapViewScreen.ZOOM_MODE);
}
};
MapViewScreen(MapViewParent p, String providerName, Hashtable settings, Vector annotations) {
super(DEFAULT_MENU | DEFAULT_CLOSE);
addMenuItem(new PanModeMenuItem(this, 0, 100));
addMenuItem(new ZoomModeMenuItem(this, 1, 100));
mapPinImage = Bitmap.getBitmapResource("mappin.png");
mapParent = p;
createMapProvider(providerName);
mapGeoCoding = new GoogleGeoCoding();
createUI(settings);
this.annotations = annotations;
handleAnnotations();
}
public void close() {
mapField.close();
mapGeoCoding.stop();
mapParent.onChildClosed();
super.close();
parent.childClosed();
}
private void setMode(int m) {
mode = m;
mapField.redraw();
}
private void createMapProvider(String providerName) {
mapProvider = null;
for (int i = 0; i != providers.length; ++i) {
if (providers[i].accept(providerName)) {
mapProvider = providers[i];
break;
}
}
if (mapProvider == null)
throw new IllegalArgumentException("Unknown map provider: " + providerName);
}
private void createUI(Hashtable settings) {
synchronized (Application.getEventLock()) {
mapField = mapProvider.createMap();
mapField.setPreferredSize(Display.getWidth(), Display.getHeight());
add(mapField.getBBField());
}
// Set map type
String map_type = (String)settings.get("map_type");
if (map_type == null)
map_type = "roadmap";
mapField.setMapType(map_type);
Hashtable region = (Hashtable)settings.get("region");
if (region != null) {
// Set coordinates
Double lat = (Double)region.get("latitude");
Double lon = (Double)region.get("longitude");
if (lat != null && lon != null)
mapField.moveTo(lat.doubleValue(), lon.doubleValue());
// Set zoom
Double latDelta = (Double)region.get("latDelta");
Double lonDelta = (Double)region.get("lonDelta");
if (latDelta != null && lonDelta != null) {
int zoom = mapField.calculateZoom(latDelta.doubleValue(), lonDelta.doubleValue());
mapField.setZoom(zoom);
}
}
Double radius = (Double)settings.get("radius");
if (radius != null) {
int zoom = mapField.calculateZoom(radius.doubleValue(), radius.doubleValue());
mapField.setZoom(zoom);
}
String center = (String)settings.get("center");
if (center != null) {
mapGeoCoding.resolve(center, new GeoCoding.OnGeocodingDone() {
public void onSuccess(double latitude, double longitude) {
mapField.moveTo(latitude, longitude);
}
public void onError(String description) {}
});
}
mode = PAN_MODE;
mapField.redraw();
}
private void handleAnnotations() {
Enumeration e = annotations.elements();
while (e.hasMoreElements()) {
final Annotation ann = (Annotation)e.nextElement();
if (ann == null)
continue;
if (ann.street_address == null && ann.coordinates == null)
continue;
if (ann.street_address != null && ann.street_address.length() > 0)
mapGeoCoding.resolve(ann.street_address, new GeoCoding.OnGeocodingDone() {
public void onSuccess(double latitude, double longitude) {
ann.coordinates = new Annotation.Coordinates(latitude, longitude);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
invalidate();
}
});
}
public void onError(String description) {
ann.street_address = null;
}
});
}
}
/**
* Handle trackball click events.
* @see net.rim.device.api.ui.Screen#invokeAction(int)
*/
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(!handled)
{
switch(action)
{
case ACTION_INVOKE: // Trackball click.
{
return true;
}
}
}
return handled;
}
protected void paint(Graphics graphics) {
super.paint(graphics);
// Draw annotations
int pinWidth = mapPinImage.getWidth();
int pinHeight = mapPinImage.getHeight();
Enumeration e = annotations.elements();
while (e.hasMoreElements()) {
Annotation ann = (Annotation)e.nextElement();
if (ann == null || ann.coordinates == null)
continue;
long x = mapField.toScreenCoordinateX(ann.coordinates.longitude);
if (x + pinWidth/2 < 0 || x - pinWidth/2 > mapField.getWidth())
continue;
long y = mapField.toScreenCoordinateY(ann.coordinates.latitude);
if (y + pinHeight/2 < 0 || y - pinHeight/2 > mapField.getHeight())
continue;
graphics.drawBitmap((int)(x - pinWidth/2), (int)(y - pinHeight/2), pinWidth, pinHeight, mapPinImage, 0, 0);
}
if (mSelectedAnnotation != null)
drawTitle(graphics, mSelectedAnnotation);
graphics.setColor(Color.BLACK);
// Draw current mode
String strMode = null;
if (mode == PAN_MODE)
strMode = "Pan mode";
else if (mode == ZOOM_MODE)
strMode = "Zoom mode";
if (strMode != null) {
// Detect drawn text size
int tw = graphics.getFont().getAdvance(strMode);
int th = graphics.getFont().getHeight();
// Actual drawing
int x = mapField.getLeft() + mapField.getWidth()/2 - tw/2;
int y = mapField.getTop() + mapField.getHeight() - th - 10;
tw = graphics.drawText(strMode, x, y);
}
}
private void fillRectWithRoundedCorners(Graphics graphics, int left, int top, int width, int height, int roundRadius) {
final int r = roundRadius;
final int d = r*2;
final int right = left + width;
final int bottom = top + height;
graphics.fillArc(left - r, top - r, d, d, 90, 90);
graphics.fillArc(left - r, bottom - r, d, d, 180, 90);
graphics.fillArc(right - r, bottom - r, d, d, 270, 90);
graphics.fillArc(right - r, top - r, d, d, 0, 90);
graphics.fillRect(left - r, top, r, bottom - top);
graphics.fillRect(right, top, r, bottom - top);
graphics.fillRect(left, top - r, right - left, r);
graphics.fillRect(left, bottom, right - left, r);
graphics.fillRect(left, top, right - left, bottom - top);
}
private void drawRectWithRoundedCorners(Graphics graphics, int left, int top, int width, int height, int roundRadius) {
final int r = roundRadius;
final int d = r*2;
final int right = left + width;
final int bottom = top + height;
graphics.drawArc(left - r, top - r, d, d, 90, 90);
graphics.drawArc(left - r, bottom - r, d, d, 180, 90);
graphics.drawArc(right - r, bottom - r, d, d, 270, 90);
graphics.drawArc(right - r, top - r, d, d, 0, 90);
graphics.drawLine(left - r, top, left - r, bottom);
graphics.drawLine(right + r, top, right + r, bottom);
graphics.drawLine(left, top - r, right, top - r);
graphics.drawLine(left, bottom + r, right, bottom + r);
}
private void drawTitle(Graphics graphics, Annotation ann) {
String textToDraw = ann.title;
int width = graphics.getFont().getAdvance(textToDraw);
int height = graphics.getFont().getHeight();
int annX = (int)mapField.toScreenCoordinateX(ann.coordinates.longitude);
int annY = (int)mapField.toScreenCoordinateY(ann.coordinates.latitude);
int left = annX - width/2;
int top = annY - height/2 - mapPinImage.getHeight()/2;
final int roundRadius = 6;
// Shadow
graphics.setColor(Color.GRAY);
fillRectWithRoundedCorners(graphics, left + 4, top + 4, width, height, roundRadius);
// Actual shape
graphics.setColor(Color.WHITE);
fillRectWithRoundedCorners(graphics, left, top, width, height, roundRadius);
graphics.setColor(Color.BLACK);
drawRectWithRoundedCorners(graphics, left, top, width, height, roundRadius);
graphics.setColor(Color.BLACK);
graphics.drawText(textToDraw, left, top);
}
private int calcDxSmooth(int dx, long curTime) {
int newDx;
if (curTime > prevMoveTime + MOVE_TIMEOUT_DOUBLING) {
newDx = dx;
}
else {
if (dx == 0)
newDx = 0;
else {
newDx = dx < 0 ? (prevDx < 0 ? prevDx*2 : -MIN_MOVE_STEP) : (prevDx > 0 ? prevDx*2 : MIN_MOVE_STEP);
if (newDx < -MAX_MOVE_STEP)
newDx = -MAX_MOVE_STEP;
else if (newDx > MAX_MOVE_STEP)
newDx = MAX_MOVE_STEP;
}
}
prevDx = newDx;
return newDx;
}
private int calcDySmooth(int dy, long curTime) {
int newDy;
if (curTime > prevMoveTime + MOVE_TIMEOUT_DOUBLING) {
newDy = dy;
}
else {
if (dy == 0)
newDy = 0;
else {
newDy = dy < 0 ? (prevDy < 0 ? prevDy*2 : -MIN_MOVE_STEP) : (prevDy > 0 ? prevDy*2 : MIN_MOVE_STEP);
if (newDy < -MAX_MOVE_STEP)
newDy = -MAX_MOVE_STEP;
else if (newDy > MAX_MOVE_STEP)
newDy = MAX_MOVE_STEP;
}
}
prevDy = newDy;
return newDy;
}
private int calcDx(int dx, long curTime) {
//return dx*2;
return calcDxSmooth(dx, curTime);
}
private int calcDy(int dy, long curTime) {
//return dy*2;
return calcDySmooth(dy, curTime);
}
private void handleMove(int dx, int dy) {
if (mode == PAN_MODE) {
//LOG.TRACE("Scroll by " + dx + "," + dy);
mapField.move(dx, dy);
mapField.redraw();
}
else if (mode == ZOOM_MODE && dy != 0) {
int currentZoom = mapField.getZoom();
int minZoom = mapField.getMinZoom();
int maxZoom = mapField.getMaxZoom();
int newZoom;
if (dy > 0) {
newZoom = Math.max(currentZoom - 1, minZoom);
}
else {
newZoom = Math.min(currentZoom + 1, maxZoom);
}
//LOG.TRACE("Set zoom to " + newZoom + " (was " + currentZoom + ")");
mapField.setZoom(newZoom);
mapField.redraw();
}
}
private void handleClick(int x, int y) {
Annotation a = getCurrentAnnotation(x, y);
Annotation selectedAnnotation = mSelectedAnnotation;
mSelectedAnnotation = a;
if (a != null && selectedAnnotation != null && selectedAnnotation.equals(a)) {
// We have clicked already selected annotation
WebView.navigate(a.url);
mapParent.close();
mSelectedAnnotation = null;
}
invalidate();
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
if ((status & KeypadListener.STATUS_TRACKWHEEL) == 0 &&
(status & KeypadListener.STATUS_FOUR_WAY) == 0)
return false;
if (mode == PAN_MODE) {
long curTime = System.currentTimeMillis();
dx = calcDx(dx, curTime);
dy = calcDy(dy, curTime);
prevMoveTime = curTime;
}
handleMove(dx, dy);
return true;
}
protected boolean trackwheelClick(int status, int time) {
int x = getWidth()/2;
int y = getHeight()/2;
handleClick(x, y);
return true;
}
protected boolean touchEvent(TouchEvent message) {
switch (message.getEvent()) {
case TouchEvent.CLICK:
handleClick(message.getX(1), message.getY(1));
return true;
case TouchEvent.DOWN:
mTouchDown = true;
mTouchX = message.getX(1);
mTouchY = message.getY(1);
break;
case TouchEvent.UP:
mTouchDown = false;
break;
case TouchEvent.MOVE:
if (mTouchDown) {
int x = message.getX(1);
int y = message.getY(1);
int dx = x - mTouchX;
int dy = y - mTouchY;
if (mode == PAN_MODE) {
dx = -dx;
dy = -dy;
}
handleMove(dx, dy);
mTouchX = x;
mTouchY = y;
return true;
}
}
return super.touchEvent(message);
}
public double getCenterLatitude() {
return mapField.getCenterLatitude();
}
public double getCenterLongitude() {
return mapField.getCenterLongitude();
}
private Annotation getCurrentAnnotation(int x, int y) {
// return current annotation (point we are under now)
Enumeration e = annotations.elements();
while (e.hasMoreElements()) {
Annotation a = (Annotation)e.nextElement();
Annotation.Coordinates coords = a.coordinates;
if (coords == null)
continue;
long annX = mapField.toScreenCoordinateX(coords.longitude);
long annY = mapField.toScreenCoordinateY(coords.latitude);
annY -= mapPinImage.getHeight()/2;
long deltaX = (long)x - annX;
long deltaY = (long)y - annY;
double distance = MapTools.math_sqrt(deltaX*deltaX + deltaY*deltaY);
if ((int)distance > ANNOTATION_SENSIVITY_AREA_RADIUS)
continue;
return a;
}
return null;
}
} |
package com.triggertrap.seekarc;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
*
* SeekArc.java
*
* This is a class that functions much like a SeekBar but
* follows a circle path instead of a straight line.
*
* @author Neil Davies
*
*/
public class SeekArc extends View {
private static final String TAG = SeekArc.class.getSimpleName();
private static int INVALID_PROGRESS_VALUE = -1;
// The initial rotational offset -90 means we start at 12 o'clock
private final int mAngleOffset = -90;
/**
* The Drawable for the seek arc thumbnail
*/
private Drawable mThumb;
/**
* The Maximum value that this SeekArc can be set to
*/
private int mMax = 100;
/**
* The Current value that the SeekArc is set to
*/
private int mProgress = 0;
/**
* The width of the progress line for this SeekArc
*/
private int mProgressWidth = 4;
/**
* The Width of the background arc for the SeekArc
*/
private int mArcWidth = 2;
/**
* The dimension of allowance that the arc will accept inputs outside of the arc drawing
*/
private int mArcAllowance = 0;
/**
* The Angle to start drawing this Arc from
*/
private int mStartAngle = 0;
/**
* The Angle through which to draw the arc (Max is 360)
*/
private int mSweepAngle = 360;
/**
* The rotation of the SeekArc- 0 is twelve o'clock
*/
private int mRotation = 0;
/**
* Give the SeekArc rounded edges
*/
private boolean mRoundedEdges = false;
/**
* Enable touch inside the SeekArc
*/
private boolean mTouchInside = true;
/**
* Will the progress increase clockwise or anti-clockwise
*/
private boolean mClockwise = true;
/**
* is the control enabled/touchable
*/
private boolean mEnabled = true;
private boolean mDragging = false;
// Internal variables
private int mArcRadius = 0;
private float mProgressSweep = 0;
private float mProposedSweep = 0;
private RectF mArcRect = new RectF();
private Paint mArcPaint;
private Paint mProgressPaint;
private Paint mProposedPaint;
private int mTranslateX;
private int mTranslateY;
private int mThumbXPos;
private int mThumbYPos;
private double mTouchAngle;
private float mTouchIgnoreRadius;
private float mTouchOuterRadius;
private OnSeekArcChangeListener mOnSeekArcChangeListener;
public interface OnSeekArcChangeListener {
/**
* Notification that the progress level has changed. Clients can use the
* fromUser parameter to distinguish user-initiated changes from those
* that occurred programmatically.
*
* @param seekArc
* The SeekArc whose progress has changed
* @param progress
* The current progress level. This will be in the range
* 0..max where max was set by
* {@link SeekArc#setMax(int)}. (The default value for
* max is 100.)
* @param fromUser
* True if the progress change was initiated by the user.
*/
void onProgressChanged(SeekArc seekArc, int progress, boolean fromUser);
/**
* Notification that the user has started a touch gesture. Clients may
* want to use this to disable advancing the seekbar.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStartTrackingTouch(SeekArc seekArc);
/**
* Notification that the user has finished a touch gesture. Clients may
* want to use this to re-enable advancing the seekarc.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStopTrackingTouch(SeekArc seekArc);
}
public SeekArc(Context context) {
super(context);
init(context, null, 0);
}
public SeekArc(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, R.attr.seekArcStyle);
}
public SeekArc(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
Log.d(TAG, "Initialising SeekArc");
final Resources res = getResources();
float density = context.getResources().getDisplayMetrics().density;
// Defaults, may need to link this into theme settings
int arcColor = res.getColor(R.color.progress_gray);
int progressColor = res.getColor(R.color.default_blue_light);
int proposedColor = res.getColor(R.color.proposed_red);
int thumbHalfheight;
int thumbHalfWidth;
mThumb = res.getDrawable(R.drawable.seek_arc_control_selector);
// Convert progress width to pixels for current density
mProgressWidth = (int) (mProgressWidth * density);
if (attrs != null) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SeekArc, defStyle, 0);
Drawable thumb = a.getDrawable(R.styleable.SeekArc_thumb);
if (thumb != null) {
mThumb = thumb;
}
thumbHalfheight = mThumb.getIntrinsicHeight() / 2;
thumbHalfWidth = mThumb.getIntrinsicWidth() / 2;
mThumb.setBounds(-thumbHalfWidth, -thumbHalfheight, thumbHalfWidth,
thumbHalfheight);
mMax = a.getInteger(R.styleable.SeekArc_max, mMax);
mProgress = a.getInteger(R.styleable.SeekArc_progress, mProgress);
mProgressWidth = (int) a.getDimension(R.styleable.SeekArc_progressWidth,
mProgressWidth);
mArcWidth = (int) a.getDimension(R.styleable.SeekArc_arcWidth,
mArcWidth);
mArcAllowance = (int) a.getDimension(R.styleable.SeekArc_arcAllowance,
mArcAllowance);
mStartAngle = a.getInt(R.styleable.SeekArc_startAngle, mStartAngle);
mSweepAngle = a.getInt(R.styleable.SeekArc_sweepAngle, mSweepAngle);
mRotation = a.getInt(R.styleable.SeekArc_rotation, mRotation);
mRoundedEdges = a.getBoolean(R.styleable.SeekArc_roundEdges,
mRoundedEdges);
mTouchInside = a.getBoolean(R.styleable.SeekArc_touchInside,
mTouchInside);
mClockwise = a.getBoolean(R.styleable.SeekArc_clockwise,
mClockwise);
mEnabled = a.getBoolean(R.styleable.SeekArc_enabled, mEnabled);
arcColor = a.getColor(R.styleable.SeekArc_arcColor, arcColor);
progressColor = a.getColor(R.styleable.SeekArc_progressColor, progressColor);
proposedColor = a.getColor(R.styleable.SeekArc_proposedColor, proposedColor);
a.recycle();
}
mProgress = (mProgress > mMax) ? mMax : mProgress;
mProgress = (mProgress < 0) ? 0 : mProgress;
mSweepAngle = (mSweepAngle > 360) ? 360 : mSweepAngle;
mSweepAngle = (mSweepAngle < 0) ? 0 : mSweepAngle;
mProgressSweep = (float) mProgress / mMax * mSweepAngle;
mStartAngle = (mStartAngle > 360) ? 0 : mStartAngle;
mStartAngle = (mStartAngle < 0) ? 0 : mStartAngle;
// Dotted lines effect ish
// PathEffect effect = new DashPathEffect(new float[]{50, 50}, 0);
mArcPaint = new Paint();
mArcPaint.setColor(arcColor);
mArcPaint.setAntiAlias(true);
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setStrokeWidth(mArcWidth);
//mArcPaint.setPathEffect(effect);
//mArcPaint.setAlpha(45);
mProgressPaint = new Paint();
mProgressPaint.setColor(progressColor);
mProgressPaint.setAntiAlias(true);
mProgressPaint.setStyle(Paint.Style.STROKE);
mProgressPaint.setStrokeWidth(mProgressWidth);
//mProgressPaint.setPathEffect(effect);
mProposedPaint = new Paint();
mProposedPaint.setColor(proposedColor);
mProposedPaint.setAntiAlias(true);
mProposedPaint.setStyle(Paint.Style.STROKE);
mProposedPaint.setStrokeWidth(mProgressWidth);
//mProposedPaint.setPathEffect(effect);
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
mProposedPaint.setStrokeCap(Paint.Cap.ROUND);
}
}
@Override
protected void onDraw(Canvas canvas) {
if(!mClockwise) {
canvas.scale(-1, 1, mArcRect.centerX(), mArcRect.centerY() );
}
// Draw the arcs
final int arcStart = mStartAngle + mAngleOffset + mRotation;
final int arcSweep = mSweepAngle;
canvas.drawArc(mArcRect, arcStart, arcSweep, false, mArcPaint);
canvas.drawArc(mArcRect, arcStart, mProgressSweep, false, mProgressPaint);
if (mDragging) {
// start: at the current progress degree
// sweep: only the different between the proposed and current progress.
// swap the polarity of the sweep.
canvas.drawArc(
mArcRect,
arcStart + mProgressSweep,
-(mProgressSweep - mProposedSweep),
false,
mProposedPaint
);
}
if(mEnabled) {
// Draw the thumb nail
canvas.translate(mTranslateX - mThumbXPos, mTranslateY - mThumbYPos);
mThumb.draw(canvas);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int height = getDefaultSize(getSuggestedMinimumHeight(),
heightMeasureSpec);
final int width = getDefaultSize(getSuggestedMinimumWidth(),
widthMeasureSpec);
final int min = Math.min(width, height);
float top;
float left;
float arcRadius;
int arcDiameter;
mTranslateX = (int) (width * 0.5f);
mTranslateY = (int) (height * 0.5f);
arcDiameter = min - getPaddingLeft();
arcRadius = arcDiameter / 2;
top = height / 2 - arcRadius;
left = width / 2 - arcRadius;
mArcRadius = (int)arcRadius;
mTouchOuterRadius = mArcRadius + mArcWidth + mArcAllowance;
mArcRect.set(left, top, left + arcDiameter, top + arcDiameter);
float sweep = mDragging ? mProposedSweep : mProgressSweep;
int arcStart = (int)sweep + mStartAngle + mRotation + 90;
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(arcStart)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(arcStart)));
setTouchInSide(mTouchInside);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mEnabled) {
this.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onStartTrackingTouch();
updateOnTouch(event);
break;
case MotionEvent.ACTION_MOVE:
updateOnTouch(event);
break;
case MotionEvent.ACTION_UP:
onStopTrackingTouch();
updateOnTouch(event);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
case MotionEvent.ACTION_CANCEL:
updateOnTouch(event);
onStopTrackingTouch();
setPressed(false);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return true;
}
return false;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mThumb != null && mThumb.isStateful()) {
int[] state = getDrawableState();
mThumb.setState(state);
}
invalidate();
}
private void onStartTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStartTrackingTouch(this);
}
}
private void onStopTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStopTrackingTouch(this);
}
}
private void updateOnTouch(MotionEvent event) {
float x = event.getX();
float y = event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
if (action == MotionEvent.ACTION_DOWN && ignoreTouch(x, y))
return;
setPressed(true);
mDragging = true;
}
else {
setPressed(false);
mDragging = false;
}
mTouchAngle = getTouchDegrees(x, y);
onProgressRefresh(getProgressForAngle(mTouchAngle), true);
}
private boolean ignoreTouch(float xPos, float yPos) {
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
float touchRadius = (float) Math.sqrt(((x * x) + (y * y)));
boolean ignore = false;
if (touchRadius < mTouchIgnoreRadius || touchRadius > mTouchOuterRadius) {
ignore = true;
}
return ignore;
}
private double getTouchDegrees(float xPos, float yPos) {
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
//invert the x-coord if we are rotating anti-clockwise
x = (mClockwise) ? x : -x;
// convert to arc Angle
double angle = Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2)
- Math.toRadians(mRotation));
if (angle < 0) {
angle = 360 + angle;
}
angle -= mStartAngle;
return angle;
}
private int getProgressForAngle(double angle) {
int touchProgress = (int) Math.round(valuePerDegree() * angle);
touchProgress = (touchProgress < 0) ? INVALID_PROGRESS_VALUE : touchProgress;
touchProgress = (touchProgress > mMax) ? INVALID_PROGRESS_VALUE : touchProgress;
if (!mDragging)
touchProgress = touchProgress == INVALID_PROGRESS_VALUE ? 0 : touchProgress;
return touchProgress;
}
private float valuePerDegree() {
return (float) mMax / mSweepAngle;
}
private void onProgressRefresh(int progress, boolean fromUser) {
if (mDragging)
updateDelta(progress, fromUser);
else
updateProgress(progress, fromUser);
}
private void updateThumbPosition() {
float sweep;
int angle;
sweep = mDragging ? mProposedSweep : mProgressSweep;
angle = (int) (mStartAngle + sweep + mRotation + 90);
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(angle)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(angle)));
}
private void updateProgress(int progress, boolean fromUser) {
if (progress == INVALID_PROGRESS_VALUE) {
return;
}
progress = (progress > mMax) ? mMax : progress;
progress = (progress < 0) ? 0 : progress;
mProgress = progress;
if (mOnSeekArcChangeListener != null)
mOnSeekArcChangeListener.onProgressChanged(this, progress, fromUser);
mProgressSweep = (float) progress / mMax * mSweepAngle;
updateThumbPosition();
invalidate();
}
private void updateDelta(int progress, boolean fromUser) {
if (progress == INVALID_PROGRESS_VALUE)
return;
progress = progress > mMax ? mMax : progress;
progress = progress < 0 ? 0 : progress;
mProgress = progress;
if (mOnSeekArcChangeListener != null)
mOnSeekArcChangeListener.onProgressChanged(this, progress, fromUser);
mProposedSweep = (float) progress / mMax * mSweepAngle;
updateThumbPosition();
invalidate();
}
/**
* Sets a listener to receive notifications of changes to the SeekArc's
* progress level. Also provides notifications of when the user starts and
* stops a touch gesture within the SeekArc.
*
* @param l
* The seek bar notification listener
*
* @see SeekArc.OnSeekArcChangeListener
*/
public void setOnSeekArcChangeListener(OnSeekArcChangeListener l) {
mOnSeekArcChangeListener = l;
}
public void setProgress(int progress) {
updateProgress(progress, false);
}
public int getProgress() {
return mProgress;
}
public int getProgressWidth() {
return mProgressWidth;
}
public void setProgressWidth(int mProgressWidth) {
this.mProgressWidth = mProgressWidth;
mProgressPaint.setStrokeWidth(mProgressWidth);
}
public int getArcWidth() {
return mArcWidth;
}
public void setArcWidth(int mArcWidth) {
this.mArcWidth = mArcWidth;
mArcPaint.setStrokeWidth(mArcWidth);
}
public int getArcRotation() {
return mRotation;
}
public void setArcRotation(int mRotation) {
this.mRotation = mRotation;
updateThumbPosition();
}
public int getStartAngle() {
return mStartAngle;
}
public void setStartAngle(int mStartAngle) {
this.mStartAngle = mStartAngle;
updateThumbPosition();
}
public int getSweepAngle() {
return mSweepAngle;
}
public void setSweepAngle(int mSweepAngle) {
this.mSweepAngle = mSweepAngle;
updateThumbPosition();
}
public void setRoundedEdges(boolean isEnabled) {
mRoundedEdges = isEnabled;
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
} else {
mArcPaint.setStrokeCap(Paint.Cap.SQUARE);
mProgressPaint.setStrokeCap(Paint.Cap.SQUARE);
}
}
public void setTouchInSide(boolean isEnabled) {
int thumbHalfheight = mThumb.getIntrinsicHeight() / 2;
int thumbHalfWidth = mThumb.getIntrinsicWidth() / 2;
mTouchInside = isEnabled;
if (mTouchInside) {
mTouchIgnoreRadius = (float) mArcRadius / 4;
} else {
// Don't use the exact radius makes interaction too tricky
mTouchIgnoreRadius = mArcRadius
- Math.min(thumbHalfWidth, thumbHalfheight);
}
}
public void setClockwise(boolean isClockwise) {
mClockwise = isClockwise;
}
public boolean isClockwise() {
return mClockwise;
}
public boolean isEnabled() {
return mEnabled;
}
public void setEnabled(boolean enabled) {
this.mEnabled = enabled;
}
public int getProgressColor() {
return mProgressPaint.getColor();
}
public void setProgressColor(int color) {
mProgressPaint.setColor(color);
invalidate();
}
public int getArcColor() {
return mArcPaint.getColor();
}
public void setArcColor(int color) {
mArcPaint.setColor(color);
invalidate();
}
public int getMax() {
return mMax;
}
public void setMax(int mMax) {
this.mMax = mMax;
}
} |
package org.jetel.data;
import java.io.UnsupportedEncodingException;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import org.jetel.exception.BadDataFormatException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.bytes.ByteBufferUtils;
import org.jetel.util.bytes.CloverBuffer;
import org.jetel.util.string.Compare;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* A class that represents array of bytes field.<br>
* <br>
* <i>Note: it has no sence to test this field for null value as even all zeros
* can indicate meaningful value. Yet, the isNull & setNull is implemented.
*
*@author D.Pavlis
*@created January 26, 2003
*@since October 29, 2002
*@see org.jetel.metadata.DataFieldMetadata
*/
@SuppressWarnings("EI")
public class ByteDataField extends DataField implements Comparable<Object> {
private static final long serialVersionUID = 3823545028385612760L;
/**
* Description of the Field
*
*@since October 29, 2002
*/
protected byte[] value;
protected final static int INITIAL_BYTE_ARRAY_CAPACITY = 8;
/**
* Constructor for the NumericDataField object
*
*@param _metadata Metadata describing field
*@since October 29, 2002
*/
public ByteDataField(DataFieldMetadata _metadata){
this(_metadata, false);
}
/**
* Constructor for the NumericDataField object
*
* @param _metadata Metadata describing field
* @param plain <i>not used (only for compatibility reason)</i>
*/
public ByteDataField(DataFieldMetadata _metadata, boolean plain) {
super(_metadata);
reset();
}
/**
* Constructor for the NumericDataField object
*
*@param _metadata Metadata describing field
*@param value Value to assign to field
*@since October 29, 2002
*/
public ByteDataField(DataFieldMetadata _metadata, byte[] value) {
super(_metadata);
setValue(value);
}
private void prepareBuf() {
if (this.value == null) {
int len = metadata.getSize();
this.value = new byte[len > 0 ? len : INITIAL_BYTE_ARRAY_CAPACITY];
}
}
private void prepareBuf(CloverBuffer newValue) {
this.value = new byte[newValue.remaining()];
}
@Override
public DataField duplicate(){
return new ByteDataField(metadata, value);
}
/**
* @see org.jetel.data.DataField#copyField(org.jetel.data.DataField)
* @deprecated use setValue(DataField) instead
*/
@Override
public void copyFrom(DataField fromField){
if (fromField instanceof ByteDataField && !(fromField instanceof CompressedByteDataField) && !(this instanceof CompressedByteDataField)){
if (!fromField.isNull){
int length = ((ByteDataField) fromField).value.length;
if (this.value == null || this.value.length != length){
this.value = new byte[length];
}
System.arraycopy(((ByteDataField) fromField).value,
0, this.value, 0, length);
}
setNull(fromField.isNull);
} else {
super.copyFrom(fromField);
}
}
@Override
public void setNull(boolean isNull) {
super.setNull(isNull);
if (this.isNull) {
value = null;
}
}
/**
* Sets the value of the field - accepts byte[], Byte, Byte[]
*
*@param _value The new value
*@since October 29, 2002
*/
@Override
public void setValue(Object value) {
if(value == null) {
setNull(true);
}else if (value instanceof byte[]){
setValue((byte[])value);
}else if(value instanceof Byte) {
setValue(((Byte) value).byteValue());
} else if(value instanceof Byte[]) {
//convert Byte[] into byte[]
Byte[] valueByte = (Byte[]) value;
byte[] result = new byte[valueByte.length];
int i = 0;
for(Byte b : valueByte) {
result[i++] = b.byteValue();
}
setValue(result);
}else {
BadDataFormatException ex = new BadDataFormatException("Not a byte/byte_array " + value.getClass().getName());
ex.setFieldNumber(getMetadata().getNumber());
throw ex;
}
}
@Override
public void setValue(DataField fromField) {
if (fromField instanceof ByteDataField && !(fromField instanceof CompressedByteDataField) && !(this instanceof CompressedByteDataField)){
if (!fromField.isNull){
int length = ((ByteDataField) fromField).value.length;
if (this.value == null || this.value.length != length){
this.value = new byte[length];
}
System.arraycopy(((ByteDataField) fromField).value,
0, this.value, 0, length);
}
setNull(fromField.isNull);
} else {
super.setValue(fromField);
}
}
/**
* Sets the value of the field
*
*@param value value is copied into internal byte array using
* System.arraycopy method
*@since October 29, 2002
*/
public void setValue(byte[] value) {
if(value != null) {
this.value = new byte[value.length];
System.arraycopy(value, 0, this.value, 0, value.length);
setNull(false);
} else {
setNull(true);
}
}
/**
* Sets the value of the field
*
*@param value The new byte value - the whole byte array is filled with this
* value
*@since October 29, 2002
*/
public void setValue(byte value) {
prepareBuf();
Arrays.fill(this.value, value);
setNull(false);
}
@Override
public void reset(){
if (metadata.isNullable()){
setNull(true);
}else if (metadata.isDefaultValueSet()){
setToDefaultValue();
}else{
value = null;
}
}
/**
* Gets the Field Type
*
*@return The Type value
*@since October 29, 2002
*/
@Override
public char getType() {
return DataFieldMetadata.BYTE_FIELD;
}
/**
* Gets the value represented by this object (as byte[] object)
*
*@return The Value value
*@since October 29, 2002
*/
@Override
public byte[] getValue() {
return isNull ? null : getByteArray();
}
/**
* @see org.jetel.data.DataField#getValueDuplicate()
*/
@Override
public byte[] getValueDuplicate() {
if(isNull) {
return null;
}
byte[] ret = new byte[value.length];
System.arraycopy(value, 0, ret, 0, value.length);
return ret;
}
/**
* Gets the byte value represented by this object as byte primitive
*
*@param position offset in byte array
*@return The Byte value
*@since October 29, 2002
*/
public byte getByte(int position) {
if(isNull) {
return 0;
}
return getByteArray()[position];
}
/**
* Gets the Byte array value of the ByteDataField object
*
*@return The Byte[] value
*@since October 29, 2002
*/
public byte[] getByteArray() {
return value;
}
/**
* Formats internal byte array value into string representation
*
*@return String representation of byte array
*@since October 29, 2002
*/
@Override
public String toString() {
return toString(Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
}
/**
* Formats internal byte array value into string representation
*
* @param charset charset to be used for converting bytes into String
* @return String representation of byte array
* @since 19.11.2006
*/
public String toString(String charset) {
if (isNull()) {
return metadata.getNullValue();
}
try{
return new String(getByteArray(),charset);
}catch(UnsupportedEncodingException ex){
throw new RuntimeException(ex.toString()+" when calling toString() on field \""+
this.metadata.getName()+"\"",ex);
}
}
@Override
public void fromString(CharSequence seq) {
fromString(seq, Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
}
/**
* Parses byte array value from string (converts characters in string into byte
* array using specified charset encoder)
*
* @param seq
* @param charset charset to be used for encoding String into bytes
* @since 11.12.2006
*/
public void fromString(CharSequence seq, String charset) {
if (seq == null || Compare.equals(seq, metadata.getNullValue())) {
setNull(true);
return;
}
try {
this.value = seq.toString().getBytes(charset);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.toString() + " when calling fromString() on field \""
+ this.metadata.getName() + "\" (" + DataFieldMetadata.type2Str(getType()) + ") ", ex);
}
setNull(false);
}
@Override
public void fromByteBuffer(CloverBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException {
prepareBuf(dataBuffer);
dataBuffer.get(value);
setNull(Arrays.equals(value, metadata.getNullValue().getBytes(decoder.charset())));
}
@Override
public void toByteBuffer(CloverBuffer dataBuffer, CharsetEncoder encoder) throws CharacterCodingException {
try {
if (!isNull()) {
dataBuffer.put(getByteArray());
} else {
dataBuffer.put(encoder.encode(CharBuffer.wrap(metadata.getNullValue())));
}
} catch (BufferOverflowException e) {
throw new RuntimeException("The size of data buffer is only " + dataBuffer.limit() + ". Set appropriate parameter in defaultProperties file.", e);
}
}
/**
* Performs serialization of the internal value into ByteBuffer (used when
* moving data records between components).
*
*@param buffer Description of Parameter
*@since October 29, 2002
*/
@Override
public void serialize(CloverBuffer buffer) {
try {
if(isNull) {
// encode nulls as zero
ByteBufferUtils.encodeLength(buffer, 0);
} else {
// increment length of non-null values by one
ByteBufferUtils.encodeLength(buffer, value.length + 1);
buffer.put(value);
}
} catch (BufferOverflowException e) {
throw new RuntimeException("The size of data buffer is only " + buffer.maximumCapacity() + ". Set appropriate parameter in defaultProperties file.", e);
}
}
/**
* Performs deserialization of data
*
*@param buffer Description of Parameter
*@since October 29, 2002
*/
@Override
public void deserialize(CloverBuffer buffer) {
// encoded length is incremented by one, decrement it back to normal
final int length = ByteBufferUtils.decodeLength(buffer) - 1;
if (length < 0) {
setNull(true);
} else {
if (value == null || length != value.length) {
value = new byte[length];
}
buffer.get(value);
setNull(false);
}
}
@Override
public boolean equals(Object obj) {
if (isNull || obj==null) return false;
if (obj instanceof ByteDataField){
return Arrays.equals(this.value, ((ByteDataField) obj).value);
}else if (obj instanceof byte[]){
return Arrays.equals(this.value, (byte[])obj);
}else {
return false;
}
}
/**
* Compares this object with the specified object for order.
*
*@param obj Description of the Parameter
*@return Description of the Return Value
*/
@Override
public int compareTo(Object obj) {
byte[] byteObj;
if (isNull) return -1;
if (obj == null) return 1;
if (obj instanceof ByteDataField){
if (!((ByteDataField) obj).isNull()) {
byteObj = ((ByteDataField) obj).value;
}else {
return 1;
}
}else if (obj instanceof byte[]){
byteObj= (byte[])obj;
}else {
throw new IllegalArgumentException("Can't compare ByteDataField and "+obj.getClass().getName());
}
int compLength = value.length <= byteObj.length ? value.length : byteObj.length;
for (int i = 0; i < compLength; i++) {
if (value[i] > byteObj[i]) {
return 1;
} else if (value[i] < byteObj[i]) {
return -1;
}
}
// arrays seem to be the same (so far), decide according to the length
if (value.length == byteObj.length) {
return 0;
} else if (value.length > byteObj.length) {
return 1;
} else {
return -1;
}
}
@Override
public int hashCode(){
return Arrays.hashCode(this.value);
}
/**
* Returns how many bytes will be occupied when this field with current
* value is serialized into ByteBuffer
*
* @return The size value
* @see org.jetel.data.DataField
*/
@Override
public int getSizeSerialized() {
if(isNull) {
return ByteBufferUtils.lengthEncoded(0);
} else {
final int length = value.length;
return length + ByteBufferUtils.lengthEncoded(length);
}
}
} |
package com.yammer.dropwizard.cli;
import com.google.common.collect.Maps;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.util.JarLocation;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.action.VersionArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import java.util.SortedMap;
/**
* The command-line runner for Dropwizard services.
*/
public class Cli {
private static final String COMMAND_NAME_ATTR = "command";
private static final String[] HELP = { "-h" };
private final SortedMap<String, Command> commands;
private final Bootstrap<?> bootstrap;
private final ArgumentParser parser;
/**
* Create a new CLI interface for a service and its bootstrapped environment.
*
* @param serviceClass the service class
* @param bootstrap the bootstrap for the service
*/
public Cli(Class<?> serviceClass, Bootstrap<?> bootstrap) {
this.commands = Maps.newTreeMap();
this.parser = buildParser(serviceClass);
this.bootstrap = bootstrap;
for (Command command : bootstrap.getCommands()) {
addCommand(command);
}
}
/**
* Runs the command line interface given some arguments.
*
* @param arguments the command line arguments
* @throws Exception if something goes wrong
*/
public void run(String[] arguments) throws Exception {
try {
// assume -h if no arguments are given
final String[] args = (arguments.length == 0) ? HELP : arguments;
final Namespace namespace = parser.parseArgs(args);
final Command command = commands.get(namespace.getString(COMMAND_NAME_ATTR));
command.run(bootstrap, namespace);
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
}
}
private ArgumentParser buildParser(Class<?> serviceClass) {
final String usage = "java -jar " + new JarLocation(serviceClass);
final ArgumentParser p = ArgumentParsers.newArgumentParser(usage)
.defaultHelp(true);
String version = serviceClass.getPackage().getImplementationVersion();
if (version == null) {
version = "No service version detected. Add a Implementation-Version " +
"entry to your JAR's manifest to enable this.";
}
p.version(version);
p.addArgument("-v", "--version")
.action(new VersionArgumentAction())
.help("show the service version and exit");
return p;
}
private void addCommand(Command command) {
commands.put(command.getName(), command);
parser.addSubparsers().help("Available commands");
final Subparser subparser = parser.addSubparsers().addParser(command.getName());
command.configure(subparser);
subparser.description(command.getDescription())
.setDefault(COMMAND_NAME_ATTR, command.getName())
.defaultHelp(true);
}
} |
package com.coinbase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.coinbase.auth.AccessToken;
import com.coinbase.v1.entity.Account;
import com.coinbase.v1.entity.AccountChangesResponse;
import com.coinbase.v1.entity.AccountResponse;
import com.coinbase.v1.entity.AccountsResponse;
import com.coinbase.v1.entity.Address;
import com.coinbase.v1.entity.AddressResponse;
import com.coinbase.v1.entity.AddressesResponse;
import com.coinbase.v1.entity.Application;
import com.coinbase.v1.entity.ApplicationResponse;
import com.coinbase.v1.entity.ApplicationsResponse;
import com.coinbase.v1.entity.Button;
import com.coinbase.v1.entity.ButtonResponse;
import com.coinbase.v1.entity.ContactsResponse;
import com.coinbase.v1.entity.HistoricalPrice;
import com.coinbase.v1.entity.OAuthCodeRequest;
import com.coinbase.v1.entity.OAuthCodeResponse;
import com.coinbase.v1.entity.OAuthTokensRequest;
import com.coinbase.v1.entity.OAuthTokensResponse;
import com.coinbase.v1.entity.Order;
import com.coinbase.v1.entity.OrderResponse;
import com.coinbase.v1.entity.OrdersResponse;
import com.coinbase.v1.entity.PaymentMethodResponse;
import com.coinbase.v1.entity.PaymentMethodsResponse;
import com.coinbase.v1.entity.Quote;
import com.coinbase.v1.entity.RecurringPayment;
import com.coinbase.v1.entity.RecurringPaymentResponse;
import com.coinbase.v1.entity.RecurringPaymentsResponse;
import com.coinbase.v1.entity.Report;
import com.coinbase.v1.entity.ReportResponse;
import com.coinbase.v1.entity.ReportsResponse;
import com.coinbase.v1.entity.Request;
import com.coinbase.v1.entity.Response;
import com.coinbase.v1.entity.ResponseV1;
import com.coinbase.v1.entity.ResponseV2;
import com.coinbase.v1.entity.RevokeTokenRequest;
import com.coinbase.v1.entity.Token;
import com.coinbase.v1.entity.TokenResponse;
import com.coinbase.v1.entity.Transaction;
import com.coinbase.v1.entity.TransactionResponse;
import com.coinbase.v1.entity.TransactionsResponse;
import com.coinbase.v1.entity.Transfer;
import com.coinbase.v1.entity.TransferResponse;
import com.coinbase.v1.entity.TransfersResponse;
import com.coinbase.v1.entity.User;
import com.coinbase.v1.entity.UserResponse;
import com.coinbase.v1.entity.UsersResponse;
import com.coinbase.v1.exception.CoinbaseException;
import com.coinbase.v1.exception.CredentialsIncorrectException;
import com.coinbase.v1.exception.TwoFactorIncorrectException;
import com.coinbase.v1.exception.TwoFactorRequiredException;
import com.coinbase.v1.exception.UnauthorizedDeviceException;
import com.coinbase.v1.exception.UnauthorizedException;
import com.coinbase.v1.exception.UnspecifiedAccount;
import com.coinbase.v2.models.account.Accounts;
import com.coinbase.v2.models.paymentMethods.PaymentMethod;
import com.coinbase.v2.models.paymentMethods.PaymentMethods;
import com.coinbase.v2.models.price.Price;
import com.coinbase.v2.models.transactions.Transactions;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.joda.money.CurrencyUnit;
import org.joda.money.IllegalCurrencyException;
import org.joda.money.Money;
import org.joda.time.DateTime;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import au.com.bytecode.opencsv.CSVReader;
import okio.Buffer;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class Coinbase {
protected static final ObjectMapper objectMapper = ObjectMapperProvider.createDefaultMapper();
protected URL _baseApiUrl;
protected URL _baseOAuthUrl;
protected URL _baseV2ApiUrl;
protected String _accountId;
protected String _apiKey;
protected String _apiSecret;
protected String _accessToken;
protected SSLContext _sslContext;
protected SSLSocketFactory _socketFactory;
protected CallbackVerifier _callbackVerifier;
protected OkHttpClient _client;
protected static Coinbase _instance = null;
protected Context _context;
public Coinbase() {
try {
_baseApiUrl = new URL("https://coinbase.com/api/v1/");
_baseOAuthUrl = new URL("https:
_baseV2ApiUrl = new URL(ApiConstants.BASE_URL_PRODUCTION + "/" + ApiConstants.SERVER_VERSION + "/");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
_sslContext = CoinbaseSSL.getSSLContext();
_socketFactory = _sslContext.getSocketFactory();
_callbackVerifier = new CallbackVerifierImpl();
if (_client == null) {
_client = generateClient(_sslContext);
}
}
protected static OkHttpClient generateClient(SSLContext sslContext) {
OkHttpClient client = new OkHttpClient();
if (sslContext != null)
client.setSslSocketFactory(sslContext.getSocketFactory());
// Disable SPDY, causes issues on some Android versions
client.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setConnectTimeout(30, TimeUnit.SECONDS);
return client;
}
public static void setBaseUrl(String url, SSLContext sslContext) {
try {
getInstance()._baseApiUrl = new URL(url);
getInstance()._baseV2ApiUrl = new URL(url);
getInstance()._client = generateClient(sslContext);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void init(Context context, String apiKey, String apiSecret) {
getInstance()._apiKey = apiKey;
getInstance()._apiSecret = apiSecret;
getInstance()._context = context;
}
public static void init(Context context, String accessToken) {
getInstance()._accessToken = accessToken;
getInstance()._context = context;
}
/**
* Retrieve the coinbase singleton object.
*
* @return Coinbase object
*/
public static Coinbase getInstance() {
if (_instance == null) {
_instance = new Coinbase();
}
return _instance;
}
Coinbase(CoinbaseBuilder builder) {
_baseApiUrl = builder.base_api_url;
_baseOAuthUrl = builder.base_oauth_url;
_apiKey = builder.api_key;
_apiSecret = builder.api_secret;
_accessToken = builder.access_token;
_accountId = builder.acct_id;
_sslContext = builder.ssl_context;
_callbackVerifier = builder.callback_verifier;
try {
if (_baseApiUrl == null) {
_baseApiUrl = new URL("https://coinbase.com/api/v1/");
}
if (_baseOAuthUrl == null) {
_baseOAuthUrl = new URL("https:
}
if (_baseV2ApiUrl == null) {
_baseV2ApiUrl = new URL("https://api.coinbase.com/v2/");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
// Register BTC as a currency since Android won't let joda read from classpath resources
try {
CurrencyUnit.registerCurrency("BTC", -1, 8, new ArrayList<String>());
} catch (IllegalArgumentException ex) {
}
if (_sslContext != null) {
_socketFactory = _sslContext.getSocketFactory();
} else {
_sslContext = CoinbaseSSL.getSSLContext();
_socketFactory = _sslContext.getSocketFactory();
}
if (_callbackVerifier == null) {
_callbackVerifier = new CallbackVerifierImpl();
}
}
public User getUser() throws IOException, CoinbaseException {
URL usersUrl;
try {
usersUrl = new URL(_baseApiUrl, "users");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(usersUrl, UsersResponse.class).getUsers().get(0).getUser();
}
public AccountsResponse getAccounts() throws IOException, CoinbaseException {
return getAccounts(1, 25, false);
}
public AccountsResponse getAccounts(int page) throws IOException, CoinbaseException {
return getAccounts(page, 25, false);
}
public AccountsResponse getAccounts(int page, int limit) throws IOException, CoinbaseException {
return getAccounts(page, limit, false);
}
public AccountsResponse getAccounts(int page, int limit, boolean includeInactive) throws IOException, CoinbaseException {
URL accountsUrl;
try {
accountsUrl = new URL(
_baseApiUrl,
"accounts?" +
"&page=" + page +
"&limit=" + limit +
"&all_accounts=" + (includeInactive ? "true" : "false")
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(accountsUrl, AccountsResponse.class);
}
public Money getBalance() throws IOException, CoinbaseException {
if (_accountId != null) {
return getBalance(_accountId);
} else {
throw new UnspecifiedAccount();
}
}
public Money getBalance(String accountId) throws IOException, CoinbaseException {
URL accountBalanceUrl;
try {
accountBalanceUrl = new URL(_baseApiUrl, "accounts/" + accountId + "/balance");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return deserialize(doHttp(accountBalanceUrl, "GET", null), Money.class);
}
public void setPrimaryAccount(String accountId) throws CoinbaseException, IOException {
URL setPrimaryUrl;
try {
setPrimaryUrl = new URL(_baseApiUrl, "accounts/" + accountId + "/primary");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
post(setPrimaryUrl, new Request(), Response.class);
}
public void deleteAccount(String accountId) throws CoinbaseException, IOException {
URL accountUrl;
try {
accountUrl = new URL(_baseApiUrl, "accounts/" + accountId);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
delete(accountUrl, Response.class);
}
public void setPrimaryAccount() throws CoinbaseException, IOException {
if (_accountId != null) {
setPrimaryAccount(_accountId);
} else {
throw new UnspecifiedAccount();
}
}
public void deleteAccount() throws CoinbaseException, IOException {
if (_accountId != null) {
deleteAccount(_accountId);
} else {
throw new UnspecifiedAccount();
}
}
public void updateAccount(Account account) throws CoinbaseException, IOException, UnspecifiedAccount {
if (_accountId != null) {
updateAccount(_accountId, account);
} else {
throw new UnspecifiedAccount();
}
}
public Account createAccount(Account account) throws CoinbaseException, IOException {
URL accountsUrl;
try {
accountsUrl = new URL(_baseApiUrl, "accounts");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setAccount(account);
return post(accountsUrl, request, AccountResponse.class).getAccount();
}
public void updateAccount(String accountId, Account account) throws CoinbaseException, IOException {
URL accountUrl;
try {
accountUrl = new URL(_baseApiUrl, "accounts/" + accountId);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
Request request = new Request();
request.setAccount(account);
put(accountUrl, request, Response.class);
}
public Money getSpotPrice(CurrencyUnit currency) throws IOException, CoinbaseException {
URL spotPriceUrl;
try {
spotPriceUrl = new URL(_baseApiUrl, "prices/spot_rate?currency=" + URLEncoder.encode(currency.getCurrencyCode(), "UTF-8"));
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return deserialize(doHttp(spotPriceUrl, "GET", null), Money.class);
}
public Quote getBuyQuote(Money amount) throws IOException, CoinbaseException {
return getBuyQuote(amount, null);
}
public Quote getBuyQuote(Money amount, String paymentMethodId) throws IOException, CoinbaseException {
String qtyParam;
if (amount.getCurrencyUnit().getCode().equals("BTC")) {
qtyParam = "qty";
} else {
qtyParam = "native_qty";
}
URL buyPriceUrl;
try {
buyPriceUrl = new URL(
_baseApiUrl,
"prices/buy?" + qtyParam + "=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") +
(_accountId != null ? "&account_id=" + _accountId : "") +
(paymentMethodId != null ? "&payment_method_id=" + paymentMethodId : "")
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class);
}
public Quote getSellQuote(Money amount) throws IOException, CoinbaseException {
return getSellQuote(amount, null);
}
public Quote getSellQuote(Money amount, String paymentMethodId) throws IOException, CoinbaseException {
String qtyParam;
if (amount.getCurrencyUnit().getCode().equals("BTC")) {
qtyParam = "qty";
} else {
qtyParam = "native_qty";
}
URL sellPriceUrl;
try {
sellPriceUrl = new URL(
_baseApiUrl,
"prices/sell?" + qtyParam + "=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") +
(_accountId != null ? "&account_id=" + _accountId : "") +
(paymentMethodId != null ? "&payment_method_id=" + paymentMethodId : "")
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return deserialize(doHttp(sellPriceUrl, "GET", null), Quote.class);
}
public TransactionsResponse getTransactions(int page) throws IOException, CoinbaseException {
URL transactionsUrl;
try {
transactionsUrl = new URL(
_baseApiUrl,
"transactions?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(transactionsUrl, TransactionsResponse.class);
}
public TransactionsResponse getTransactions() throws IOException, CoinbaseException {
return getTransactions(1);
}
public Transaction getTransaction(String id) throws IOException, CoinbaseException {
URL transactionUrl;
try {
transactionUrl = new URL(_baseApiUrl, "transactions/" + id);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid transaction id");
}
return get(transactionUrl, TransactionResponse.class).getTransaction();
}
public Transaction requestMoney(Transaction transaction) throws CoinbaseException, IOException {
URL requestMoneyUrl;
try {
requestMoneyUrl = new URL(_baseApiUrl, "transactions/request_money");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
if (transaction.getAmount() == null) {
throw new CoinbaseException("Amount is a required field");
}
Request request = newAccountSpecificRequest();
request.setTransaction(transaction);
return post(requestMoneyUrl, request, TransactionResponse.class).getTransaction();
}
public void resendRequest(String id) throws CoinbaseException, IOException {
URL resendRequestUrl;
try {
resendRequestUrl = new URL(_baseApiUrl, "transactions/" + id + "/resend_request");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid transaction id");
}
put(resendRequestUrl, newAccountSpecificRequest(), Response.class);
}
public void deleteRequest(String id) throws CoinbaseException, IOException {
URL cancelRequestUrl;
try {
cancelRequestUrl = new URL(_baseApiUrl, "transactions/" + id + "/cancel_request");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid transaction id");
}
delete(cancelRequestUrl, Response.class);
}
public Transaction completeRequest(String id) throws CoinbaseException, IOException {
URL completeRequestUrl;
try {
completeRequestUrl = new URL(_baseApiUrl, "transactions/" + id + "/complete_request");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid transaction id");
}
return put(completeRequestUrl, newAccountSpecificRequest(), TransactionResponse.class).getTransaction();
}
public Transaction sendMoney(Transaction transaction) throws CoinbaseException, IOException {
URL sendMoneyUrl;
try {
sendMoneyUrl = new URL(_baseApiUrl, "transactions/send_money");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
if (transaction.getAmount() == null) {
throw new CoinbaseException("Amount is a required field");
}
Request request = newAccountSpecificRequest();
request.setTransaction(transaction);
return post(sendMoneyUrl, request, TransactionResponse.class).getTransaction();
}
public TransfersResponse getTransfers(int page) throws IOException, CoinbaseException {
URL transfersUrl;
try {
transfersUrl = new URL(
_baseApiUrl,
"transfers?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(transfersUrl, TransfersResponse.class);
}
public TransfersResponse getTransfers() throws IOException, CoinbaseException {
return getTransfers(1);
}
public Transaction transferMoneyBetweenAccounts(String amount, String toAccountId) throws CoinbaseException, IOException {
URL transferMoneyURL;
try {
transferMoneyURL = new URL(_baseApiUrl, "transactions/transfer_money");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Transaction transaction = new Transaction();
transaction.setTo(toAccountId);
transaction.setTransferBitcoinAmountString(amount);
Request request = newAccountSpecificRequest();
request.setTransaction(transaction);
return post(transferMoneyURL, request, TransactionResponse.class).getTransaction();
}
public Transfer sell(Money amount) throws CoinbaseException, IOException {
return sell(amount, null);
}
public Transfer sell(Money amount, String paymentMethodId) throws CoinbaseException, IOException {
return sell(amount, paymentMethodId, null);
}
public Transfer sell(Money amount, String paymentMethodId, Boolean commit) throws CoinbaseException, IOException {
URL sellsUrl;
try {
sellsUrl = new URL(_baseApiUrl, "sells");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setQty(amount.getAmount().doubleValue());
request.setPaymentMethodId(paymentMethodId);
request.setCurrency(amount.getCurrencyUnit().getCurrencyCode());
request.setCommit(commit);
return post(sellsUrl, request, TransferResponse.class).getTransfer();
}
public Transfer buy(Money amount) throws CoinbaseException, IOException {
return buy(amount, null);
}
public Transfer buy(Money amount, String paymentMethodId) throws CoinbaseException, IOException {
return buy(amount, paymentMethodId, null);
}
public Transfer buy(Money amount, String paymentMethodId, Boolean commit) throws CoinbaseException, IOException {
URL buysUrl;
try {
buysUrl = new URL(_baseApiUrl, "buys");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setQty(amount.getAmount().doubleValue());
request.setPaymentMethodId(paymentMethodId);
request.setCurrency(amount.getCurrencyUnit().getCurrencyCode());
request.setCommit(commit);
return post(buysUrl, request, TransferResponse.class).getTransfer();
}
public Transfer commitTransfer(String accountId, String transactionId) throws CoinbaseException, IOException {
URL commitUrl;
try {
commitUrl = new URL(_baseApiUrl, "transfers/" + transactionId + "/commit");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid transaction id");
}
Request request = new Request();
request.setAccountId(accountId);
return post(commitUrl, request, TransferResponse.class).getTransfer();
}
public Order getOrder(String idOrCustom) throws IOException, CoinbaseException {
URL orderUrl;
try {
orderUrl = new URL(_baseApiUrl, "orders/" + idOrCustom);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid order id/custom");
}
return get(orderUrl, OrderResponse.class).getOrder();
}
public OrdersResponse getOrders(int page) throws IOException, CoinbaseException {
URL ordersUrl;
try {
ordersUrl = new URL(
_baseApiUrl,
"orders?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(ordersUrl, OrdersResponse.class);
}
public OrdersResponse getOrders() throws IOException, CoinbaseException {
return getOrders(1);
}
public AddressesResponse getAddresses(int page) throws IOException, CoinbaseException {
URL addressesUrl;
try {
addressesUrl = new URL(
_baseApiUrl,
"addresses?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(addressesUrl, AddressesResponse.class);
}
public AddressesResponse getAddresses() throws IOException, CoinbaseException {
return getAddresses(1);
}
public ContactsResponse getContacts(int page) throws IOException, CoinbaseException {
URL contactsUrl;
try {
contactsUrl = new URL(
_baseApiUrl,
"contacts?page=" + page
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(contactsUrl, ContactsResponse.class);
}
public ContactsResponse getContacts() throws IOException, CoinbaseException {
return getContacts(1);
}
public ContactsResponse getContacts(String query, int page) throws IOException, CoinbaseException {
URL contactsUrl;
try {
contactsUrl = new URL(
_baseApiUrl,
"contacts?page=" + page +
"&query=" + URLEncoder.encode(query, "UTF-8")
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(contactsUrl, ContactsResponse.class);
}
public ContactsResponse getContacts(String query) throws IOException, CoinbaseException {
return getContacts(query, 1);
}
public Map<String, BigDecimal> getExchangeRates() throws IOException, CoinbaseException {
URL ratesUrl;
try {
ratesUrl = new URL(_baseApiUrl, "currencies/exchange_rates");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return deserialize(doHttp(ratesUrl, "GET", null), new TypeReference<HashMap<String, BigDecimal>>() {
});
}
public List<CurrencyUnit> getSupportedCurrencies() throws IOException, CoinbaseException {
URL currenciesUrl;
try {
currenciesUrl = new URL(_baseApiUrl, "currencies");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
List<List<String>> rawResponse =
deserialize(doHttp(currenciesUrl, "GET", null), new TypeReference<List<List<String>>>() {
});
List<CurrencyUnit> result = new ArrayList<CurrencyUnit>();
for (List<String> currency : rawResponse) {
try {
result.add(CurrencyUnit.getInstance(currency.get(1)));
} catch (IllegalCurrencyException ex) {
}
}
return result;
}
public List<HistoricalPrice> getHistoricalPrices(int page) throws CoinbaseException, IOException {
URL historicalPricesUrl;
try {
historicalPricesUrl = new URL(
_baseApiUrl,
"prices/historical?page=" + page
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
String responseBody = doHttp(historicalPricesUrl, "GET", null);
CSVReader reader = new CSVReader(new StringReader(responseBody));
ArrayList<HistoricalPrice> result = new ArrayList<HistoricalPrice>();
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
HistoricalPrice hp = new HistoricalPrice();
hp.setTime(DateTime.parse(nextLine[0]));
hp.setSpotPrice(Money.of(CurrencyUnit.USD, new BigDecimal(nextLine[1])));
result.add(hp);
}
} catch (IOException e) {
throw new CoinbaseException("Error parsing csv response");
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
return result;
}
public List<HistoricalPrice> getHistoricalPrices() throws CoinbaseException, IOException {
return getHistoricalPrices(1);
}
public Button createButton(Button button) throws CoinbaseException, IOException {
URL buttonsUrl;
try {
buttonsUrl = new URL(_baseApiUrl, "buttons");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setButton(button);
return post(buttonsUrl, request, ButtonResponse.class).getButton();
}
public Order createOrder(Button button) throws CoinbaseException, IOException {
URL ordersUrl;
try {
ordersUrl = new URL(_baseApiUrl, "orders");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setButton(button);
return post(ordersUrl, request, OrderResponse.class).getOrder();
}
public Order createOrderForButton(String buttonCode) throws CoinbaseException, IOException {
URL createOrderForButtonUrl;
try {
createOrderForButtonUrl = new URL(_baseApiUrl, "buttons/" + buttonCode + "/create_order");
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid button code");
}
return post(createOrderForButtonUrl, new Request(), OrderResponse.class).getOrder();
}
public PaymentMethodsResponse getPaymentMethods() throws IOException, CoinbaseException {
URL paymentMethodsUrl;
try {
paymentMethodsUrl = new URL(_baseV2ApiUrl, "payment-methods");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
HashMap<String, String> headers = getV2VersionHeaders();
return get(paymentMethodsUrl, headers, PaymentMethodsResponse.class);
}
public PaymentMethodResponse getPaymentMethod(String id) throws CoinbaseException, IOException {
URL paymentMethodURL;
try {
paymentMethodURL = new URL(_baseV2ApiUrl, "payment-methods/" + id);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
HashMap<String, String> headers = getV2VersionHeaders();
return get(paymentMethodURL, headers, PaymentMethodResponse.class);
}
public void deletePaymentMethod(String id) throws CoinbaseException, IOException {
URL deleteURL;
try {
deleteURL = new URL(_baseV2ApiUrl, "payment-methods/" + id);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
HashMap<String, String> headers = getV2VersionHeaders();
doHttp(deleteURL, "DELETE", null, headers);
}
public RecurringPaymentsResponse getSubscribers(int page) throws IOException, CoinbaseException {
URL subscribersUrl;
try {
subscribersUrl = new URL(
_baseApiUrl,
"subscribers?page=" + page
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(subscribersUrl, RecurringPaymentsResponse.class);
}
public RecurringPaymentsResponse getSubscribers() throws IOException, CoinbaseException {
return getSubscribers(1);
}
public RecurringPaymentsResponse getRecurringPayments(int page) throws IOException, CoinbaseException {
URL recurringPaymentsUrl;
try {
recurringPaymentsUrl = new URL(
_baseApiUrl,
"recurring_payments?page=" + page
);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(recurringPaymentsUrl, RecurringPaymentsResponse.class);
}
public RecurringPaymentsResponse getRecurringPayments() throws IOException, CoinbaseException {
return getRecurringPayments(1);
}
public RecurringPayment getRecurringPayment(String id) throws CoinbaseException, IOException {
URL recurringPaymentUrl;
try {
recurringPaymentUrl = new URL(_baseApiUrl, "recurring_payments/" + id);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid payment id");
}
return get(recurringPaymentUrl, RecurringPaymentResponse.class).getRecurringPayment();
}
public RecurringPayment getSubscriber(String id) throws CoinbaseException, IOException {
URL subscriberUrl;
try {
subscriberUrl = new URL(_baseApiUrl, "subscribers/" + id);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid subscriber id");
}
return get(subscriberUrl, RecurringPaymentResponse.class).getRecurringPayment();
}
public AddressResponse generateReceiveAddress(Address addressParams) throws CoinbaseException, IOException {
URL generateAddressUrl;
try {
generateAddressUrl = new URL(_baseApiUrl, "account/generate_receive_address");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setAddress(addressParams);
return post(generateAddressUrl, request, AddressResponse.class);
}
public AddressResponse generateReceiveAddress() throws CoinbaseException, IOException {
return generateReceiveAddress(null);
}
public User createUser(User userParams) throws CoinbaseException, IOException {
URL usersUrl;
try {
usersUrl = new URL(_baseApiUrl, "users");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setUser(userParams);
return post(usersUrl, request, UserResponse.class).getUser();
}
public User createUser(User userParams, String clientId, String scope) throws CoinbaseException, IOException {
URL usersUrl;
try {
usersUrl = new URL(_baseApiUrl, "users");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setUser(userParams);
request.setScopes(scope);
request.setClientId(clientId);
return post(usersUrl, request, UserResponse.class).getUser();
}
public UserResponse createUserWithOAuth(User userParams, String clientId, String scope) throws CoinbaseException, IOException {
URL usersUrl;
try {
usersUrl = new URL(_baseApiUrl, "users");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setUser(userParams);
request.setScopes(scope);
request.setClientId(clientId);
return post(usersUrl, request, UserResponse.class);
}
public User updateUser(String userId, User userParams) throws CoinbaseException, IOException {
URL userUrl;
try {
userUrl = new URL(_baseApiUrl, "users/" + userId);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid user id");
}
Request request = new Request();
request.setUser(userParams);
return put(userUrl, request, UserResponse.class).getUser();
}
public Token createToken() throws CoinbaseException, IOException {
URL tokensUrl;
try {
tokensUrl = new URL(_baseApiUrl, "tokens");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return post(tokensUrl, new Request(), TokenResponse.class).getToken();
}
public void redeemToken(String tokenId) throws CoinbaseException, IOException {
URL redeemTokenUrl;
try {
redeemTokenUrl = new URL(_baseApiUrl, "tokens/redeem");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setTokenId(tokenId);
post(redeemTokenUrl, request, Response.class);
}
public Application createApplication(Application applicationParams) throws CoinbaseException, IOException {
URL applicationsUrl;
try {
applicationsUrl = new URL(_baseApiUrl, "oauth/applications");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = new Request();
request.setApplication(applicationParams);
return post(applicationsUrl, request, ApplicationResponse.class).getApplication();
}
public ApplicationsResponse getApplications() throws IOException, CoinbaseException {
URL applicationsUrl;
try {
applicationsUrl = new URL(_baseApiUrl, "oauth/applications");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return get(applicationsUrl, ApplicationsResponse.class);
}
public Application getApplication(String id) throws IOException, CoinbaseException {
URL applicationUrl;
try {
applicationUrl = new URL(_baseApiUrl, "oauth/applications/" + id);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid application id");
}
return get(applicationUrl, ApplicationResponse.class).getApplication();
}
public Report createReport(Report reportParams) throws CoinbaseException, IOException {
URL reportsUrl;
try {
reportsUrl = new URL(_baseApiUrl, "reports");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
Request request = newAccountSpecificRequest();
request.setReport(reportParams);
return post(reportsUrl, request, ReportResponse.class).getReport();
}
public Report getReport(String reportId) throws IOException, CoinbaseException {
URL reportUrl;
try {
reportUrl = new URL(
_baseApiUrl,
"reports/" + reportId +
(_accountId != null ? "?account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid report id");
}
return get(reportUrl, ReportResponse.class).getReport();
}
public ReportsResponse getReports(int page) throws IOException, CoinbaseException {
URL reportsUrl;
try {
reportsUrl = new URL(
_baseApiUrl,
"reports?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(reportsUrl, ReportsResponse.class);
}
public ReportsResponse getReports() throws IOException, CoinbaseException {
return getReports(1);
}
public AccountChangesResponse getAccountChanges(int page) throws IOException, CoinbaseException {
URL accountChangesUrl;
try {
accountChangesUrl = new URL(
_baseApiUrl,
"account_changes?page=" + page +
(_accountId != null ? "&account_id=" + _accountId : "")
);
} catch (MalformedURLException ex) {
throw new CoinbaseException("Invalid account id");
}
return get(accountChangesUrl, AccountChangesResponse.class);
}
public AccountChangesResponse getAccountChanges() throws IOException, CoinbaseException {
return getAccountChanges(1);
}
public String getAuthCode(OAuthCodeRequest request)
throws CoinbaseException, IOException {
URL credentialsAuthorizationUrl;
try {
credentialsAuthorizationUrl = new URL(_baseOAuthUrl, "authorize/with_credentials");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
return post(credentialsAuthorizationUrl, request, OAuthCodeResponse.class).getCode();
}
public OAuthTokensResponse getTokens(String clientId, String clientSecret, String authCode, String redirectUri)
throws UnauthorizedDeviceException, CoinbaseException, IOException {
URL tokenUrl;
try {
tokenUrl = new URL(_baseOAuthUrl, "token");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
OAuthTokensRequest request = new OAuthTokensRequest();
request.setClientId(clientId);
request.setClientSecret(clientSecret);
request.setGrantType(OAuthTokensRequest.GrantType.AUTHORIZATION_CODE);
request.setCode(authCode);
request.setRedirectUri(redirectUri != null ? redirectUri : "2_legged");
return post(tokenUrl, request, OAuthTokensResponse.class);
}
public void revokeToken() throws CoinbaseException, IOException {
if (_accessToken == null) {
throw new CoinbaseException(
"This client must have been initialized with an access token in order to call revokeToken()"
);
}
URL revokeTokenUrl;
try {
revokeTokenUrl = new URL(_baseOAuthUrl, "revoke");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
RevokeTokenRequest request = new RevokeTokenRequest();
request.setToken(_accessToken);
post(revokeTokenUrl, request, Response.class);
_accessToken = null;
}
public OAuthTokensResponse refreshTokens(String clientId, String clientSecret, String refreshToken)
throws CoinbaseException, IOException {
URL tokenUrl;
try {
tokenUrl = new URL(_baseOAuthUrl, "token");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
OAuthTokensRequest request = new OAuthTokensRequest();
request.setClientId(clientId);
request.setClientSecret(clientSecret);
request.setGrantType(OAuthTokensRequest.GrantType.REFRESH_TOKEN);
request.setRefreshToken(refreshToken);
return post(tokenUrl, request, OAuthTokensResponse.class);
}
public void sendSMS(String clientId, String clientSecret, String email, String password) throws CoinbaseException, IOException {
URL smsUrl;
try {
smsUrl = new URL(_baseOAuthUrl, "authorize/with_credentials/sms_token");
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
OAuthCodeRequest request = new OAuthCodeRequest();
request.setClientId(clientId);
request.setClientSecret(clientSecret);
request.setUsername(email);
request.setPassword(password);
post(smsUrl, request, Response.class);
}
public Uri getAuthorizationUri(OAuthCodeRequest params) throws CoinbaseException {
URL authorizeURL;
Uri builtUri;
Uri.Builder uriBuilder;
try {
authorizeURL = new URL(_baseOAuthUrl, "authorize");
builtUri = Uri.parse(authorizeURL.toURI().toString());
uriBuilder = builtUri.buildUpon();
} catch (URISyntaxException ex) {
throw new AssertionError(ex);
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
uriBuilder.appendQueryParameter("response_type", "code");
if (params.getClientId() != null) {
uriBuilder.appendQueryParameter("client_id", params.getClientId());
} else {
throw new CoinbaseException("client_id is required");
}
if (params.getRedirectUri() != null) {
uriBuilder.appendQueryParameter("redirect_uri", params.getRedirectUri());
} else {
throw new CoinbaseException("redirect_uri is required");
}
if (params.getScope() != null) {
uriBuilder.appendQueryParameter("scope", params.getScope());
} else {
throw new CoinbaseException("scope is required");
}
if (params.getMeta() != null) {
OAuthCodeRequest.Meta meta = params.getMeta();
if (meta.getName() != null) {
uriBuilder.appendQueryParameter("meta[name]", meta.getName());
}
if (meta.getSendLimitAmount() != null) {
Money sendLimit = meta.getSendLimitAmount();
uriBuilder.appendQueryParameter("meta[send_limit_amount]", sendLimit.getAmount().toPlainString());
uriBuilder.appendQueryParameter("meta[send_limit_currency]", sendLimit.getCurrencyUnit().getCurrencyCode());
if (meta.getSendLimitPeriod() != null) {
uriBuilder.appendQueryParameter("meta[send_limit_period]", meta.getSendLimitPeriod().toString());
}
}
}
return uriBuilder.build();
}
public boolean verifyCallback(String body, String signature) {
return _callbackVerifier.verifyCallback(body, signature);
}
protected void doHmacAuthentication(URL url, String body, HttpsURLConnection conn) throws IOException {
String nonce = String.valueOf(System.currentTimeMillis());
String message = nonce + url.toString() + (body != null ? body : "");
Mac mac = null;
try {
mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(_apiSecret.getBytes(), "HmacSHA256"));
} catch (Throwable t) {
throw new IOException(t);
}
String signature = new String(Hex.encodeHex(mac.doFinal(message.getBytes())));
conn.setRequestProperty("ACCESS_KEY", _apiKey);
conn.setRequestProperty("ACCESS_SIGNATURE", signature);
conn.setRequestProperty("ACCESS_NONCE", nonce);
}
protected void doAccessTokenAuthentication(HttpsURLConnection conn) {
conn.setRequestProperty("Authorization", "Bearer " + _accessToken);
}
protected String doHttp(URL url, String method, Object requestBody) throws IOException, CoinbaseException {
return doHttp(url, method, requestBody, null);
}
protected String doHttp(URL url, String method, Object requestBody, HashMap<String, String> headers) throws IOException, CoinbaseException {
URLConnection urlConnection = url.openConnection();
if (!(urlConnection instanceof HttpsURLConnection)) {
throw new RuntimeException(
"Custom Base URL must return javax.net.ssl.HttpsURLConnection on openConnection.");
}
HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
conn.setSSLSocketFactory(_socketFactory);
conn.setRequestMethod(method);
String body = null;
if (requestBody != null) {
body = objectMapper.writeValueAsString(requestBody);
conn.setRequestProperty("Content-Type", "application/json");
}
if (_accessToken != null) {
doAccessTokenAuthentication(conn);
} else if (_apiKey != null && _apiSecret != null) {
doHmacAuthentication(url, body, conn);
}
if (headers != null) {
for (String key : headers.keySet()) {
conn.setRequestProperty(key, headers.get(key));
}
}
if (body != null) {
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
try {
outputStream.write(body.getBytes(Charset.forName("UTF-8")));
} finally {
outputStream.close();
}
}
InputStream is = null;
InputStream es = null;
try {
is = conn.getInputStream();
String str = IOUtils.toString(is, "UTF-8");
return str;
} catch (IOException e) {
if (HttpsURLConnection.HTTP_PAYMENT_REQUIRED == conn.getResponseCode()) {
throw new TwoFactorRequiredException();
}
es = conn.getErrorStream();
String errorBody = null;
if (es != null) {
errorBody = IOUtils.toString(es, "UTF-8");
if (errorBody != null && conn.getContentType().toLowerCase().contains("json")) {
Response coinbaseResponse;
try {
coinbaseResponse = deserialize(errorBody, ResponseV1.class);
} catch (Exception ex) {
try {
coinbaseResponse = deserialize(errorBody, ResponseV2.class);
} catch (Exception ex1) {
throw new CoinbaseException(errorBody);
}
}
handleErrors(coinbaseResponse);
}
}
if (HttpsURLConnection.HTTP_UNAUTHORIZED == conn.getResponseCode()) {
throw new UnauthorizedException(errorBody);
}
throw e;
} finally {
if (is != null) {
is.close();
}
if (es != null) {
es.close();
}
}
}
protected static <T> T deserialize(String json, Class<T> clazz) throws IOException {
return objectMapper.readValue(json, clazz);
}
protected static <T> T deserialize(String json, TypeReference<T> typeReference) throws IOException {
return objectMapper.readValue(json, typeReference);
}
protected <T extends Response> T get(URL url, Class<T> responseClass) throws IOException, CoinbaseException {
return get(url, null, responseClass);
}
protected <T extends Response> T get(URL url, HashMap<String, String> headers, Class<T> responseClass) throws IOException, CoinbaseException {
return handleErrors(deserialize(doHttp(url, "GET", null, headers), responseClass));
}
protected <T extends Response> T post(URL url, Object entity, Class<T> responseClass) throws CoinbaseException, IOException {
return handleErrors(deserialize(doHttp(url, "POST", entity), responseClass));
}
protected <T extends Response> T put(URL url, Object entity, Class<T> responseClass) throws CoinbaseException, IOException {
return handleErrors(deserialize(doHttp(url, "PUT", entity), responseClass));
}
protected <T extends Response> T delete(URL url, Class<T> responseClass) throws CoinbaseException, IOException {
return handleErrors(deserialize(doHttp(url, "DELETE", null), responseClass));
}
protected static <T extends Response> T handleErrors(T response) throws CoinbaseException {
String errors = response.getErrors();
if (errors != null) {
if (errors.contains("device_confirmation_required")) {
throw new UnauthorizedDeviceException();
} else if (errors.contains("2fa_required")) {
throw new TwoFactorRequiredException();
} else if (errors.contains("2fa_incorrect")) {
throw new TwoFactorIncorrectException();
} else if (errors.contains("incorrect_credentials")) {
throw new CredentialsIncorrectException();
}
throw new CoinbaseException(response.getErrors());
}
if (response.isSuccess() != null && !response.isSuccess()) {
throw new CoinbaseException("Unknown error");
}
return response;
}
protected Request newAccountSpecificRequest() {
Request request = new Request();
if (_accountId != null) {
request.setAccountId(_accountId);
}
return request;
}
protected HashMap<String, String> getV2VersionHeaders() {
HashMap<String, String> headers = new HashMap<>();
headers.put("CB-VERSION", "2015-03-20");
headers.put("CB-CLIENT", getPackageVersionName());
return headers;
}
protected Interceptor buildOAuthInterceptor() {
return new Interceptor() {
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request newRequest = chain
.request()
.newBuilder()
.addHeader("Authorization", "Bearer " + _accessToken)
.build();
return chain.proceed(newRequest);
}
};
}
protected Interceptor buildHmacAuthInterceptor() {
return new Interceptor() {
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request request = chain.request();
String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
String method = request.method().toUpperCase();
String path = request.url().getFile();
String body = "";
if (request.body() != null) {
final com.squareup.okhttp.Request requestCopy = request.newBuilder().build();
final Buffer buffer = new Buffer();
requestCopy.body().writeTo(buffer);
body = buffer.readUtf8();
}
String message = timestamp + method + path + body;
Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(_apiSecret.getBytes(), "HmacSHA256"));
} catch (Throwable t) {
throw new IOException(t);
}
String signature = new String(Hex.encodeHex(mac.doFinal(message.getBytes())));
com.squareup.okhttp.Request newRequest = request.newBuilder()
.addHeader("CB-ACCESS-KEY", _apiKey)
.addHeader("CB-ACCESS_SIGN", signature)
.addHeader("CB-ACCESS-TIMESTAMP", timestamp)
.build();
return chain.proceed(newRequest);
}
};
}
private String getPackageVersionName() {
String packageName = "";
String versionName = "";
if (_context != null) {
packageName = _context.getPackageName();
}
try {
versionName = _context.getPackageManager().getPackageInfo(_context.getPackageName(), 0).versionName;
} catch (Throwable t) {
}
return packageName + "/" + versionName;
}
protected Interceptor buildVersionInterceptor() {
return new Interceptor() {
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request newRequest = chain
.request()
.newBuilder()
.addHeader("CB-VERSION", com.coinbase.ApiConstants.VERSION)
.addHeader("CB-CLIENT", getPackageVersionName())
.build();
return chain.proceed(newRequest);
}
};
}
protected Interceptor languageInterceptor() {
return new Interceptor() {
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request newRequest = chain
.request()
.newBuilder()
.addHeader("Accept-Language", Locale.getDefault().getLanguage())
.build();
return chain.proceed(newRequest);
}
};
}
protected ApiInterface getOAuthApiService() {
_client.interceptors().clear();
if (_accessToken != null)
_client.interceptors().add(buildOAuthInterceptor());
_client.interceptors().add(buildVersionInterceptor());
String url = _baseOAuthUrl.toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.client(_client)
.addConverterFactory(GsonConverterFactory.create())
.build();
com.coinbase.ApiInterface service = retrofit.create(com.coinbase.ApiInterface.class);
return service;
}
protected com.coinbase.ApiInterface getApiService() {
_client.interceptors().clear();
if (_accessToken != null)
_client.interceptors().add(buildOAuthInterceptor());
_client.interceptors().add(buildVersionInterceptor());
String url = _baseV2ApiUrl.toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.client(_client)
.addConverterFactory(GsonConverterFactory.create())
.build();
com.coinbase.ApiInterface service = retrofit.create(com.coinbase.ApiInterface.class);
return service;
}
public Call refreshTokens(String clientId,
String clientSecret,
String refreshToken,
final Callback<AccessToken> callback) {
HashMap<String, Object> params = new HashMap<>();
params.put(ApiConstants.CLIENT_ID, clientId);
params.put(ApiConstants.CLIENT_SECRET, clientSecret);
params.put(ApiConstants.REFRESH_TOKEN, refreshToken);
params.put(ApiConstants.GRANT_TYPE, ApiConstants.REFRESH_TOKEN);
ApiInterface apiInterface = getOAuthApiService();
Call call = apiInterface.refreshTokens(params);
call.enqueue(new Callback<AccessToken>() {
@Override
public void onResponse(retrofit.Response<AccessToken> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
if (response != null && response.body() != null)
_accessToken = response.body().getAccessToken();
}
@Override
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call revokeToken(final Callback<Void> callback) {
if (_accessToken == null) {
Log.w("Coinbase Error", "This client must have been initialized with an access token in order to call revokeToken()");
return null;
}
HashMap<String, Object> params = new HashMap<>();
params.put(ApiConstants.TOKEN, _accessToken);
ApiInterface apiInterface = getOAuthApiService();
Call call = apiInterface.revokeToken(params);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(retrofit.Response<Void> response, Retrofit retrofit) {
if (response.isSuccess())
_accessToken = null;
if (callback != null)
callback.onResponse(response, retrofit);
}
@Override
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getUser(final Callback<com.coinbase.v2.models.user.User> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getUser();
call.enqueue(new Callback<com.coinbase.v2.models.user.User>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.user.User> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call updateUser(String name, String timeZone, String nativeCurrency, final Callback<com.coinbase.v2.models.user.User> callback) {
HashMap<String, Object> params = new HashMap<>();
if (name != null)
params.put(ApiConstants.NAME, name);
if (timeZone != null)
params.put(ApiConstants.TIME_ZONE, timeZone);
if (nativeCurrency != null)
params.put(ApiConstants.NATIVE_CURRENCY, nativeCurrency);
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.updateUser(params);
call.enqueue(new Callback<com.coinbase.v2.models.user.User>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.user.User> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getAccount(String accountId, final Callback<com.coinbase.v2.models.account.Account> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getAccount(accountId);
call.enqueue(new Callback<com.coinbase.v2.models.account.Account>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.account.Account> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getAccounts(HashMap<String, Object> options, final Callback<Accounts> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getAccounts(options);
call.enqueue(new Callback<Accounts>() {
public void onResponse(retrofit.Response<Accounts> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call createAccount(HashMap<String, Object> options, final Callback<com.coinbase.v2.models.account.Account> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.createAccount(options);
call.enqueue(new Callback<com.coinbase.v2.models.account.Account>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.account.Account> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call setAccountPrimary(String accountId, final Callback<Void> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.setAccountPrimary(accountId);
call.enqueue(new Callback() {
@Override
public void onResponse(retrofit.Response response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
@Override
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call updateAccount(String accountId, HashMap<String, Object> options, final Callback<com.coinbase.v2.models.account.Account> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.updateAccount(accountId, options);
call.enqueue(new Callback<com.coinbase.v2.models.account.Account>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.account.Account> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call deleteAccount(String accountId, final Callback<Void> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.deleteAccount(accountId);
call.enqueue(new Callback() {
@Override
public void onResponse(retrofit.Response response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
@Override
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getTransactions(String accountId,
HashMap<String, Object> options,
List<String> expandOptions,
final Callback<Transactions> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getTransactions(accountId, expandOptions, options);
call.enqueue(new Callback<Transactions>() {
public void onResponse(retrofit.Response<Transactions> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getTransaction(String accountId, String transactionId, final Callback<com.coinbase.v2.models.transactions.Transaction> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
List<String> expandOptions = Arrays.asList(com.coinbase.ApiConstants.FROM, com.coinbase.ApiConstants.TO, com.coinbase.ApiConstants.BUY, com.coinbase.ApiConstants.SELL);
Call call = apiInterface.getTransaction(accountId, transactionId, expandOptions);
call.enqueue(new Callback<com.coinbase.v2.models.transactions.Transaction>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transactions.Transaction> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call completeRequest(String accountId, String transactionId, final Callback<Void> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.completeRequest(accountId, transactionId);
call.enqueue(new Callback<Void>() {
public void onResponse(retrofit.Response<Void> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call resendRequest(String accountId, String transactionId, final Callback<Void> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.resendRequest(accountId, transactionId);
call.enqueue(new Callback<Void>() {
public void onResponse(retrofit.Response<Void> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call cancelRequest(String accountId, String transactionId, final Callback<Void> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.cancelRequest(accountId, transactionId);
call.enqueue(new Callback<Void>() {
public void onResponse(retrofit.Response<Void> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call sendMoney(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transactions.Transaction> callback) {
params.put(com.coinbase.ApiConstants.TYPE, com.coinbase.ApiConstants.SEND);
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.sendMoney(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transactions.Transaction>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transactions.Transaction> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call requestMoney(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transactions.Transaction> callback) {
params.put(com.coinbase.ApiConstants.TYPE, com.coinbase.ApiConstants.REQUEST);
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.requestMoney(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transactions.Transaction>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transactions.Transaction> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call transferMoney(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transactions.Transaction> callback) {
params.put(com.coinbase.ApiConstants.TYPE, ApiConstants.TRANSFER);
ApiInterface apiInterface = getApiService();
Call call = apiInterface.transferMoney(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transactions.Transaction>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transactions.Transaction> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call buyBitcoin(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.buyBitcoin(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call commitBuyBitcoin(String accountId, String buyId, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.commitBuyBitcoin(accountId, buyId);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call sellBitcoin(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.sellBitcoin(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call commitSellBitcoin(String accountId, String sellId, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.commitSellBitcoin(accountId, sellId);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getSellPrice(String baseCurrency, String fiatCurrency,
HashMap<String, Object> params, final Callback<Price> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getSellPrice(baseCurrency, fiatCurrency, params);
call.enqueue(new Callback<Price>() {
public void onResponse(retrofit.Response<Price> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getBuyPrice(String baseCurrency, String fiatCurrency,
HashMap<String, Object> params, final Callback<Price> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getBuyPrice(baseCurrency, fiatCurrency, params);
call.enqueue(new Callback<Price>() {
public void onResponse(retrofit.Response<Price> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getSpotPrice(String baseCurrency, String fiatCurrency,
HashMap<String, Object> params, final Callback<Price> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getSpotPrice(baseCurrency, fiatCurrency, params);
call.enqueue(new Callback<Price>() {
public void onResponse(retrofit.Response<Price> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call generateAddress(String accountId, final Callback<com.coinbase.v2.models.address.Address> callback) {
ApiInterface apiInterface = getApiService();
Call call = apiInterface.generateAddress(accountId);
call.enqueue(new Callback<com.coinbase.v2.models.address.Address>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.address.Address> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call depositFunds(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.depositFunds(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call commitDeposit(String accountId, String depositId, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.commitDeposit(accountId, depositId);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call withdrawFunds(String accountId, HashMap<String, Object> params, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.withdrawFunds(accountId, params);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call commitWithdraw(String accountId, String withdrawId, final Callback<com.coinbase.v2.models.transfers.Transfer> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.commitWithdraw(accountId, withdrawId);
call.enqueue(new Callback<com.coinbase.v2.models.transfers.Transfer>() {
public void onResponse(retrofit.Response<com.coinbase.v2.models.transfers.Transfer> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getPaymentMethod(String paymentMethodId, final Callback<PaymentMethod> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getPaymentMethod(paymentMethodId);
call.enqueue(new Callback<PaymentMethod>() {
public void onResponse(retrofit.Response<PaymentMethod> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
public Call getPaymentMethods(HashMap<String, Object> options, final Callback<PaymentMethods> callback) {
com.coinbase.ApiInterface apiInterface = getApiService();
Call call = apiInterface.getPaymentMethods(options);
call.enqueue(new Callback<PaymentMethods>() {
public void onResponse(retrofit.Response<PaymentMethods> response, Retrofit retrofit) {
if (callback != null)
callback.onResponse(response, retrofit);
}
public void onFailure(Throwable t) {
if (callback != null)
callback.onFailure(t);
}
});
return call;
}
} |
package dr.app.seqgen;
import dr.evolution.tree.Tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.datatype.Microsatellite;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.Patterns;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Taxa;
import dr.evomodel.sitemodel.SiteModel;
import dr.evomodel.sitemodel.GammaSiteModel;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.substmodel.MicrosatelliteModel;
import dr.math.MathUtils;
/**
* @author Chieh-Hsi Wu
*
* Simulates a pattern of microsatellites given a tree and microsatellite model
*
*/
public class MicrosatelliteSimulator extends SequenceSimulator{
private Taxa taxa;
private Microsatellite dataType;
public MicrosatelliteSimulator(
Microsatellite dataType,
Taxa taxa,
Tree tree,
MicrosatelliteModel msatModel,
BranchRateModel branchRateModel){
this(dataType, taxa, tree, new GammaSiteModel(msatModel), branchRateModel);
}
public MicrosatelliteSimulator(
Microsatellite dataType,
Taxa taxa,
Tree tree,
SiteModel siteModel,
BranchRateModel branchRateModel) {
super(tree, siteModel, branchRateModel, 1);
this.dataType = dataType;
this.taxa = taxa;
}
/**
* Convert integer representation of microsatellite length to string.
*/
Sequence intArray2Sequence(int [] seq, NodeRef node) {
String sSeq = ""+seq[0];
return new Sequence(m_tree.getNodeTaxon(node), sSeq);
} // intArray2Sequence
/**
* Convert an alignment to a pattern
*/
public Patterns simulateMsatPattern(){
Alignment align = simulate();
int[] pattern = new int[align.getTaxonCount()];
for(int i = 0; i < pattern.length; i++){
String taxonName = align.getSequence(i).getTaxon().getId();
int index = taxa.getTaxonIndex(taxonName);
pattern[index] = Integer.parseInt(align.getSequence(i).getSequenceString());
}
Patterns patterns = new Patterns(dataType,taxa);
patterns.addPattern(pattern);
for(int i = 0; i < pattern.length;i++){
System.out.print(pattern[i]+",");
}
System.out.println();
return patterns;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.