answer
stringlengths 17
10.2M
|
|---|
package ro.isdc.wro.extensions.processor.js;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.logging.Level;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.model.group.processor.Minimize;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.SupportedResourceType;
import ro.isdc.wro.model.resource.processor.ResourcePostProcessor;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.DefaultCodingConvention;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.Result;
@Minimize
@SupportedResourceType(ResourceType.JS)
public class GoogleClosureCompressorProcessor
implements ResourcePostProcessor, ResourcePreProcessor {
private static final Logger LOG = LoggerFactory.getLogger(GoogleClosureCompressorProcessor.class);
/**
* {@link CompilationLevel} to use for compression.
*/
private final CompilationLevel compilationLevel;
/**
* Uses google closure compiler with default compilation level: {@link CompilationLevel#SIMPLE_OPTIMIZATIONS}
*/
public GoogleClosureCompressorProcessor() {
compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
}
/**
* Uses google closure compiler with specified compilation level.
*
* @param compilationLevel not null {@link CompilationLevel} enum.
*/
public GoogleClosureCompressorProcessor(final CompilationLevel compilationLevel) {
if (compilationLevel == null) {
throw new IllegalArgumentException("compilation level cannot be null!");
}
this.compilationLevel = compilationLevel;
}
/**
* {@inheritDoc}
*/
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
process(reader, writer);
}
/**
* {@inheritDoc}
*/
public void process(final Reader reader, final Writer writer)
throws IOException {
final String content = IOUtils.toString(reader);
try {
Compiler.setLoggingLevel(Level.SEVERE);
final Compiler compiler = new Compiler();
final CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new DefaultCodingConvention());
//make it play nice with GAE
compiler.disableThreads();
// Advanced mode is used here, but additional options could be set, too.
compilationLevel.setOptionsForCompilationLevel(options);
compiler.initOptions(options);
final JSSourceFile extern = JSSourceFile.fromCode("externs.js", "");
final JSSourceFile input = JSSourceFile.fromInputStream("", new ByteArrayInputStream(content.getBytes()));
final Result result = compiler.compile(extern, input, options);
if (result.success) {
writer.write(compiler.toSource());
} else {
writer.write(content);
}
} finally {
LOG.debug("finally");
reader.close();
writer.close();
}
}
}
|
package org.elasticsearch.xpack.eql.qa.mixed_node;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.test.NotEqualMessageBuilder;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.ql.TestNode;
import org.elasticsearch.xpack.ql.TestNodes;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.Collections.unmodifiableList;
import static org.elasticsearch.xpack.ql.TestUtils.buildNodeAndVersions;
import static org.elasticsearch.xpack.ql.TestUtils.readResource;
/**
* Class testing the behavior of events and sequence queries in a mixed cluster scenario (during rolling upgrade).
* The test is against a three-node cluster where one node is upgraded, the other two are on the old version.
*
*/
public class EqlSearchIT extends ESRestTestCase {
private static final String index = "test_eql_mixed_versions";
private static int numShards;
private static int numReplicas = 1;
private static int numDocs;
private static TestNodes nodes;
private static List<TestNode> newNodes;
private static List<TestNode> bwcNodes;
@Before
public void createIndex() throws IOException {
nodes = buildNodeAndVersions(client());
numShards = nodes.size();
numDocs = randomIntBetween(numShards, 15);
newNodes = new ArrayList<>(nodes.getNewNodes());
bwcNodes = new ArrayList<>(nodes.getBWCNodes());
String mappings = readResource(EqlSearchIT.class.getResourceAsStream("/eql_mapping.json"));
createIndex(
index,
Settings.builder()
.put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), numShards)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numReplicas)
.build(),
mappings
);
}
@After
public void cleanUpIndex() throws IOException {
if (indexExists(index)) {
deleteIndex(index);
}
}
public void testEventsWithRequestToOldNodes() throws Exception {
assertEventsQueryOnNodes(bwcNodes);
}
public void testEventsWithRequestToUpgradedNodes() throws Exception {
assertEventsQueryOnNodes(newNodes);
}
public void testSequencesWithRequestToOldNodes() throws Exception {
assertSequncesQueryOnNodes(bwcNodes);
}
public void testSequencesWithRequestToUpgradedNodes() throws Exception {
assertSequncesQueryOnNodes(newNodes);
}
private void assertEventsQueryOnNodes(List<TestNode> nodesList) throws Exception {
final String event = randomEvent();
Map<String, Object> expectedResponse = prepareEventsTestData(event);
try (
RestClient client = buildClient(restClientSettings(),
nodesList.stream().map(TestNode::getPublishAddress).toArray(HttpHost[]::new))
) {
// filter only the relevant bits of the response
String filterPath = "filter_path=hits.events._source.@timestamp,hits.events._source.event_type,hits.events._source.sequence";
Request request = new Request("POST", index + "/_eql/search?" + filterPath);
request.setJsonEntity("{\"query\":\"" + event + " where true\",\"size\":15}");
assertBusy(() -> { assertResponse(expectedResponse, runEql(client, request)); });
}
}
private void assertSequncesQueryOnNodes(List<TestNode> nodesList) throws Exception {
Map<String, Object> expectedResponse = prepareSequencesTestData();
try (
RestClient client = buildClient(restClientSettings(),
nodesList.stream().map(TestNode::getPublishAddress).toArray(HttpHost[]::new))
) {
String filterPath = "filter_path=hits.sequences.join_keys,hits.sequences.events._id,hits.sequences.events._source";
String query = "sequence by `sequence` with maxspan=100ms [success where true] by correlation_success1, correlation_success2 "
+ "[failure where true] by correlation_failure1, correlation_failure2";
String filter = "{\"range\":{\"@timestamp\":{\"gte\":\"1970-05-01\"}}}";
Request request = new Request("POST", index + "/_eql/search?" + filterPath);
request.setJsonEntity("{\"query\":\"" + query + "\",\"filter\":" + filter + "}");
assertBusy(() -> { assertResponse(expectedResponse, runEql(client, request)); });
}
}
private String randomEvent() {
return randomFrom("success", "failure");
}
private Map<String, Object> prepareEventsTestData(String event) throws IOException {
List<Map<String, Object>> sourceEvents = new ArrayList<Map<String, Object>>();
Map<String, Object> expectedResponse = singletonMap("hits", singletonMap("events", sourceEvents));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < numDocs; i++) {
final String randomEvent = randomEvent();
builder.append("{\"index\":{\"_id\":" + i + "}}\n");
builder.append("{");
builder.append("\"@timestamp\":" + i + ",");
builder.append("\"event_type\":\"" + randomEvent + "\",");
builder.append("\"sequence\":" + i);
builder.append("}\n");
if (randomEvent.equals(event)) {
Map<String, Object> eventSource = new HashMap<>();
eventSource.put("@timestamp", i);
eventSource.put("event_type", randomEvent);
eventSource.put("sequence", i);
sourceEvents.add(singletonMap("_source", eventSource));
}
}
Request request = new Request("PUT", index + "/_bulk?refresh");
request.setJsonEntity(builder.toString());
assertOK(client().performRequest(request));
if (sourceEvents.isEmpty()) {
return emptyMap();
}
return expectedResponse;
}
/*
* Output to compare with looks like this:
* {
* "hits": {
* "sequences": [
* {
* "join_keys": [
* 44,
* "C",
* "D"
* ],
* "events": [
* {
* "_id": "14",
* "_source": {
* ...
* }
* }
* ]
* }
* }
* }
*
*/
private Map<String, Object> prepareSequencesTestData() throws IOException {
Map<String, Object> event14 = new HashMap<>();
Map<String, Object> event14Source = new HashMap<>();
event14.put("_id", "14");
event14.put("_source", event14Source);
event14Source.put("@timestamp", "12345678914");
event14Source.put("event_type", "success");
event14Source.put("sequence", 44);
event14Source.put("correlation_success1", "C");
event14Source.put("correlation_success2", "D");
Map<String, Object> event15 = new HashMap<>();
Map<String, Object> event15Source = new HashMap<>();
event15.put("_id", "15");
event15.put("_source", event15Source);
event15Source.put("@timestamp", "12345678999");
event15Source.put("event_type", "failure");
event15Source.put("sequence", 44);
event15Source.put("correlation_failure1", "C");
event15Source.put("correlation_failure2", "D");
Map<String, Object> sequence = new HashMap<>();
List<Map<String, Object>> events = unmodifiableList(asList(event14, event15));
List<Map<String, Object>> sequences = singletonList(sequence);
Map<String, Object> expectedResponse = singletonMap("hits", singletonMap("sequences", sequences));
sequence.put("join_keys", asList(44, "C", "D"));
sequence.put("events", events);
final String bulkEntries = readResource(EqlSearchIT.class.getResourceAsStream("/eql_data.json"));
Request request = new Request("POST", index + "/_bulk?refresh");
request.setJsonEntity(bulkEntries);
assertOK(client().performRequest(request));
return expectedResponse;
}
private void assertResponse(Map<String, Object> expected, Map<String, Object> actual) {
if (false == expected.equals(actual)) {
NotEqualMessageBuilder message = new NotEqualMessageBuilder();
message.compareMaps(actual, expected);
fail("Response does not match:\n" + message.toString());
}
}
private Map<String, Object> runEql(RestClient client, Request request) throws IOException {
Response response = client.performRequest(request);
try (InputStream content = response.getEntity().getContent()) {
return XContentHelper.convertToMap(JsonXContent.jsonXContent, content, false);
}
}
}
|
package fi.bitrite.android.ws.view;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import fi.bitrite.android.ws.model.Feedback;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
/**
* Custom table that creates rows dynamically.
*/
public class FeedbackTable extends TableLayout {
public FeedbackTable(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void addRows(List<Feedback> feedback) {
int i = 0;
for (Feedback f : feedback) {
int bgColor = (i++ % 2 == 0) ? 0 : 0xFF222222;
TableRow tr = getFeedbackRow(bgColor);
TextView meta = getFeedbackText(getMetaString(f));
meta.setTypeface(null, Typeface.ITALIC);
meta.setPadding(0, 5, 0, 0);
tr.addView(meta);
addView(tr);
tr = getFeedbackRow(bgColor);
TextView body = getFeedbackText(f.getBody());
body.setPadding(0, 0, 0, 5);
tr.addView(body);
addView(tr);
}
}
private String getMetaString(Feedback f) {
StringBuilder sb = new StringBuilder();
String name = f.getFullname();
if (name == null || name.length() == 0) {
name = "Unknown";
}
sb.append(name.trim());
sb.append(" (");
sb.append(f.getGuestOrHost());
sb.append(", ");
Date d = new Date(f.getHostingDate()*1000L);
String hostedOn = DateFormat.getDateInstance().format(d);
sb.append(hostedOn);
sb.append(")");
return sb.toString();
}
private TextView getFeedbackText(String text) {
TextView row = new TextView(getContext());
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT
));
row.setText(text);
return row;
}
private TableRow getFeedbackRow(int bgColor) {
TableRow tr = new TableRow(getContext());
tr.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT
));
tr.setBackgroundColor(bgColor);
return tr;
}
}
|
package io.swagger.codegen;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import io.swagger.codegen.cmd.ConfigHelp;
import io.swagger.codegen.cmd.Generate;
import io.swagger.codegen.cmd.Langs;
import io.swagger.codegen.cmd.Meta;
public class SwaggerCodegen {
public static void main(String[] args) {
@SuppressWarnings("unchecked")
Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("swagger-codegen-cli")
.withDescription("Swagger code generator CLI. More info on swagger.io")
.withDefaultCommand(Langs.class)
.withCommands(
Generate.class,
Meta.class,
Langs.class,
Help.class,
ConfigHelp.class
);
builder.build().parse(args).run();
}
}
|
package org.voltcore.logging;
import com.google_voltpatches.common.base.Throwables;
import org.voltcore.utils.CoreUtils;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
/**
* Class that implements the core functionality of a Log4j logger
* or a java.util.logging logger. The point is that it should work
* whether log4j is in the classpath or not. New VoltDB code should
* avoid log4j wherever possible.
*/
public class VoltLogger {
final CoreVoltLogger m_logger;
private static final String m_threadName = "Async Logger";
private static final ExecutorService m_es = CoreUtils.getSingleThreadExecutor(m_threadName);
private static final boolean m_disableAsync = Boolean.getBoolean("DISABLE_ASYNC_LOGGING");
static {
Runtime.getRuntime().addShutdownHook(new Thread("Async logger final sync") {
@Override
public void run() {
try {
m_es.submit(new Runnable() {
@Override
public void run() {}
}).get();
} catch (Exception e) {
Throwables.getRootCause(e).printStackTrace();
}
}
});
}
/**
* Abstraction of core functionality shared between Log4j and
* java.util.logging.
*/
static interface CoreVoltLogger {
public boolean isEnabledFor(Level level);
public void log(Level level, Object message, Throwable t);
public void l7dlog(Level level, String key, Object[] params, Throwable t);
public void addSimpleWriterAppender(StringWriter writer);
public void setLevel(Level level);
public long getLogLevels(VoltLogger loggers[]);
}
/*
* Submit all tasks asynchronously to the thread to preserve message order,
* but don't wait for the task to complete for info, debug, trace, and warn
*/
private void submit(final Level l, final Object message, final Throwable t, boolean wait) {
if (m_disableAsync) m_logger.log(l, message, t);
final Thread currentThread = Thread.currentThread();
final Runnable r = new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(currentThread.getName());
try {
m_logger.log(l, message, t);
} finally {
Thread.currentThread().setName(m_threadName);
}
}
};
if (wait) {
try {
m_es.submit(r).get();
} catch (Exception e) {
Throwables.propagate(e);
}
} else {
m_es.execute(r);
}
}
private void submitl7d(final Level level, final String key, final Object[] params, final Throwable t) {
if (m_disableAsync) m_logger.l7dlog(level, key, params, t);
final Thread currentThread = Thread.currentThread();
final Runnable r = new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(currentThread.getName());
try {
m_logger.l7dlog(level, key, params, t);
} finally {
Thread.currentThread().setName(m_threadName);
}
}
};
switch (level) {
case INFO:
case WARN:
case DEBUG:
case TRACE:
m_es.execute(r);
break;
case FATAL:
case ERROR:
try {
m_es.submit(r).get();
} catch (Exception e) {
Throwables.propagate(e);
}
break;
default:
throw new AssertionError("Unrecognized level " + level);
}
}
public void debug(Object message) {
submit(Level.DEBUG, message, null, false);
}
public void debug(Object message, Throwable t) {
submit(Level.DEBUG, message, t, false);
}
public boolean isDebugEnabled() {
return m_logger.isEnabledFor(Level.DEBUG);
}
public void error(Object message) {
submit(Level.ERROR, message, null, true);
}
public void error(Object message, Throwable t) {
submit(Level.ERROR, message, t, true);
}
public void fatal(Object message) {
submit(Level.FATAL, message, null, true);
}
public void fatal(Object message, Throwable t) {
submit(Level.FATAL, message, t, true);
}
public void info(Object message) {
submit(Level.INFO, message, null, false);
}
public void info(Object message, Throwable t) {
submit(Level.INFO, message, t, false);
}
public boolean isInfoEnabled() {
return m_logger.isEnabledFor(Level.INFO);
}
public void trace(Object message) {
submit(Level.TRACE, message, null, false);
}
public void trace(Object message, Throwable t) {
submit(Level.TRACE, message, t, false);
}
public boolean isTraceEnabled() {
return m_logger.isEnabledFor(Level.TRACE);
}
public void warn(Object message) {
submit(Level.WARN, message, null, false);
}
public void warn(Object message, Throwable t) {
submit(Level.WARN, message, t, false);
}
public void l7dlog(final Level level, final String key, final Throwable t) {
submitl7d(level, key, null, t);
}
public void l7dlog(final Level level, final String key, final Object[] params, final Throwable t) {
submitl7d(level, key, params, t);
}
public void addSimpleWriterAppender(StringWriter writer) {
m_logger.addSimpleWriterAppender(writer);
}
public void setLevel(Level level) {
m_logger.setLevel(level);
}
public long getLogLevels(VoltLogger loggers[]) {
return m_logger.getLogLevels(loggers);
}
/**
* Static method to change the Log4j config globally. This fails
* if you're not using Log4j for now.
* @param xmlConfig The text of a Log4j config file.
*/
public static void configure(String xmlConfig) {
try {
Class<?> loggerClz = Class.forName("org.voltcore.logging.VoltLog4jLogger");
assert(loggerClz != null);
Method configureMethod = loggerClz.getMethod("configure", String.class);
configureMethod.invoke(null, xmlConfig);
} catch (Exception e) {
return;
}
}
/**
* Try to load the Log4j logger without importing it. Eventually support
* graceful failback to java.util.logging.
* @param classname The id of the logger.
*/
public VoltLogger(String classname) {
CoreVoltLogger tempLogger = null;
// try to load the Log4j logger without importing it
// any exception thrown will just keep going
try {
Class<?> loggerClz = Class.forName("org.voltcore.logging.VoltLog4jLogger");
assert(loggerClz != null);
Constructor<?> constructor = loggerClz.getConstructor(String.class);
tempLogger = (CoreVoltLogger) constructor.newInstance(classname);
}
catch (Exception e) {}
catch (LinkageError e) {}
// if unable to load Log4j, try to use java.util.logging
if (tempLogger == null)
tempLogger = new VoltUtilLoggingLogger(classname);
// set the final variable for the core logger
m_logger = tempLogger;
// Don't let the constructor exit without
if (m_logger == null)
throw new RuntimeException("Unable to get VoltLogger instance.");
}
}
|
package org.voltdb.export;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.COWSortedMap;
import org.voltcore.utils.DBBPool;
import org.voltcore.utils.Pair;
import org.voltdb.CatalogContext;
import org.voltdb.VoltDB;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Connector;
import org.voltdb.catalog.ConnectorProperty;
import org.voltdb.catalog.Database;
import org.voltdb.utils.LogKeys;
import com.google_voltpatches.common.base.Preconditions;
import com.google_voltpatches.common.base.Throwables;
import org.voltdb.utils.VoltFile;
/**
* Bridges the connection to an OLAP system and the buffers passed
* between the OLAP connection and the execution engine. Each processor
* implements ExportDataProcessor interface. The processors are passed one
* or more ExportDataSources. The sources map, currently, 1:1 with Export
* enabled tables. The ExportDataSource has poll() and ack() methods that
* processors may use to pull and acknowledge as processed, EE Export data.
* Data passed to processors is wrapped in ExportDataBlocks which in turn
* wrap a BBContainer.
*
* Processors are loaded by reflection based on configuration in project.xml.
*/
public class ExportManager
{
/**
* Processors also log using this facility.
*/
private static final VoltLogger exportLog = new VoltLogger("EXPORT");
private final COWSortedMap<Long,ExportGeneration> m_generations =
new COWSortedMap<Long, ExportGeneration>();
/*
* When a generation is drained store a the id so
* we can tell if a buffer comes late
*/
private final CopyOnWriteArrayList<Long> m_generationGhosts =
new CopyOnWriteArrayList<Long>();
private final HostMessenger m_messenger;
/**
* Set of partition ids for which this export manager instance is master of
*/
private final Set<Integer> m_masterOfPartitions = new HashSet<Integer>();
/**
* Thrown if the initial setup of the loader fails
*/
public static class SetupException extends Exception {
private static final long serialVersionUID = 1L;
SetupException(final String msg) {
super(msg);
}
SetupException(final Throwable cause) {
super(cause);
}
}
/**
* Connections OLAP loaders. Currently at most one loader allowed.
* Supporting multiple loaders mainly involves reference counting
* the EE data blocks and bookkeeping ACKs from processors.
*/
AtomicReference<ExportDataProcessor> m_processor = new AtomicReference<ExportDataProcessor>();
/** Obtain the global ExportManager via its instance() method */
private static ExportManager m_self;
private final int m_hostId;
private String m_loaderClass;
private volatile Properties m_processorConfig = new Properties();
/*
* Issue a permit when a generation is drained so that when we are truncating if a generation
* is completely truncated we can wait for the on generation drained task to finish.
*
* This eliminates a race with CL replay where it may do catalog updates and such while truncation
* is still running on generation drained.
*/
private final Semaphore m_onGenerationDrainedForTruncation = new Semaphore(0);
private final Runnable m_onGenerationDrained = new Runnable() {
@Override
public void run() {
/*
* Do all the work to switch to a new generation in the thread for the processor
* of the old generation
*/
ExportDataProcessor proc = m_processor.get();
if (proc == null) {
VoltDB.crashLocalVoltDB("No export data processor found", true, null);
}
proc.queueWork(new Runnable() {
@Override
public void run() {
try {
rollToNextGeneration();
} catch (RuntimeException e) {
exportLog.error("Error rolling to next export generation", e);
} catch (Exception e) {
exportLog.error("Error rolling to next export generation", e);
} finally {
m_onGenerationDrainedForTruncation.release();
}
}
});
}
};
private void rollToNextGeneration() throws Exception {
ExportDataProcessor newProcessor = null;
ExportDataProcessor oldProcessor = null;
ExportGeneration oldGeneration = null;
synchronized (ExportManager.this) {
oldGeneration = m_generations.firstEntry().getValue();
m_generationGhosts.add(m_generations.remove(m_generations.firstEntry().getKey()).m_timestamp);
exportLog.info("Finished draining generation " + oldGeneration.m_timestamp);
try {
if (m_loaderClass != null && !m_generations.isEmpty()) {
exportLog.info("Creating connector " + m_loaderClass);
final Class<?> loaderClass = Class.forName(m_loaderClass);
//Make it so
ExportGeneration nextGeneration = m_generations.firstEntry().getValue();
newProcessor = (ExportDataProcessor)loaderClass.newInstance();
newProcessor.addLogger(exportLog);
newProcessor.setExportGeneration(nextGeneration);
newProcessor.setProcessorConfig(m_processorConfig);
newProcessor.readyForData();
if (nextGeneration.isDiskBased()) {
/*
* Changes in partition count can make the load balancing strategy not capture
* all partitions for data that was from a previously larger cluster.
* For those use a naive leader election strategy that is implemented
* by export generation.
*/
nextGeneration.kickOffLeaderElection();
} else {
/*
* This strategy is the one that piggy backs on
* regular partition mastership distribution to determine
* who will process export data for different partitions.
* We stashed away all the ones we have mastership of
* in m_masterOfPartitions
*/
for( Integer partitionId: m_masterOfPartitions) {
nextGeneration.acceptMastershipTask(partitionId);
}
}
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error creating next export processor", true, e);
}
oldProcessor = m_processor.getAndSet(newProcessor);
}
/*
* The old processor should not be null since this shutdown task
* is running for this processor
*/
oldProcessor.shutdown();
try {
if (oldGeneration != null)
oldGeneration.closeAndDelete();
} catch (IOException e) {
e.printStackTrace();
exportLog.error(e);
}
}
/**
* Construct ExportManager using catalog.
* @param myHostId
* @param catalogContext
* @throws ExportManager.SetupException
*/
public static synchronized void initialize(
int myHostId,
CatalogContext catalogContext,
boolean isRejoin,
HostMessenger messenger,
List<Pair<Integer, Long>> partitions)
throws ExportManager.SetupException
{
ExportManager em = new ExportManager(myHostId, catalogContext, messenger, partitions);
Connector connector = getConnector(catalogContext);
m_self = em;
if (connector != null && connector.getEnabled() == true) {
em.createInitialExportProcessor(catalogContext, connector, true, partitions, isRejoin);
}
}
/**
* Indicate to associated {@link ExportGeneration}s to become
* masters for the given partition id
* @param partitionId
*/
synchronized public void acceptMastership(int partitionId) {
if (m_loaderClass == null) {
return;
}
Preconditions.checkArgument(
m_masterOfPartitions.add(partitionId),
"can't acquire mastership twice for partition id: " + partitionId
);
exportLog.info("ExportManager accepting mastership for partition " + partitionId);
/*
* Only the first generation will have a processor which
* makes it safe to accept mastership.
*/
ExportGeneration gen = m_generations.firstEntry().getValue();
if (gen != null && !gen.isDiskBased()) {
gen.acceptMastershipTask(partitionId);
}
}
/**
* Get the global instance of the ExportManager.
* @return The global single instance of the ExportManager.
*/
public static ExportManager instance() {
return m_self;
}
public static void setInstanceForTest(ExportManager self) {
m_self = self;
}
protected ExportManager() {
m_hostId = 0;
m_messenger = null;
}
private static Connector getConnector(CatalogContext catalogContext) {
final Cluster cluster = catalogContext.catalog.getClusters().get("cluster");
final Database db = cluster.getDatabases().get("database");
final Connector conn= db.getConnectors().get("0");
return conn;
}
/**
* Read the catalog to setup manager and loader(s)
* @param siteTracker
*/
private ExportManager(
int myHostId,
CatalogContext catalogContext,
HostMessenger messenger,
List<Pair<Integer, Long>> partitions)
throws ExportManager.SetupException
{
m_hostId = myHostId;
m_messenger = messenger;
final Cluster cluster = catalogContext.catalog.getClusters().get("cluster");
final Connector conn = getConnector(catalogContext);
if (conn == null) {
exportLog.info("System is not using any export functionality.");
return;
}
if (conn.getEnabled() == false) {
exportLog.info("Export is disabled by user configuration.");
return;
}
updateProcessorConfig(conn);
exportLog.info(String.format("Export is enabled and can overflow to %s.", cluster.getExportoverflow()));
m_loaderClass = conn.getLoaderclass();
}
private synchronized void createInitialExportProcessor(
CatalogContext catalogContext,
final Connector conn,
boolean startup,
List<Pair<Integer, Long>> partitions,
boolean isRejoin) {
try {
exportLog.info("Creating connector " + m_loaderClass);
ExportDataProcessor newProcessor = null;
final Class<?> loaderClass = Class.forName(m_loaderClass);
newProcessor = (ExportDataProcessor)loaderClass.newInstance();
newProcessor.addLogger(exportLog);
newProcessor.setProcessorConfig(m_processorConfig);
m_processor.set(newProcessor);
File exportOverflowDirectory = new File(catalogContext.cluster.getExportoverflow());
/*
* If this is a catalog update providing an existing generation,
* the persisted stuff has already been initialized
*/
if (startup) {
initializePersistedGenerations(
exportOverflowDirectory,
catalogContext, conn);
}
/*
* If this is startup there is no existing generation created for new export data
* So construct one here, otherwise use the one provided
*/
if (startup) {
final ExportGeneration currentGeneration = new ExportGeneration(
catalogContext.m_uniqueId,
m_onGenerationDrained,
exportOverflowDirectory, isRejoin);
currentGeneration.initializeGenerationFromCatalog(conn, m_hostId, m_messenger, partitions);
m_generations.put( catalogContext.m_uniqueId, currentGeneration);
}
final ExportGeneration nextGeneration = m_generations.firstEntry().getValue();
/*
* For the newly constructed processor, provide it the oldest known generation
*/
newProcessor.setExportGeneration(nextGeneration);
newProcessor.readyForData();
if (startup) {
/*
* If the oldest known generation was disk based,
* and we are using server side export we need to kick off a leader election
* to choose which server is going to export each partition
*/
if (nextGeneration.isDiskBased()) {
nextGeneration.kickOffLeaderElection();
}
} else {
/*
* When it isn't startup, it is necessary to kick things off with the mastership
* settings that already exist
*/
if (nextGeneration.isDiskBased()) {
/*
* Changes in partition count can make the load balancing strategy not capture
* all partitions for data that was from a previously larger cluster.
* For those use a naive leader election strategy that is implemented
* by export generation.
*/
nextGeneration.kickOffLeaderElection();
} else {
/*
* This strategy is the one that piggy backs on
* regular partition mastership distribution to determine
* who will process export data for different partitions.
* We stashed away all the ones we have mastership of
* in m_masterOfPartitions
*/
for( Integer partitionId: m_masterOfPartitions) {
nextGeneration.acceptMastershipTask(partitionId);
}
}
}
}
catch (final ClassNotFoundException e) {
exportLog.l7dlog( Level.ERROR, LogKeys.export_ExportManager_NoLoaderExtensions.name(), e);
Throwables.propagate(e);
}
catch (final Exception e) {
Throwables.propagate(e);
}
}
private void initializePersistedGenerations(
File exportOverflowDirectory, CatalogContext catalogContext,
Connector conn) throws IOException {
TreeSet<File> generationDirectories = new TreeSet<File>();
for (File f : exportOverflowDirectory.listFiles()) {
if (f.isDirectory()) {
if (!f.canRead() || !f.canWrite() || !f.canExecute()) {
throw new RuntimeException("Can't one of read/write/execute directory " + f);
}
generationDirectories.add(f);
}
}
//Only give the processor to the oldest generation
for (File generationDirectory : generationDirectories) {
ExportGeneration generation =
new ExportGeneration(
m_onGenerationDrained,
generationDirectory);
if (generation.initializeGenerationFromDisk(conn, m_messenger)) {
m_generations.put( generation.m_timestamp, generation);
} else {
String list[] = generationDirectory.list();
if (list != null && list.length == 0) {
try {
VoltFile.recursivelyDelete(generationDirectory);
} catch (IOException ioe) {
}
} else {
exportLog.error("Invalid export generation in overflow directory " + generationDirectory
+ " this will need to be manually cleaned up. number of files left: "
+ (list != null ? list.length : 0));
}
}
}
}
private void updateProcessorConfig(final Connector conn) {
Properties newConfig = new Properties();
if (conn.getConfig() != null) {
Iterator<ConnectorProperty> connPropIt = conn.getConfig().iterator();
while (connPropIt.hasNext()) {
ConnectorProperty prop = connPropIt.next();
newConfig.put(prop.getName(), prop.getValue());
}
}
m_processorConfig = newConfig;
}
public synchronized void updateCatalog(CatalogContext catalogContext, List<Pair<Integer, Long>> partitions)
{
final Cluster cluster = catalogContext.catalog.getClusters().get("cluster");
final Database db = cluster.getDatabases().get("database");
final Connector conn= db.getConnectors().get("0");
if (conn == null || !conn.getEnabled()) {
m_loaderClass = null;
return;
}
m_loaderClass = conn.getLoaderclass();
updateProcessorConfig(conn);
File exportOverflowDirectory = new File(catalogContext.cluster.getExportoverflow());
ExportGeneration newGeneration = null;
try {
newGeneration = new ExportGeneration(
catalogContext.m_uniqueId,
m_onGenerationDrained,
exportOverflowDirectory, false);
} catch (IOException e1) {
VoltDB.crashLocalVoltDB("Error processing catalog update in export system", true, e1);
}
newGeneration.initializeGenerationFromCatalog(conn, m_hostId, m_messenger, partitions);
m_generations.put(catalogContext.m_uniqueId, newGeneration);
/*
* If there is no existing export processor, create an initial one.
* This occurs when export is turned on/off at runtime.
*/
if (m_processor.get() == null) {
createInitialExportProcessor(catalogContext, conn, false, partitions, false);
}
}
public void shutdown() {
ExportDataProcessor proc = m_processor.getAndSet(null);
if (proc != null) {
proc.shutdown();
}
for (ExportGeneration generation : m_generations.values()) {
generation.close();
}
m_generations.clear();
m_loaderClass = null;
}
public static long getQueuedExportBytes(int partitionId, String signature) {
ExportManager instance = instance();
try {
Map<Long, ExportGeneration> generations = instance.m_generations;
if (generations.isEmpty()) {
assert(false);
return -1;
}
long exportBytes = 0;
for (ExportGeneration generation : generations.values()) {
exportBytes += generation.getQueuedExportBytes( partitionId, signature);
}
return exportBytes;
} catch (Exception e) {
//Don't let anything take down the execution site thread
exportLog.error(e);
}
return 0;
}
/*
* This method pulls double duty as a means of pushing export buffers
* and "syncing" export data to disk. Syncing doesn't imply fsync, it just means
* writing the data to a file instead of keeping it all in memory.
* End of stream indicates that no more data is coming from this source
* for this generation.
*/
public static void pushExportBuffer(
long exportGeneration,
int partitionId,
String signature,
long uso,
long bufferPtr,
ByteBuffer buffer,
boolean sync,
boolean endOfStream) {
ExportManager instance = instance();
try {
ExportGeneration generation = instance.m_generations.get(exportGeneration);
if (generation == null) {
DBBPool.deleteCharArrayMemory(bufferPtr);
/*
* If the generation was already drained it is fine for a buffer to come late and miss it
*/
synchronized(instance) {
if (!instance.m_generationGhosts.contains(exportGeneration)) {
assert(false);
exportLog.error("Could not a find an export generation " + exportGeneration +
". Should be impossible. Discarding export data");
}
}
return;
}
/*
* Due to issues double freeing and using after free,
* copy the buffer onto the heap and rely on GC.
*
* This should buy enough time to diagnose the root cause.
*/
if (buffer != null) {
ByteBuffer buf = ByteBuffer.allocate(buffer.remaining());
buf.put(buffer);
buf.flip();
DBBPool.deleteCharArrayMemory(bufferPtr);
buffer = buf;
bufferPtr = 0;
}
generation.pushExportBuffer(partitionId, signature, uso, bufferPtr, buffer, sync, endOfStream);
} catch (Exception e) {
//Don't let anything take down the execution site thread
exportLog.error("Error pushing export buffer", e);
}
}
public void truncateExportToTxnId(long snapshotTxnId, long[] perPartitionTxnIds) {
exportLog.info("Truncating export data after txnId " + snapshotTxnId);
for (ExportGeneration generation : m_generations.values()) {
//If the generation was completely drained, wait for the task to finish running
//by waiting for the permit that will be generated
if (generation.truncateExportToTxnId(snapshotTxnId, perPartitionTxnIds)) {
try {
m_onGenerationDrainedForTruncation.acquire();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB("Interrupted truncating export data", true, e);
}
}
}
}
}
|
package org.csstudio.channel.views;
import gov.bnl.channelfinder.api.ChannelUtil;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.widgets.Combo;
import org.csstudio.channel.widgets.PVTableByPropertyWidget;
import org.csstudio.ui.util.helpers.ComboHistoryHelper;
/**
* View that allows to create a waterfall plot out of a given PV.
*/
public class PVTableByPropertyView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "org.csstudio.channel.views.PVTableByPropertyView";
/** Memento */
private IMemento memento = null;
/** Memento tag */
private static final String MEMENTO_PVNAME = "PVName"; //$NON-NLS-1$
/**
* The constructor.
*/
public PVTableByPropertyView() {
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
}
@Override
public void init(final IViewSite site, final IMemento memento)
throws PartInitException {
super.init(site, memento);
// Save the memento
this.memento = memento;
}
@Override
public void saveState(final IMemento memento) {
super.saveState(memento);
// Save the currently selected variable
if (combo.getText() != null) {
memento.putString(MEMENTO_PVNAME, combo.getText());
}
}
public void setPVName(String name) {
combo.setText(name);
changeQuery(name);
}
private Combo combo;
private PVTableByPropertyWidget tableWidget;
private Combo columnProperty;
private Combo rowProperty;
private Composite parent;
private void changeQuery(String text) {
tableWidget.setColumnProperty(null);
tableWidget.setRowProperty(null);
tableWidget.setChannelQuery(text);
if (tableWidget.getChannels() != null) {
Collection<String> propertyNames = ChannelUtil.getPropertyNames(tableWidget.getChannels());
rowProperty.setItems(propertyNames.toArray(new String[propertyNames.size()]));
columnProperty.setItems(propertyNames.toArray(new String[propertyNames.size()]));
parent.layout();
}
}
@Override
public void createPartControl(Composite parent) {
this.parent = parent;
parent.setLayout(new FormLayout());
Label lblPvName = new Label(parent, SWT.NONE);
FormData fd_lblPvName = new FormData();
fd_lblPvName.top = new FormAttachment(0, 13);
fd_lblPvName.left = new FormAttachment(0, 10);
lblPvName.setLayoutData(fd_lblPvName);
lblPvName.setText("Query:");
ComboViewer comboViewer = new ComboViewer(parent, SWT.NONE);
combo = comboViewer.getCombo();
FormData fd_combo = new FormData();
fd_combo.top = new FormAttachment(0, 10);
fd_combo.left = new FormAttachment(lblPvName, 6);
combo.setLayoutData(fd_combo);
tableWidget = new PVTableByPropertyWidget(parent, SWT.NONE);
FormData fd_waterfallComposite = new FormData();
fd_waterfallComposite.bottom = new FormAttachment(100, -10);
fd_waterfallComposite.top = new FormAttachment(combo, 6);
fd_waterfallComposite.left = new FormAttachment(0, 10);
fd_waterfallComposite.right = new FormAttachment(100, -10);
tableWidget.setLayoutData(fd_waterfallComposite);
ComboHistoryHelper name_helper =
new ComboHistoryHelper(Activator.getDefault()
.getDialogSettings(), "WaterfallPVs", combo, 20, true) {
@Override
public void newSelection(final String pv_name) {
changeQuery(pv_name);
}
};
Label lblRow = new Label(parent, SWT.NONE);
fd_combo.right = new FormAttachment(lblRow, -6);
FormData fd_lblRow = new FormData();
fd_lblRow.top = new FormAttachment(lblPvName, 0, SWT.TOP);
lblRow.setLayoutData(fd_lblRow);
lblRow.setText("Row:");
rowProperty = new Combo(parent, SWT.NONE);
fd_lblRow.right = new FormAttachment(rowProperty, -6);
FormData fd_rowProperty = new FormData();
fd_rowProperty.top = new FormAttachment(lblPvName, -3, SWT.TOP);
rowProperty.setLayoutData(fd_rowProperty);
rowProperty.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
tableWidget.setRowProperty(rowProperty.getItem(rowProperty.getSelectionIndex()));
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
tableWidget.setRowProperty(rowProperty.getItem(rowProperty.getSelectionIndex()));
}
});
Label lblColumn = new Label(parent, SWT.NONE);
fd_rowProperty.right = new FormAttachment(lblColumn, -6);
FormData fd_lblColumn = new FormData();
fd_lblColumn.top = new FormAttachment(lblPvName, 0, SWT.TOP);
lblColumn.setLayoutData(fd_lblColumn);
lblColumn.setText("Column:");
columnProperty = new Combo(parent, SWT.NONE);
fd_lblColumn.right = new FormAttachment(columnProperty, -6);
FormData fd_columnProperty = new FormData();
fd_columnProperty.bottom = new FormAttachment(tableWidget, -6);
fd_columnProperty.right = new FormAttachment(100, -10);
columnProperty.setLayoutData(fd_columnProperty);
columnProperty.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
tableWidget.setColumnProperty(columnProperty.getItem(columnProperty.getSelectionIndex()));
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
tableWidget.setColumnProperty(columnProperty.getItem(columnProperty.getSelectionIndex()));
}
});
name_helper.loadSettings();
if (memento != null && memento.getString(MEMENTO_PVNAME) != null) {
setPVName(memento.getString(MEMENTO_PVNAME));
}
}
}
|
package org.csstudio.trends.databrowser.model;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.data.TimestampFactory;
import org.csstudio.platform.model.IArchiveDataSource;
import org.csstudio.swt.chart.TraceType;
import org.csstudio.trends.databrowser.Plugin;
import org.csstudio.trends.databrowser.preferences.Preferences;
import org.csstudio.util.swt.DefaultColors;
import org.csstudio.util.time.RelativeTime;
import org.csstudio.util.time.StartEndTimeParser;
import org.csstudio.util.xml.DOMHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Model
{
/** Start- and end time specifications. */
private StartEndTimeParser start_end_times;
/** Scan period for 'live' data in seconds. */
private double scan_period = 0.5;
/** Minimum for scan_period. */
public static final double MIN_SCAN_RATE = 0.1;
/** Update period of the plot in seconds. */
private double update_period = 1.0;
/** Minumum for update_period. */
public static final double MIN_UPDATE_RATE = 0.5;
/** Ring buffer size, number of elements, for 'live' data. */
private int ring_size = 1024;
private ArrayList<AbstractModelItem> items = new ArrayList<AbstractModelItem>();
/** <code>true</code> if all model items were 'started'. */
private boolean is_running = false;
private ArrayList<ModelListener> listeners =
new ArrayList<ModelListener>();
/** Construct a new model. */
@SuppressWarnings("nls")
public Model()
{
String start, end;
try
{
start = Preferences.getStartSpecification();
end = Preferences.getEndSpecification();
}
catch (Exception ex)
{ // No prefs because running as unit test?
start = "-1 hour";
end = RelativeTime.NOW;
}
try
{
// Set time defaults, since otherwise start/end would be null.
setTimeSpecifications(start, end);
}
catch (Exception ex)
{
Plugin.logException("Cannot init. time range", ex);
}
}
/** Must be called to dispose the model. */
public void dispose()
{
disposeItems();
}
/** Peoperly clear the item list. */
private void disposeItems()
{
for (AbstractModelItem item : items)
item.dispose();
items.clear();
}
/** Add a listener. */
public void addListener(ModelListener listener)
{
if (listeners.contains(listener))
throw new Error("Listener added more than once."); //$NON-NLS-1$
listeners.add(listener);
}
/** Remove a listener. */
public void removeListener(ModelListener listener)
{
if (!listeners.contains(listener))
throw new Error("Unknown listener."); //$NON-NLS-1$
listeners.remove(listener);
}
/** Set a new start and end time specification.
* <p>
* Also updates the current start and end time with
* values computed from the specs "right now".
* @see org.csstudio.util.time.StartEndTimeParser
* @see #getStartSpecification()
* @see #setTimeRange(ITimestamp, ITimestamp)
* @exception Exception on parse error of specs.
*/
public void setTimeSpecifications(String start_specification,
String end_specification)
throws Exception
{
start_end_times =
new StartEndTimeParser(start_specification, end_specification);
// In case of parse errors, we won't reach this point
// fireTimeSpecificationsChanged, fireTimeRangeChanged
for (ModelListener l : listeners)
{
l.timeSpecificationsChanged();
l.timeRangeChanged();
}
}
/** Get the start specification that is held 'permamently' when
* the model is saved and re-loaded.
* <p>
* When the specifications are initially loaded or later changed,
* the current start and end time is computed from the specs.
* <p>
* At runtime, scroll operations will update the currently
* displayed start and end time by re-evaluating a
* relative start specification of for example "-30 min",
* but that won't affect the actual start/end specification.
* <p>
* The config view has buttons to force an update of the specification
* from the current start/end times and vice versa.
*
* @see #getStartTime()
* @return Start specification.
*/
public String getStartSpecification()
{ return start_end_times.getStartSpecification(); }
/** @see #getStartSpecification()
* @return End specification.
*/
public String getEndSpecification()
{ return start_end_times.getEndSpecification(); }
/** Re-evaluate the start/end specifications.
* <p>
* In case of absolute start/end time specs, nothing changes.
* For relative start/end time specs, the 'current' start and
* end times get updated.
*/
public void updateStartEndTime()
{
try
{
if (start_end_times.eval())
{
// fireTimeRangeChanged
for (ModelListener l : listeners)
l.timeRangeChanged();
}
}
catch (Exception ex)
{
Plugin.logException("Model start/end time update error", ex); //$NON-NLS-1$
}
}
/** The start time according to the most recent evaluation
* of the start specification.
* This is the time where the plot should start.
* @see #getStartSpecification()
* @return Start time.
*/
public ITimestamp getStartTime()
{ return TimestampFactory.fromCalendar(start_end_times.getStart()); }
/** The end time according to the most recent evaluation
* of the end specification.
* This is the time where the plot should end.
* @see #getStartTime()
* @return End time.
*/
public ITimestamp getEndTime()
{ return TimestampFactory.fromCalendar(start_end_times.getEnd()); }
/** @return Returns the scan period in seconds. */
public double getScanPeriod()
{ return scan_period; }
/** @return Returns the update period in seconds. */
public double getUpdatePeriod()
{ return update_period; }
/** Set new scan and update periods.
* <p>
* Actual periods might differ because of enforced minumum etc.
*
* @param scan Scan period in seconds.
* @param update Update period in seconds.
*/
public void setPeriods(double scan, double update)
{
// Don't allow 'too fast'
if (scan < MIN_SCAN_RATE)
scan = MIN_SCAN_RATE;
if (update < MIN_UPDATE_RATE)
update = MIN_UPDATE_RATE;
// No sense in redrawing faster than the data can change.
if (update < scan)
update = scan;
scan_period = scan;
update_period = update;
// firePeriodsChanged
for (ModelListener l : listeners)
l.periodsChanged();
}
/** @return Returns the current ring buffer size. */
public int getRingSize()
{ return ring_size; }
/** @param ring_size The ring_size to set. */
public void setRingSize(int ring_size)
{
this.ring_size = ring_size;
for (AbstractModelItem item : items)
{
if (item instanceof PVModelItem)
((PVModelItem)item).setRingSize(ring_size);
}
}
/** @return Returns the number of chart items. */
public int getNumItems()
{ return items.size(); }
/** @return Returns the chart item of given index. */
public IModelItem getItem(int i)
{ return items.get(i); }
public enum ItemType
{
/** A live or archived PV */
ProcessVariable,
/** A computed item */
Formula
};
/** Add a new item to the model.
*
* @param pv_name The PV to add.
* @return Returns the newly added chart item.
*/
public IPVModelItem addPV(String pv_name)
{
return (IPVModelItem) add(ItemType.ProcessVariable, pv_name, -1);
}
/** Add a new item to the model.
*
* @param pv_name The PV to add.
* @param axis_index The Y axis to use [0, 1, ...] or -1 for new axis.
* @return Returns the newly added chart item.
*/
public IPVModelItem addPV(String pv_name, int axis_index)
{
return (IPVModelItem) add(ItemType.ProcessVariable, pv_name, axis_index);
}
/** Add a new item to the model.
*
* @param type Describes the type of PV to add
* @param pv_name The PV to add.
* @return Returns the newly added chart item.
*/
public IModelItem add(ItemType type, String pv_name)
{
return add(type, pv_name, -1);
}
/** Add a new item to the model.
*
* @param type Describes the type of PV to add
* @param pv_name The PV to add.
* @param axis_index The Y axis to use [0, 1, ...] or -1 for new axis.
* @return Returns the newly added chart item.
*/
public IModelItem add(ItemType type, String pv_name, int axis_index)
{
int c = items.size();
if (axis_index < 0)
{
axis_index = 0;
for (int i=0; i<c; ++i)
if (axis_index < items.get(i).getAxisIndex() + 1)
axis_index = items.get(i).getAxisIndex() + 1;
}
int line_width = 0;
return add(type, pv_name, axis_index, DefaultColors.getRed(c),
DefaultColors.getGreen(c), DefaultColors.getBlue(c),
line_width);
}
/** Add a new item to the model.
*
* @param type Describes the type of PV to add
* @param pv_name The PV to add.
* @param axis_index The Y axis to use [0, 1, ...]
* @param red,
* @param green,
* @param blue The color to use.
* @param line_width The line width.
* @return Returns the newly added chart item, or <code>null</code>.
*/
private IModelItem add(ItemType type, String pv_name, int axis_index,
int red, int green, int blue, int line_width)
{
// Do not allow duplicate PV names.
int i = findEntry(pv_name);
if (i >= 0)
return items.get(i);
// Default low..high range
double low = 0.0;
double high = 10.0;
final boolean visible = true;
boolean auto_scale;
try
{
auto_scale = Preferences.getAutoScale();
}
catch (Exception ex)
{ // No prefs because in unit test
auto_scale = false;
}
boolean log_scale = false;
TraceType trace_type = TraceType.Lines;
// Use settings of existing item for that axis - if there is one
for (IModelItem item : items)
if (item.getAxisIndex() == axis_index)
{
low = item.getAxisLow();
high = item.getAxisHigh();
auto_scale = item.getAutoScale();
log_scale = item.getLogScale();
trace_type = item.getTraceType();
break;
}
AbstractModelItem item = null;
switch (type)
{
case ProcessVariable:
item = new PVModelItem(this, pv_name, ring_size,
axis_index, low, high, visible, auto_scale,
red, green, blue, line_width, trace_type,
log_scale);
break;
case Formula:
item = new FormulaModelItem(this, pv_name,
axis_index, low, high, visible, auto_scale,
red, green, blue, line_width, trace_type,
log_scale);
if (items.size() > 0)
{
// Create a dummy example formula
// that doubles the first PV
FormulaInput inputs[] = new FormulaInput[]
{
new FormulaInput(items.get(0), "x") //$NON-NLS-1$
};
try
{
((FormulaModelItem)item).setFormula("2*x", inputs); //$NON-NLS-1$
}
catch (Exception ex)
{
Plugin.logException("Setting formula", ex); //$NON-NLS-1$
}
}
break;
}
silentAdd(item);
fireEntryAdded(item);
return item;
}
/** Set axis limits of all items on given axis. */
public void setAxisLimits(int axis_index, double low, double high)
{
for (AbstractModelItem item : items)
{
if (item.getAxisIndex() != axis_index)
continue;
// Don't call setAxisMin(), Max(), since that would recurse.
item.setAxisLimitsSilently(low, high);
fireEntryConfigChanged(item);
}
}
/** Set axis type (log, linear) of all items on given axis. */
void setLogScale(int axis_index, boolean use_log_scale)
{
for (AbstractModelItem item : items)
{
if (item.getAxisIndex() != axis_index)
continue;
if (item.getLogScale() != use_log_scale)
{
item.setLogScaleSilently(use_log_scale);
fireEntryConfigChanged(item);
}
}
}
/** Set auto scale option of all items on given axis.
* <p>
* Also updates the auto scaling of all other items on same axis.
*/
void setAutoScale(int axis_index, boolean use_auto_scale)
{
for (AbstractModelItem item : items)
{
if (item.getAxisIndex() != axis_index)
continue;
if (item.getAutoScale() != use_auto_scale)
{
item.setAutoScaleSilently(use_auto_scale);
fireEntryConfigChanged(item);
}
}
}
/** Add an archive data source to all items in the model.
* @see IModelItem#addArchiveDataSource(IArchiveDataSource)
*/
public void addArchiveDataSource(IArchiveDataSource archive)
{
for (IModelItem item : items)
if (item instanceof IPVModelItem)
((IPVModelItem) item).addArchiveDataSource(archive);
}
/** As <code>add()</code>, but without listener notification.
* @see #add()
*/
private void silentAdd(AbstractModelItem item)
{
items.add(item);
if (is_running && item instanceof PVModelItem)
((PVModelItem)item).start();
}
/** Remove item with given PV name. */
public void remove(String pv_name)
{
int i = findEntry(pv_name);
if (i < 0)
return;
AbstractModelItem item = items.remove(i);
item.dispose();
fireEntryRemoved(item);
}
/** @return Returns index of entry with given PV name or <code>-1</code>. */
int findEntry(String pv_name)
{
for (int i=0; i<items.size(); ++i)
if (items.get(i).getName().equals(pv_name))
return i;
return -1;
}
/** @return Returns <code>true</code> if running.
* @see #start
* @see #stop
*/
public boolean isRunning()
{
return is_running;
}
/** Start the model (subscribe, ...) */
public final void start()
{
if (!is_running)
{
for (AbstractModelItem item : items)
if (item instanceof PVModelItem)
((PVModelItem)item).start();
is_running = true;
}
}
/** Stop the model (subscribe, ...) */
public final void stop()
{
if (is_running)
{
for (AbstractModelItem item : items)
if (item instanceof PVModelItem)
((PVModelItem)item).stop();
is_running = false;
}
}
/** Scan PVs. */
public final ITimestamp scan()
{
ITimestamp now = TimestampFactory.now();
for (AbstractModelItem item : items)
if (item instanceof PVModelItem)
((PVModelItem)item).addCurrentValueToSamples(now);
return now;
}
/** Update (re-compute) formulas. */
public final void updateFormulas()
{
for (AbstractModelItem item : items)
if (item instanceof FormulaModelItem)
((FormulaModelItem)item).compute();
}
/** @return Returns the whole model as an XML string. */
@SuppressWarnings("nls")
public String getXMLContent()
{
StringBuffer b = new StringBuffer(1024);
b.append("<databrowser>\n");
b.append(" <start>" + start_end_times.getStartSpecification() + "</start>\n");
b.append(" <end>" + start_end_times.getEndSpecification() + "</end>\n");
b.append(" <scan_period>" + scan_period + "</scan_period>\n");
b.append(" <update_period>" + update_period + "</update_period>\n");
b.append(" <ring_size>" + ring_size + "</ring_size>\n");
b.append(" <pvlist>\n");
for (AbstractModelItem item : items)
b.append(item.getXMLContent());
b.append(" </pvlist>\n");
b.append("</databrowser>");
String s = b.toString();
return s;
}
/** Load model from XML file stream. */
public void load(InputStream stream) throws Exception
{
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = docBuilder.parse(stream);
loadFromDocument(doc);
}
/** Load model from DOM document. */
@SuppressWarnings("nls")
private void loadFromDocument(Document doc) throws Exception
{
boolean was_running = is_running;
if (was_running)
stop();
disposeItems();
// Check if it's a <databrowser/>.
doc.getDocumentElement().normalize();
Element root_node = doc.getDocumentElement();
final String root_name = root_node.getNodeName();
if (!root_name.equals("databrowser"))
throw new Exception("Expected <databrowser>, found <" + root_name
+ ">");
// Get the period entries
String start_specification = DOMHelper.getSubelementString(root_node, "start");
String end_specification = DOMHelper.getSubelementString(root_node, "end");
if (start_specification.length() < 1 ||
end_specification.length() < 1)
{
start_specification = Preferences.getStartSpecification();
end_specification = Preferences.getEndSpecification();
}
start_end_times = new StartEndTimeParser(start_specification,
end_specification);
double scan = DOMHelper.getSubelementDouble(root_node, "scan_period");
double update = DOMHelper.getSubelementDouble(root_node, "update_period");
ring_size = DOMHelper.getSubelementInt(root_node, "ring_size");
Element pvlist = DOMHelper.findFirstElementNode(root_node
.getFirstChild(), "pvlist");
if (pvlist != null)
{
Element pv = DOMHelper.findFirstElementNode(
pvlist.getFirstChild(), PVModelItem.TAG_PV);
while (pv != null)
{
silentAdd(PVModelItem.loadFromDOM(this, pv, ring_size));
pv = DOMHelper.findNextElementNode(pv, PVModelItem.TAG_PV);
}
}
// This also notifies listeners about the new periods:
setPeriods(scan, update);
fireEntriesChanged();
if (was_running)
start();
}
/** @see ModelListener#entryConfigChanged(IModelItem) */
void fireEntryConfigChanged(IModelItem item)
{
for (ModelListener l : listeners)
l.entryConfigChanged(item);
}
/** @see ModelListener#entryLookChanged(IModelItem) */
void fireEntryLookChanged(IModelItem item)
{
for (ModelListener l : listeners)
l.entryLookChanged(item);
}
/** @see ModelListener#entryArchivesChanged(IModelItem) */
void fireEntryArchivesChanged(IModelItem item)
{
for (ModelListener l : listeners)
l.entryArchivesChanged(item);
}
/** @see ModelListener#entryAdded(IModelItem) */
void fireEntryAdded(IModelItem item)
{
for (ModelListener l : listeners)
l.entryAdded(item);
}
/** @see ModelListener#entryRemoved(IModelItem) */
void fireEntryRemoved(IModelItem item)
{
for (ModelListener listener : listeners)
listener.entryRemoved(item);
}
/** @see ModelListener#entriesChanged() */
private void fireEntriesChanged()
{
for (ModelListener l : listeners)
l.entriesChanged();
}
}
|
package org.jboss.hal.testsuite.test.configuration.messaging.connections;
import org.apache.commons.lang.RandomStringUtils;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.testsuite.category.Shared;
import org.jboss.hal.testsuite.creaper.ResourceVerifier;
import org.jboss.hal.testsuite.page.config.MessagingPage;
import org.jboss.hal.testsuite.test.configuration.messaging.AbstractMessagingTestCase;
import org.jboss.hal.testsuite.util.ConfigChecker;
import org.jboss.hal.testsuite.util.ElytronIntegrationChecker;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wildfly.extras.creaper.commands.messaging.AddQueue;
import org.wildfly.extras.creaper.commands.messaging.RemoveQueue;
import org.wildfly.extras.creaper.core.CommandFailedException;
import org.wildfly.extras.creaper.core.online.ModelNodeResult;
import org.wildfly.extras.creaper.core.online.operations.Address;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Values;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
@RunWith(Arquillian.class)
@Category(Shared.class)
public class BridgesTestCase extends AbstractMessagingTestCase {
private static final Logger log = LoggerFactory.getLogger(BridgesTestCase.class);
private static final String BRIDGE = "bridge_" + RandomStringUtils.randomAlphanumeric(5);
private static final String BRIDGE_TBA = "bridge-TBA_" + RandomStringUtils.randomAlphanumeric(5);
private static final String BRIDGE_TBR = "bridge-TBR_" + RandomStringUtils.randomAlphanumeric(5);
private static final Address BRIDGE_ADDRESS = DEFAULT_MESSAGING_SERVER.and("bridge", BRIDGE);
private static final Address BRIDGE_TBR_ADDRESS = DEFAULT_MESSAGING_SERVER.and("bridge", BRIDGE_TBR);
private static final Address BRIDGE_TBA_ADDRESS = DEFAULT_MESSAGING_SERVER.and("bridge", BRIDGE_TBA);
private static final Address BRIDGE_TBA_2_ADDRESS = DEFAULT_MESSAGING_SERVER.and("bridge", "bridge-TBA_2_" + RandomStringUtils.randomAlphanumeric(5));
private static final Address BRIDGE_TBA_3_ADDRESS = DEFAULT_MESSAGING_SERVER.and("bridge", "bridge-TBA_3_" + RandomStringUtils.randomAlphanumeric(5));
private static final String
CONNECTOR = "http-connector",
QUEUE_CREATE_BRIDGE = "testQueue_" + RandomStringUtils.randomAlphanumeric(5),
QUEUE_EDIT_BRIDGE = "testQueue_" + RandomStringUtils.randomAlphanumeric(5),
DISCOVERY_GROUP_EDIT = "discoveryGroupBridges_" + RandomStringUtils.randomAlphanumeric(5),
HAL1317_FAIL_MESSAGE = "Probably fails because of https://issues.jboss.org/browse/HAL-1317",
HAL1318_FAIL_MESSAGE = "Probably fails because of https://issues.jboss.org/browse/HAL-1318",
HAL1324_FAIL_MESSAGE = "Probably fails because of https://issues.jboss.org/browse/HAL-1324",
HAL1325_FAIL_MESSAGE = "Probably fails because of https://issues.jboss.org/browse/HAL-1325";
@BeforeClass
public static void setUp() throws Exception {
//add queues
List<String> entriesQueueCreateBridge = Collections.singletonList(QUEUE_CREATE_BRIDGE);
List<String> entriesQueueEditBridge = Collections.singletonList(QUEUE_EDIT_BRIDGE);
client.apply(new AddQueue.Builder(QUEUE_CREATE_BRIDGE).jndiEntries(entriesQueueCreateBridge).build());
client.apply(new AddQueue.Builder(QUEUE_EDIT_BRIDGE).jndiEntries(entriesQueueEditBridge).build());
//add bridges
createBridge(BRIDGE_ADDRESS);
createBridge(BRIDGE_TBR_ADDRESS);
administration.reloadIfRequired();
}
@Page
private MessagingPage page;
@Before
public void before() {
page.viewConnectionSettings("default");
page.switchToBridges();
page.selectInTable(BRIDGE);
}
@After
public void after() throws InterruptedException, TimeoutException, IOException {
administration.reloadIfRequired();
}
@AfterClass
public static void afterClass() throws IOException, OperationException, CommandFailedException, TimeoutException, InterruptedException {
//remove bridges
operations.removeIfExists(BRIDGE_ADDRESS);
operations.removeIfExists(BRIDGE_TBA_ADDRESS);
operations.removeIfExists(BRIDGE_TBA_2_ADDRESS);
operations.removeIfExists(BRIDGE_TBA_3_ADDRESS);
operations.removeIfExists(BRIDGE_TBR_ADDRESS);
//remove queues
client.apply(new RemoveQueue(QUEUE_CREATE_BRIDGE));
client.apply(new RemoveQueue(QUEUE_EDIT_BRIDGE));
}
@Test
public void addBridgeWithDiscoveryGroup() throws Exception {
page.addBridge()
.name(BRIDGE_TBA)
.queueName(QUEUE_CREATE_BRIDGE)
.discoveryGroup("foobar")
.saveAndDismissReloadRequiredWindow();
new ResourceVerifier(BRIDGE_TBA_ADDRESS, client).verifyExists(HAL1317_FAIL_MESSAGE);
}
@Test
public void addBridgeWithStaticConnectors() throws Exception {
page.addBridge()
.name(BRIDGE_TBA_2_ADDRESS.getLastPairValue())
.queueName(QUEUE_CREATE_BRIDGE)
.staticConnectors("foo", "bar", "qux", "qiz")
.saveAndDismissReloadRequiredWindow();
new ResourceVerifier(BRIDGE_TBA_2_ADDRESS, client).verifyExists(HAL1317_FAIL_MESSAGE);
}
@Test
public void addBridgeWithDiscoveryGroupAndForwardAddressDefined() throws Exception {
page.addBridge()
.name(BRIDGE_TBA_3_ADDRESS.getLastPairValue())
.queueName(QUEUE_CREATE_BRIDGE)
.discoveryGroup("foobar")
.forwardAddress("quz")
.saveAndDismissReloadRequiredWindow();
new ResourceVerifier(BRIDGE_TBA_3_ADDRESS, client).verifyExists();
}
@Test
public void updateBridgeFilter() throws Exception {
editTextAndVerify(BRIDGE_ADDRESS, "filter", "testFilter");
}
@Test
public void updateBridgeQueue() throws Exception {
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "queue-name", QUEUE_EDIT_BRIDGE)
.verifyFormSaved()
.verifyAttribute("queue-name", QUEUE_EDIT_BRIDGE, HAL1324_FAIL_MESSAGE);
}
@Test
public void updateBridgeForwardingAddress() throws Exception {
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "forwarding-address", "127.0.0.1")
.verifyFormSaved()
.verifyAttribute("forwarding-address", "127.0.0.1", HAL1324_FAIL_MESSAGE);
}
@Test
public void updateBridgeTransformerClass() throws Exception {
try {
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "transformer-class-name", "clazz")
.verifyFormSaved()
.verifyAttribute("transformer-class-name", "clazz", HAL1324_FAIL_MESSAGE);
} finally {
operations.undefineAttribute(BRIDGE_ADDRESS, "transformer-class-name");
}
}
@Test
public void updateBridgeDiscoveryGroup() throws Exception {
try {
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.edit(ConfigChecker.InputType.TEXT, "static-connectors", "")
.edit(ConfigChecker.InputType.TEXT, "discovery-group", DISCOVERY_GROUP_EDIT)
.andSave()
.verifyFormSaved()
.verifyAttribute("discovery-group", DISCOVERY_GROUP_EDIT, HAL1324_FAIL_MESSAGE);
} finally {
operations.undefineAttribute(BRIDGE_ADDRESS, "discovery-group");
}
}
@Test
public void updateBridgePassword() throws Exception {
page.switchToConnectionManagementTab();
final ModelNodeResult originalModelNodeResult = operations.readAttribute(BRIDGE_ADDRESS, "password");
originalModelNodeResult.assertSuccess();
try {
editTextAndVerify(BRIDGE_ADDRESS, "password", "pwd1");
} finally {
operations.writeAttribute(BRIDGE_ADDRESS, "password", originalModelNodeResult.value());
}
}
@Test
public void updateBridgeRetryInterval() throws Exception {
page.switchToConnectionManagementTab();
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "retry-interval", 1L)
.verifyFormSaved()
.verifyAttribute("retry-interval", 1L, HAL1324_FAIL_MESSAGE);
}
@Test
public void updateBridgeRetryIntervalWrongValue() {
page.switchToConnectionManagementTab();
verifyIfErrorAppears("retry-interval", "-10");
}
@Test
public void updateBridgeReconnectAttempts() throws Exception {
page.switchToConnectionManagementTab();
new ConfigChecker.Builder(client, BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "reconnect-attempts", -1)
.verifyFormSaved(HAL1325_FAIL_MESSAGE)
.verifyAttribute("reconnect-attempts", -1);
}
@Test
public void setCredentialReferenceToClearText() throws Exception {
page.switchToCredentialReference();
new ElytronIntegrationChecker.Builder(client)
.address(BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.build()
.setClearTextCredentialReferenceAndVerify(HAL1318_FAIL_MESSAGE);
}
@Test
public void setCredentialReferenceToCredentialStore() throws Exception {
page.switchToCredentialReference();
new ElytronIntegrationChecker.Builder(client)
.address(BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.build()
.setCredentialStoreCredentialReferenceAndVerify(HAL1318_FAIL_MESSAGE);
}
@Test
public void testIllegalCombinationsForCredentialReference() throws Exception {
page.switchToCredentialReference();
new ElytronIntegrationChecker.Builder(client)
.address(BRIDGE_ADDRESS)
.configFragment(page.getConfigFragment())
.build()
.testIllegalCombinationCredentialReferenceAttributes();
}
@Test
public void removeBridge() throws Exception {
page.remove(BRIDGE_TBR);
new ResourceVerifier(BRIDGE_TBR_ADDRESS, client).verifyDoesNotExist();
}
private static void createBridge(Address address) throws Exception {
operations.add(address, Values.empty()
.andList("static-connectors", CONNECTOR)
.and("queue-name", QUEUE_CREATE_BRIDGE)).assertSuccess();
}
}
|
package org.biojava.nbio.structure.align.gui.jmol;
import org.biojava.nbio.structure.*;
import org.biojava.nbio.structure.align.gui.AlignmentGui;
import org.biojava.nbio.structure.align.gui.DisplayAFP;
import org.biojava.nbio.structure.align.gui.MenuCreator;
import org.biojava.nbio.structure.align.model.AFPChain;
import org.biojava.nbio.structure.align.model.AfpChainWriter;
import org.biojava.nbio.structure.align.util.AlignmentTools;
import org.biojava.nbio.structure.align.util.AtomCache;
import org.biojava.nbio.structure.align.util.ResourceManager;
import org.biojava.nbio.structure.align.util.UserConfiguration;
import org.biojava.nbio.structure.align.webstart.AligUIManager;
import org.biojava.nbio.structure.gui.util.color.ColorUtils;
import org.biojava.nbio.structure.jama.Matrix;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
/**
* A class that provides a simple GUI for Jmol
*
* @author Andreas Prlic
* @since 1.6
*
*/
public class StructureAlignmentJmol extends AbstractAlignmentJmol implements ChangeListener {
private Atom[] ca1;
private Atom[] ca2;
private AFPChain afpChain;
private static final String LIGAND_DISPLAY_SCRIPT = ResourceManager.getResourceManager("ce")
.getString("default.ligand.jmol.script");
public static void main(String[] args) {
try {
UserConfiguration config = new UserConfiguration();
AtomCache cache = new AtomCache(config);
Structure struc = cache.getStructure("5pti");
StructureAlignmentJmol jmolPanel = new StructureAlignmentJmol(null, null, null);
jmolPanel.setStructure(struc);
// send some RASMOL style commands to Jmol
jmolPanel.evalString("select * ; color chain;");
jmolPanel.evalString("select *; spacefill off; wireframe off; backbone 0.4; ");
} catch (Exception e) {
e.printStackTrace();
}
}
public StructureAlignmentJmol() {
// don;t have an afpChain, set it to null...
this(null, null, null);
}
public StructureAlignmentJmol(AFPChain afpChain, Atom[] ca1, Atom[] ca2) {
AligUIManager.setLookAndFeel();
nrOpenWindows++;
jmolPanel = new JmolPanel();
frame = new JFrame();
JMenuBar menu = MenuCreator.initJmolMenu(frame,this, afpChain, null);
frame.setJMenuBar(menu);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.afpChain = afpChain;
this.ca1 = ca1;
this.ca2 = ca2;
frame.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e) {
nrOpenWindows
destroy();
if ( nrOpenWindows > 0) {
frame.dispose();
}
else {
// check if AlignmentGUI is visible..
AlignmentGui gui = AlignmentGui.getInstanceNoVisibilityChange();
if ( gui.isVisible()) {
frame.dispose();
gui.requestFocus();
} else {
System.exit(0);
}
}
}
});
Container contentPane = frame.getContentPane();
Box vBox = Box.createVerticalBox();
//try {
jmolPanel.addMouseMotionListener(this);
jmolPanel.addMouseListener(this);
// } catch (ClassNotFoundException e){
// e.printStackTrace();
// return;
jmolPanel.setPreferredSize(new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT));
vBox.add(jmolPanel);
/// USER SCRIPTING COMMAND
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
field.setText(COMMAND_LINE_HELP);
RasmolCommandListener listener = new RasmolCommandListener(jmolPanel,field) ;
field.addActionListener(listener);
field.addMouseListener(listener);
field.addKeyListener(listener);
vBox.add(field);
/// COMBO BOXES
Box hBox1 = Box.createHorizontalBox();
hBox1.add(Box.createGlue());
String[] styles = new String[] { "Cartoon", "Backbone", "CPK", "Ball and Stick", "Ligands","Ligands and Pocket"};
JComboBox style = new JComboBox(styles);
hBox1.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
hBox1.add(new JLabel("Style"));
hBox1.add(style);
vBox.add(hBox1);
contentPane.add(vBox);
style.addActionListener(jmolPanel);
String[] colorModes = new String[] { "Secondary Structure", "By Chain", "Rainbow", "By Element", "By Amino Acid", "Hydrophobicity" ,"Suggest Domains" , "Show SCOP Domains"};
JComboBox colors = new JComboBox(colorModes);
colors.addActionListener(jmolPanel);
hBox1.add(Box.createGlue());
hBox1.add(new JLabel("Color"));
hBox1.add(colors);
// CHeck boxes
Box hBox2 = Box.createHorizontalBox();
hBox2.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
JButton resetDisplay = new JButton("Reset Display");
resetDisplay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("reset!!");
jmolPanel.executeCmd("restore STATE state_1");
}
});
hBox2.add(resetDisplay);
hBox2.add(Box.createGlue());
JCheckBox toggleSelection = new JCheckBox("Show Selection");
toggleSelection.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED);
if (showSelection){
jmolPanel.executeCmd("set display selected");
} else {
jmolPanel.executeCmd("set display off");
}
}
}
);
hBox2.add(toggleSelection);
hBox2.add(Box.createGlue());
vBox.add(hBox2);
// ZOOM SLIDER
Box hBox3 = Box.createHorizontalBox();
hBox3.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
JLabel sliderLabel = new JLabel("Zoom");
hBox3.add(Box.createGlue());
hBox3.add(sliderLabel);
JSlider zoomSlider = new JSlider(JSlider.HORIZONTAL,0,500,100);
zoomSlider.addChangeListener(this);
zoomSlider.setMajorTickSpacing(100);
zoomSlider.setPaintTicks(true);
Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
labelTable.put(new Integer(0),new JLabel("0%"));
labelTable.put(new Integer(100),new JLabel("100%"));
labelTable.put(new Integer(200),new JLabel("200%"));
labelTable.put(new Integer(300),new JLabel("300%"));
labelTable.put(new Integer(400),new JLabel("400%"));
labelTable.put(new Integer(500),new JLabel("500%"));
zoomSlider.setLabelTable(labelTable);
zoomSlider.setPaintLabels(true);
hBox3.add(zoomSlider);
hBox3.add(Box.createGlue());
// SPIN CHECKBOX
JCheckBox toggleSpin = new JCheckBox("Spin");
toggleSpin.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean spinOn = (e.getStateChange() == ItemEvent.SELECTED);
if (spinOn){
jmolPanel.executeCmd("spin ON");
} else {
jmolPanel.executeCmd("spin OFF");
}
}
}
);
hBox3.add(toggleSpin);
hBox3.add(Box.createGlue());
vBox.add(hBox3);
// STATUS DISPLAY
Box hBox = Box.createHorizontalBox();
status = new JTextField();
status.setBackground(Color.white);
status.setEditable(false);
status.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
status.setPreferredSize(new Dimension(DEFAULT_WIDTH / 2,30));
status.setMinimumSize(new Dimension(DEFAULT_WIDTH / 2,30));
hBox.add(status);
text = new JTextField();
text.setBackground(Color.white);
text.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
text.setPreferredSize(new Dimension(DEFAULT_WIDTH / 2,30));
text.setMinimumSize(new Dimension(DEFAULT_WIDTH / 2,30));
text.setText("Display of Atom info");
text.setEditable(false);
hBox.add(text);
vBox.add(hBox);
contentPane.add(vBox);
MyJmolStatusListener li = (MyJmolStatusListener) jmolPanel.getStatusListener();
li.setTextField(status);
frame.pack();
frame.setVisible(true);
// init coordinates
initCoords();
resetDisplay();
}
@Override
protected void initCoords() {
try {
if (ca1 == null || ca2 == null) {
if (structure != null)
setStructure(structure);
else {
// System.err.println("could not find anything to
// display!");
return;
}
}
Structure artificial = AlignmentTools.getAlignedStructure(ca1, ca2);
PDBHeader header = new PDBHeader();
String title = afpChain.getAlgorithmName() + " V." + afpChain.getVersion() + " : " + afpChain.getName1()
+ " vs. " + afpChain.getName2();
header.setTitle(title);
artificial.setPDBHeader(header);
setStructure(artificial);
} catch (StructureException e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
super.destroy();
afpChain = null;
ca1 = null;
ca2 = null;
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals(MenuCreator.TEXT_ONLY)) {
if (afpChain == null) {
System.err.println("Currently not viewing an alignment!");
return;
}
// Clone the AFPChain to not override the FatCat numbers in alnsymb
AFPChain textAFP = (AFPChain) afpChain.clone();
String result = AfpChainWriter.toWebSiteDisplay(textAFP, ca1, ca2);
DisplayAFP.showAlignmentImage(afpChain, result);
} else if (cmd.equals(MenuCreator.PAIRS_ONLY)) {
if (afpChain == null) {
System.err.println("Currently not viewing an alignment!");
return;
}
String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2);
DisplayAFP.showAlignmentImage(afpChain, result);
} else if (cmd.equals(MenuCreator.ALIGNMENT_PANEL)) {
if (afpChain == null) {
System.err.println("Currently not viewing an alignment!");
return;
}
try {
DisplayAFP.showAlignmentPanel(afpChain, ca1, ca2, this);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
} else if (cmd.equals(MenuCreator.FATCAT_TEXT)) {
if (afpChain == null) {
System.err.println("Currently not viewing an alignment!");
return;
}
String result = afpChain.toFatcat(ca1, ca2);
result += AFPChain.newline;
result += afpChain.toRotMat();
DisplayAFP.showAlignmentImage(afpChain, result);
}
}
public static String getJmolString(AFPChain afpChain, Atom[] ca1, Atom[] ca2) {
if (afpChain.getBlockNum() > 1) {
return getMultiBlockJmolScript(afpChain, ca1, ca2);
}
StringBuffer j = new StringBuffer();
j.append(DEFAULT_SCRIPT);
// now color the equivalent residues ...
StringBuffer sel = new StringBuffer();
List<String> pdb1 = DisplayAFP.getPDBresnum(0, afpChain, ca1);
sel.append("select ");
int pos = 0;
for (String res : pdb1) {
if (pos > 0)
sel.append(",");
pos++;
sel.append(res);
sel.append("/1");
}
if (pos == 0)
sel.append("none");
sel.append(";");
sel.append("backbone 0.6 ; color orange;");
sel.append("select */2; color lightgrey; model 2; ");
// jmol.evalString("select */2; color lightgrey; model 2; ");
List<String> pdb2 = DisplayAFP.getPDBresnum(1, afpChain, ca2);
sel.append("select ");
pos = 0;
for (String res : pdb2) {
if (pos > 0)
sel.append(",");
pos++;
sel.append(res);
sel.append("/2");
}
if (pos == 0)
sel.append("none");
sel.append("; backbone 0.6 ; color cyan;");
// System.out.println(sel);
j.append(sel);
// now show both models again.
j.append("model 0; ");
j.append(LIGAND_DISPLAY_SCRIPT);
// color [object] cpk , set defaultColors Jmol , set defaultColors
// Rasmol
// and now select the aligned residues...
StringBuffer buf = new StringBuffer("select ");
int count = 0;
for (String res : pdb1) {
if (count > 0)
buf.append(",");
buf.append(res);
buf.append("/1");
count++;
}
for (String res : pdb2) {
buf.append(",");
buf.append(res);
buf.append("/2");
}
// buf.append("; set display selected;");
j.append(buf);
return j.toString();
}
public static String getJmolScript4Block(AFPChain afpChain, Atom[] ca1, Atom[] ca2, int blockNr) {
int blockNum = afpChain.getBlockNum();
if (blockNr >= blockNum)
return DEFAULT_SCRIPT;
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
if (optLen == null)
return DEFAULT_SCRIPT;
StringWriter jmol = new StringWriter();
jmol.append(DEFAULT_SCRIPT);
jmol.append("select */2; color lightgrey; model 2; ");
printJmolScript4Block(ca1, ca2, blockNum, optLen, optAln, jmol, blockNr);
jmol.append("model 0; ");
jmol.append(LIGAND_DISPLAY_SCRIPT);
// System.out.println(jmol);
return jmol.toString();
}
private static String getMultiBlockJmolScript(AFPChain afpChain, Atom[] ca1, Atom[] ca2) {
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
if (optLen == null)
return DEFAULT_SCRIPT;
StringWriter jmol = new StringWriter();
jmol.append(DEFAULT_SCRIPT);
jmol.append("select */2; color lightgrey; model 2; ");
for (int bk = 0; bk < blockNum; bk++) {
printJmolScript4Block(ca1, ca2, blockNum, optLen, optAln, jmol, bk);
}
jmol.append("model 0; ");
jmol.append(LIGAND_DISPLAY_SCRIPT);
// System.out.println(jmol);
return jmol.toString();
}
private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, int[] optLen, int[][][] optAln,
StringWriter jmol, int bk) {
// the block nr determines the color...
int colorPos = bk;
Color c1;
Color c2;
// If the colors for the block are specified in AFPChain use them,
// otherwise the default ones are calculated
if (colorPos > ColorUtils.colorWheel.length) {
colorPos = ColorUtils.colorWheel.length % colorPos;
}
Color end1 = ColorUtils.rotateHue(ColorUtils.orange, (1.0f / 24.0f) * blockNum);
Color end2 = ColorUtils.rotateHue(ColorUtils.cyan, (1.0f / 24.0f) * (blockNum + 1));
c1 = ColorUtils.getIntermediate(ColorUtils.orange, end1, blockNum, bk);
c2 = ColorUtils.getIntermediate(ColorUtils.cyan, end2, blockNum, bk);
List<String> pdb1 = new ArrayList<String>();
List<String> pdb2 = new ArrayList<String>();
for (int i = 0; i < optLen[bk]; i++) {
int pos1 = optAln[bk][0][i];
pdb1.add(JmolTools.getPdbInfo(ca1[pos1]));
int pos2 = optAln[bk][1][i];
pdb2.add(JmolTools.getPdbInfo(ca2[pos2]));
}
// and now select the aligned residues...
StringBuffer buf = new StringBuffer("select ");
int count = 0;
for (String res : pdb1) {
if (count > 0)
buf.append(",");
buf.append(res);
buf.append("/1");
count++;
}
buf.append("; backbone 0.6 ; color [" + c1.getRed() + "," + c1.getGreen() + "," + c1.getBlue() + "]; select ");
count = 0;
for (String res : pdb2) {
if (count > 0)
buf.append(",");
buf.append(res);
buf.append("/2");
count++;
}
// buf.append("; set display selected;");
buf.append("; backbone 0.6 ; color [" + c2.getRed() + "," + c2.getGreen() + "," + c2.getBlue() + "];");
// now color this block:
jmol.append(buf);
}
@Override
public void resetDisplay() {
if (afpChain != null && ca1 != null && ca2 != null) {
String script = getJmolString(afpChain, ca1, ca2);
// System.out.println(script);
evalString(script);
jmolPanel.evalString("save STATE state_1");
}
}
@Override
public List<Matrix> getDistanceMatrices() {
if (afpChain == null)
return null;
else
return Arrays.asList(afpChain.getDisTable1(), afpChain.getDisTable2());
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int zoomValue = (int) source.getValue();
jmolPanel.executeCmd("zoom " + zoomValue);
}
}
}
|
package gov.nih.nci.cananolab.util;
import org.hibernate.criterion.MatchMode;
/**
* For use in searching objects by the given text through Hibernate MatchMode.
*
* @author pansu
*/
public class TextMatchMode {
private String originalText;
private String updatedText;
private MatchMode matchMode = MatchMode.EXACT;
public TextMatchMode(String originalText) {
this.originalText = originalText;
updatedText = originalText;
if (originalText.equals("*")){
matchMode = MatchMode.ANYWHERE;
updatedText = "";
}else if (originalText.startsWith("*") && originalText.endsWith("*")) {
matchMode = MatchMode.ANYWHERE;
updatedText = originalText.substring(1, originalText.length() - 1);
} else if (originalText.startsWith("*")) {
matchMode = MatchMode.END;
updatedText = originalText.substring(1, originalText.length());
} else if (originalText.endsWith("*")) {
matchMode = MatchMode.START;
updatedText = originalText.substring(0, originalText.length() - 1);
}
}
public MatchMode getMatchMode() {
return matchMode;
}
public String getOriginalText() {
return originalText;
}
public String getUpdatedText() {
return updatedText;
}
}
|
package info.elexis.server.core.connector.elexis.services;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.rgw.tools.TimeTool;
import info.elexis.server.core.connector.elexis.internal.ElexisEntityManager;
import info.elexis.server.core.connector.elexis.jpa.model.annotated.Config;
import info.elexis.server.core.connector.elexis.jpa.model.annotated.Config_;
public class ConfigService {
public static final String LIST_SEPARATOR = ",";
private Logger log = LoggerFactory.getLogger(ConfigService.class);
public static ConfigService INSTANCE = InstanceHolder.INSTANCE;
private static final class InstanceHolder {
static final ConfigService INSTANCE = new ConfigService();
}
private ConfigService() {
new Config(); // TODO refactor make sure jpa bundle is loaded before
}
/**
* Get a stored value for a given key, or return the value provided as
* default
*
* @param key
* @param defValue
* default value if not set
* @return
*/
public String get(String key, String defValue) {
EntityManager em = ElexisEntityManager.createEntityManager();
try {
Config val = em.find(Config.class, key);
if (val != null) {
return val.getWert();
} else {
return defValue;
}
} finally {
em.close();
}
}
/**
* Get a stored value for a given key as boolean, or return the value
* provided as default
*
* @param key
* @param b
* @return
*/
public boolean get(String key, boolean defValue) {
String string = get(key, Boolean.toString(defValue));
return Boolean.valueOf(string);
}
/**
* Retrieve a value as a set.
*
* @param key
* @return
*/
public Set<String> getAsSet(String key) {
String val = get(key, null);
if (val == null) {
return Collections.emptySet();
}
String[] split = val.split(LIST_SEPARATOR);
return Arrays.asList(split).stream().collect(Collectors.toSet());
}
/**
* Returns a stored value as {@link LocalDate}
*
* @param key
* @return the {@link LocalDate} or <code>null</code>
*/
public LocalDate getAsDate(String key) {
String value = get(key, null);
if (value != null) {
TimeTool tt = new TimeTool(value);
return tt.toZonedDateTime().toLocalDate();
}
return null;
}
/**
* Get all nodes starting with nodePrefix
*
* @param nodePrefix
* @return
*/
public List<Config> getNodes(String nodePrefix) {
JPAQuery<Config> query = new JPAQuery<Config>(Config.class);
query.add(Config_.param, JPAQuery.QUERY.LIKE, nodePrefix + "%");
return query.execute();
}
/**
* Set a value for a given key
*
* @param key
* @param value
* @return <code>true</code> if the value was successfully set
*/
public boolean set(String key, String value) {
EntityManager em = ElexisEntityManager.createEntityManager();
try {
Config val = em.find(Config.class, key);
if (val != null && val.getWert() != null && val.getWert().equalsIgnoreCase(value)) {
return true;
}
em.getTransaction().begin();
if (val == null) {
val = new Config();
val.setParam(key);
em.persist(val);
}
em.lock(val, LockModeType.PESSIMISTIC_WRITE);
val.setWert(value);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Error on setting config ", e);
return false;
} finally {
em.close();
}
return true;
}
/**
* Store a set of values to a configuration key
*
* @param key
* @param values
* @return <code>true</code> if the values were successfully set
*/
public boolean setAsSet(String key, Set<String> values) {
String flattenedValue = values.stream().map(o -> o.toString()).reduce((u, t) -> u + LIST_SEPARATOR + t).get();
return set(key, flattenedValue);
}
public void remove(String key) {
EntityManager em = ElexisEntityManager.createEntityManager();
try {
Config val = em.find(Config.class, key);
if (val == null) {
return;
}
em.getTransaction().begin();
em.remove(val);
em.getTransaction().commit();
} finally {
em.close();
}
}
/**
* Assert that a specific value is part of the set stored in key
*
* @param key
* @param value
*/
public void assertPropertyInSet(String key, String value) {
Set<String> propertySet = getAsSet(key);
Set<String> valueSet = new HashSet<String>(propertySet);
valueSet.add(value);
setAsSet(key, valueSet);
}
}
|
package gov.nih.nci.cabig.caaers.web.admin;
import gov.nih.nci.cabig.caaers.domain.LocalResearchStaff;
import gov.nih.nci.cabig.caaers.domain.RemoteResearchStaff;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.repository.ResearchStaffRepository;
import gov.nih.nci.cabig.caaers.web.WebTestCase;
import java.util.ArrayList;
import java.util.List;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
public class EditResearchStaffControllerTest extends WebTestCase {
private EditResearchStaffController controller;
@Override
protected void setUp() throws Exception {
super.setUp();
controller = new EditResearchStaffController();
controller.setResearchStaffRepository(new ResearchStaffRepository(){
public void save(final ResearchStaff researchStaff, String changeURL) {
}
public void convertToRemote(ResearchStaff localResearchStaff, ResearchStaff remoteResearchStaff){
}
public void evict(ResearchStaff researchStaff){
}
public ResearchStaff getById(final int id) {
return new LocalResearchStaff();
}
public List<ResearchStaff> getRemoteResearchStaff(final ResearchStaff researchStaff){
List<ResearchStaff> rsList = new ArrayList<ResearchStaff>();
ResearchStaff r1 = new RemoteResearchStaff();
r1.setNciIdentifier("1");
ResearchStaff r2 = new RemoteResearchStaff();
r2.setNciIdentifier("2");
rsList.add(r1);
rsList.add(r2);
return rsList;
}
});
}
public void test(){
//@TODO
//Command object was changed from ResearchStaff to ResearchStaffCommand. This TestCase was not modified.
//Have to revist the tests commented below.
}
/**
*
* @throws Exception
*/
// public void testOnBindAndValidateWithResults() throws Exception {
// request.setMethod("POST");
// request.setParameter("_action", "syncResearchStaff");
// ResearchStaff command = new LocalResearchStaff();
// BindException errors = new BindException(command, "command");
// controller.onBindAndValidate(request, command, errors, 1);
// assertNotNull("List should not be Null", command.getExternalResearchStaff());
// //TODO: Changed thse values to 0s from 2,1 .. need to check with monish - By Srini
// assertEquals(0, command.getExternalResearchStaff().size());
// assertEquals(0, errors.getErrorCount());
// public void testOnBindAndValidateWithOutResults() throws Exception {
// controller.setResearchStaffRepository(new ResearchStaffRepository(){
// public List<ResearchStaff> getRemoteResearchStaff(final ResearchStaff researchStaff){
// List<ResearchStaff> rsList = new ArrayList<ResearchStaff>();
// return rsList;
// request.setMethod("POST");
// request.setParameter("_action", "syncResearchStaff");
// ResearchStaff command = new LocalResearchStaff();
// BindException errors = new BindException(command, "command");
// controller.onBindAndValidate(request, command, errors, 1);
// assertEquals(0, command.getExternalResearchStaff().size());
}
|
package gov.nih.nci.caadapter.common.csv.data.impl;
import gov.nih.nci.caadapter.common.Log;
import gov.nih.nci.caadapter.common.Message;
import gov.nih.nci.caadapter.common.MessageResources;
import gov.nih.nci.caadapter.common.csv.data.*;
import gov.nih.nci.caadapter.common.csv.meta.*;
import gov.nih.nci.caadapter.common.validation.ValidatorResult;
import gov.nih.nci.caadapter.common.validation.ValidatorResults;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class CSVSegmentedFileExtension extends CSVSegmentedFileImpl {
private CSVMeta csvMeta;
private ValidatorResults transformationResults;
public void insertCsvField(String csvFieldKey, String csvValue)
{
// System.out.println("CSVSegmentedFileExtension.insertCsvField().. field:"+csvFieldKey);
List parentSegs=findParentSegment(csvFieldKey);
// System.out.println("CSVSegmentedFileExtension.insertCsvField()...parent:"+parentSegs);
if (parentSegs.size()==0)
{
Message msg = MessageResources.getMessage("HL7TOCSV1", new Object[]{csvFieldKey,csvValue});
// transformationResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.ERROR, msg));
Log.logError(this, msg);
return;
}
String fieldName=csvFieldKey.substring(csvFieldKey.lastIndexOf(".")+1);
boolean isNewSegmentRequired=true;
for (Object parentObj:parentSegs)
{
CSVSegmentExtension csvExt=(CSVSegmentExtension)parentObj;
if (setNewFieldValue(csvExt, fieldName, csvValue))
{
isNewSegmentRequired=false;
break;
}
}
//new parent segment is required, create one and set field value
if (isNewSegmentRequired)
{
CSVSegmentExtension valueSetParentSeg=(CSVSegmentExtension)parentSegs.get(0);
CSVSegment grandParentSeg=valueSetParentSeg.getParentSegment();
CSVSegment newParent=createChildSegment(grandParentSeg, valueSetParentSeg.getName());
setNewFieldValue(newParent, fieldName, csvValue);
}
}
/**
* Set new value with CSVMeta
* @param userCsvMeta
*/
public void setCsvMeta(CSVMeta userCsvMeta) {
csvMeta = userCsvMeta;
CSVSegmentMeta rootSegmentMeta = csvMeta.getRootSegment();
CSVSegment rootSeg=recursivlyAddEmptySegmentRecords(rootSegmentMeta);
addLogicalRecord(rootSeg);
}
public void setBuildCSVResult(ValidatorResults validators)
{
transformationResults=validators;
}
public ValidatorResults getBuildCSVResults() {
return transformationResults;
}
/**
* Find all parent segments given the fieldName. There may be more than one
* parent segment found, but only zero or one of the parent with the value not
* not being set for the field.
* @param csvFieldKey
* @return
*/
private List findParentSegment(String csvFieldKey)
{
String parentKey=csvFieldKey.substring(0, csvFieldKey.lastIndexOf("."));
CSVSegment rootSeg =getLogicalRecords().get(0);
StringTokenizer stoken=new StringTokenizer(parentKey,".");
//skip the root name
stoken.nextToken();
List<CSVSegmentExtension> parentSegs=new ArrayList<CSVSegmentExtension>();
parentSegs.add((CSVSegmentExtension)rootSeg);
while (stoken.hasMoreElements())
{
String childSegName=stoken.nextToken();
if (parentSegs.isEmpty())
break;
else
{
List childSegs=new ArrayList<CSVSegmentExtension>();
for (CSVSegmentExtension parentSeg:parentSegs)
{
List<CSVSegment> oneChildList=((CSVSegmentExtension)parentSeg).getChildSegmentsByName(childSegName);
//findOrCreateChildSegment(parentSeg, childSegName);
for (CSVSegment oneChildSeg:oneChildList)
childSegs.add((CSVSegmentExtension)oneChildSeg);
}
parentSegs=childSegs;
}
}
return parentSegs;
}
/**
* Create a new CSVSegment and attached it with its parent segment
* @param parentSeg
* @param childSegName
* @return
*/
private CSVSegment createChildSegment (CSVSegment parentSeg, String childSegName)
{
CSVSegmentMeta newChildMeta=null;
if (parentSeg==null)
{
//create root segement
newChildMeta=this.csvMeta.getRootSegment();
}
else
{
for (CSVSegmentMeta childMeta:((CSVSegmentMeta)parentSeg.getMetaObject()).getChildSegments())
{
if (childMeta.getName().equals(childSegName))
newChildMeta=childMeta;
}
}
CSVSegment newSeg=null;
if (newChildMeta!=null)
{
newSeg=initializeEmptyCsvSegment(newChildMeta);
if (parentSeg!=null)
((CSVSegmentExtension)parentSeg).attachDuplicateChildSegment(newSeg);
else
getLogicalRecords().add(newSeg); //add to root
}
return newSeg;
}
/**
* Create an empty CSVSegment given it metadata
* @param meta
* @param transformationResults
* @return
*/
private CSVSegment initializeEmptyCsvSegment(CSVSegmentMeta meta) {
CSVSegmentImpl segment = new CSVSegmentExtension(meta);
segment.setXmlPath(meta.getXmlPath());
Message msg = MessageResources.getMessage("HL7TOCSV0", new Object[]{"initialize new segment "+meta.getXmlPath()});
transformationResults.addValidatorResult(new ValidatorResult(ValidatorResult.Level.INFO, msg));
Log.logInfo(this, msg);
//setup the fields.
ArrayList<CSVField> fields = new ArrayList<CSVField>();
List<CSVFieldMeta> fieldMeta = meta.getFields();
for (int i = 0; i < fieldMeta.size(); i++) {
CSVFieldMeta csvFieldMeta = fieldMeta.get(i);
CSVFieldImpl field = new CSVFieldExtension(csvFieldMeta);
field.setColumn(csvFieldMeta.getColumn());
field.setXmlPath(csvFieldMeta.getXmlPath());
field.setValue("");
fields.add(field);
}
segment.setFields(fields);
return segment;
}
private CSVSegment recursivlyAddEmptySegmentRecords(CSVSegmentMeta segMeta )
{
CSVSegment segment=initializeEmptyCsvSegment(segMeta);
for (CSVSegmentMeta childSegmentMeta:segMeta.getChildSegments())
{
CSVSegment childSeg=recursivlyAddEmptySegmentRecords( childSegmentMeta);
childSeg.setParentSegment(segment);
segment.addChildSegment(childSeg);
}
return segment;
}
/**
* Find the field from parent, set the it with new value if not being set yet; otherwise
* require a new parent segment
* @param parentSeg
* @param fieldName
* @param fieldValue
* @return
*/
private boolean setNewFieldValue(CSVSegment parentSeg, String fieldName, String fieldValue)
{
System.out.println("CSVSegmentedFileExtension.setNewFieldValue()..parent:"+parentSeg +"..field:"+fieldName+"..value:"+fieldValue);
boolean rtnValue=false;
CSVSegmentExtension segExt=(CSVSegmentExtension)parentSeg;
if (parentSeg==null)
return rtnValue;
CSVFieldExtension fieldExt=(CSVFieldExtension)segExt.getFieldByName(fieldName);
if (fieldExt!=null&&!fieldExt.isValueSet())
{
fieldExt.setValue(fieldValue);
fieldExt.setValueSetFlag(true);
rtnValue=true;
}
return rtnValue;
}
/**
* Express the CSVSegmentFile as string
*/
public String toString()
{
return outputCSVString();
}
/**
* Output the CSVSegmentFile as string
*/
private String outputCSVString()
{
StringBuffer sb=new StringBuffer();
for (CSVSegment csvSeg:this.getLogicalRecords())
sb.append(recursivelyConvertSegmentToCSVString(csvSeg));
return sb.toString();
}
private String recursivelyConvertSegmentToCSVString(CSVSegment csvSeg)
{
StringBuffer sb=new StringBuffer();
sb.append(csvSeg.getName());
for (CSVField csvField:csvSeg.getFields())
{
sb.append(","+csvField.getValue());
}
sb.append("\n");
List<CSVSegment> childList=csvSeg.getChildSegments();
if (childList.size()>0)
{
for (CSVSegment childSeg:childList)
sb.append(recursivelyConvertSegmentToCSVString(childSeg));
sb.append("\n");
}
return sb.toString();
}
}
|
// Nenya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.resource;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.IndexColorModel;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.WritableRaster;
import org.apache.commons.io.IOUtils;
/**
* Provides routines for writing and reading uncompressed 8-bit color
* mapped images in a manner that is extremely fast and generates a
* minimal amount of garbage during the loading process.
*/
public class FastImageIO
{
/**
* A suffix for use when storing raw images in bundles or on the file system.
*/
public static final String FILE_SUFFIX = ".raw";
/**
* Returns true if the supplied image is of a format that is supported by the fast image I/O
* services, false if not.
*/
public static boolean canWrite (BufferedImage image)
{
return (image.getColorModel() instanceof IndexColorModel) &&
(image.getRaster().getDataBuffer() instanceof DataBufferByte);
}
/**
* Writes the supplied image to the supplied output stream.
*
* @exception IOException thrown if an error occurs writing to the output stream.
*/
public static void write (BufferedImage image, OutputStream out)
throws IOException
{
DataOutputStream dout = new DataOutputStream(out);
// write the image dimensions
int width = image.getWidth(), height = image.getHeight();
dout.writeInt(width);
dout.writeInt(height);
// write the color model information
IndexColorModel cmodel = (IndexColorModel)image.getColorModel();
int tpixel = cmodel.getTransparentPixel();
dout.writeInt(tpixel);
int msize = cmodel.getMapSize();
int[] map = new int[msize];
cmodel.getRGBs(map);
dout.writeInt(msize);
for (int element : map) {
dout.writeInt(element);
}
// write the raster data
DataBufferByte dbuf = (DataBufferByte)image.getRaster().getDataBuffer();
byte[] data = dbuf.getData();
if (data.length != width * height) {
String errmsg = "Raster data not same size as image! [" +
width + "x" + height + " != " + data.length + "]";
throw new IllegalStateException(errmsg);
}
dout.write(data);
dout.flush();
}
/**
* Reads an image from the supplied file (which must contain an image previously written via a
* call to {@link #write}).
*
* @exception IOException thrown if an error occurs reading from the file.
*/
public static BufferedImage read (File file)
throws IOException
{
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel fchan = raf.getChannel();
try {
MappedByteBuffer mbuf = fchan.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
return read(mbuf);
} finally {
fchan.close();
raf.close();
}
}
/**
* Reads an image from the supplied input stream (which must return the image format previously
* written via a call to {@link #write}).
*
* @exception IOException thrown if an error occurs reading from the file.
*/
public static BufferedImage read (InputStream in)
throws IOException
{
return read(ByteBuffer.wrap(IOUtils.toByteArray(in)));
}
/**
* Reads an image from the supplied byte buffer (which must return the image format previously
* written via a call to {@link #write}).
*
* @exception IOException thrown if an error occurs reading from the file.
*/
public static BufferedImage read (ByteBuffer byteBuffer)
throws IOException
{
// read in our integer fields
IntBuffer ibuf = byteBuffer.asIntBuffer();
int width = ibuf.get();
int height = ibuf.get();
/* int tpixel = */ ibuf.get();
int msize = ibuf.get();
if (width > Short.MAX_VALUE || width < 0 || height > Short.MAX_VALUE || height < 0) {
throw new IOException("Bogus image size " + width + "x" + height);
}
IndexColorModel cmodel;
synchronized (_origin) { // any old object will do
// make sure our colormap array is big enough
if (_cmap == null || _cmap.length < msize) {
_cmap = new int[msize];
}
// read in the data and create our colormap
ibuf.get(_cmap, 0, msize);
cmodel = new IndexColorModel(
8, msize, _cmap, 0, DataBuffer.TYPE_BYTE, null);
}
// advance the byte buffer accordingly
byteBuffer.position(ibuf.position() * 4);
// read in the image data itself
byte[] data = new byte[width*height];
byteBuffer.get(data);
// create the image from our component parts
DataBuffer dbuf = new DataBufferByte(data, data.length, 0);
int[] offsets = new int[] { 0 };
PixelInterleavedSampleModel smodel =
new PixelInterleavedSampleModel(
DataBuffer.TYPE_BYTE, width, height, 1, width, offsets);
WritableRaster raster = WritableRaster.createWritableRaster(smodel, dbuf, _origin);
return new BufferedImage(cmodel, raster, false, null);
}
/** Used when loading our color map. */
protected static int[] _cmap;
/** Used when creating our writable raster. */
protected static Point _origin = new Point(0, 0);
}
|
package com.apress.spring.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class ResourceSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
|
package net.sf.picard.util;
import net.sf.picard.PicardException;
import net.sf.picard.filter.*;
import net.sf.samtools.*;
import net.sf.samtools.util.CloseableIterator;
import java.util.*;
/**
* Iterator that traverses a SAM File, accumulating information on a per-locus basis.
* Optionally takes a target interval list, in which case the loci returned are the ones covered by
* the interval list. If no target interval list, whatever loci are covered by the input reads are returned.
* By default duplicate reads and non-primary alignments are filtered out. Filtering may be changed
* via setSamFilters().
*
* @author alecw@broadinstitute.org
*/
public class SamLocusIterator implements Iterable<SamLocusIterator.LocusInfo>, CloseableIterator<SamLocusIterator.LocusInfo> {
private static final Log LOG = Log.getInstance(SamLocusIterator.class);
/**
* A SAMRecord plus the zero-based offset in the read corresponding to the position in LocusInfo
*/
public static class RecordAndOffset {
private final SAMRecord record;
private final int offset;
public RecordAndOffset(final SAMRecord record, final int offset) {
this.offset = offset;
this.record = record;
}
/**
* Zero-based offset into the read corresonding to the current position in LocusInfo
*/
public int getOffset() {
return offset;
}
public SAMRecord getRecord() {
return record;
}
public byte getReadBase() {
return record.getReadBases()[offset];
}
public byte getBaseQuality() {
return record.getBaseQualities()[offset];
}
}
/**
* The unit of iteration. Holds the locus, plus a ReadAndOffset for each read that overlaps the locus
*/
public static class LocusInfo implements Locus {
private final SAMSequenceRecord referenceSequence;
private final int position;
private final List<RecordAndOffset> recordAndOffsets = new ArrayList<RecordAndOffset>(100);
LocusInfo(final SAMSequenceRecord referenceSequence, final int position) {
this.referenceSequence = referenceSequence;
this.position = position;
}
/**
* Accumulate info for one read at the locus.
*/
public void add(final SAMRecord read, final int position) {
recordAndOffsets.add(new RecordAndOffset(read, position));
}
public int getSequenceIndex() { return referenceSequence.getSequenceIndex(); }
/**
* @return 1-based reference position
*/
public int getPosition() { return position; }
public List<RecordAndOffset> getRecordAndPositions() {
return Collections.unmodifiableList(recordAndOffsets);
}
public String getSequenceName() { return referenceSequence.getSequenceName(); }
@Override
public String toString() {
return referenceSequence.getSequenceName() + ":" + position;
}
public int getSequenceLength(){return referenceSequence.getSequenceLength();}
}
private final SAMFileReader samReader;
private final ReferenceSequenceMask referenceSequenceMask;
private PeekableIterator<SAMRecord> samIterator;
private List<SamRecordFilter> samFilters = Arrays.asList(new SecondaryOrSupplementaryFilter(),
new DuplicateReadFilter());
private final List<Interval> intervals;
private final boolean useIndex;
// LocusInfos on this list are ready to be returned by iterator. All reads that overlap
// the locus have been accumulated before the LocusInfo is moved into this list.
private final LinkedList<LocusInfo> complete = new LinkedList<LocusInfo>();
// LocusInfos for which accumulation is in progress
private final LinkedList<LocusInfo> accumulator = new LinkedList<LocusInfo>();
private int qualityScoreCutoff = Integer.MIN_VALUE;
private int mappingQualityScoreCutoff = Integer.MIN_VALUE;
private boolean includeNonPfReads = true;
/**
* If true, emit a LocusInfo for every locus in the target map, or if no target map,
* emit a LocusInfo for every locus in the reference sequence.
* If false, emit a LocusInfo only if a locus has coverage.
*/
private boolean emitUncoveredLoci = true;
// When there is a target mask, these members remember the last locus for which a LocusInfo has been
// returned, so that any uncovered locus in the target mask can be covered by a 0-coverage LocusInfo
private int lastReferenceSequence = 0;
private int lastPosition = 0;
// Set to true when past all aligned reads in input SAM file
private boolean finishedAlignedReads = false;
private final LocusComparator<Locus> locusComparator = new LocusComparator<Locus>();
/**
* Prepare to iterate through the given SAM records, skipping non-primary alignments. Do not use
* BAM index even if available.
*/
public SamLocusIterator(final SAMFileReader samReader) {
this(samReader, null);
}
/**
* Prepare to iterate through the given SAM records, skipping non-primary alignments. Do not use
* BAM index even if available.
*
* @param intervalList Either the list of desired intervals, or null. Note that if an intervalList is
* passed in that is not coordinate sorted, it will eventually be coordinated sorted by this class.
*/
public SamLocusIterator(final SAMFileReader samReader, final IntervalList intervalList) {
this(samReader, intervalList, samReader.hasIndex());
}
/**
* Prepare to iterate through the given SAM records, skipping non-primary alignments
*
* @param samReader must be coordinate sorted
* @param intervalList Either the list of desired intervals, or null. Note that if an intervalList is
* passed in that is not coordinate sorted, it will eventually be coordinated sorted by this class.
* @param useIndex If true, do indexed lookup to improve performance. Not relevant if intervalList == null.
* It is no longer the case the useIndex==true can make performance worse. It should always perform at least
* as well as useIndex==false, and generally will be much faster.
*/
public SamLocusIterator(final SAMFileReader samReader, final IntervalList intervalList, final boolean useIndex) {
if (samReader.getFileHeader().getSortOrder() == null || samReader.getFileHeader().getSortOrder() == SAMFileHeader.SortOrder.unsorted) {
LOG.warn("SamLocusIterator constructed with samReader that has SortOrder == unsorted. ", "" +
"Assuming SAM is coordinate sorted, but exceptions may occur if it is not.");
} else if (samReader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
throw new PicardException("SamLocusIterator cannot operate on a SAM file that is not coordinate sorted.");
}
this.samReader = samReader;
this.useIndex = useIndex;
if (intervalList != null) {
intervals = intervalList.getUniqueIntervals();
this.referenceSequenceMask = new IntervalListReferenceSequenceMask(intervalList);
} else {
intervals = null;
this.referenceSequenceMask = new WholeGenomeReferenceSequenceMask(samReader.getFileHeader());
}
}
public Iterator<LocusInfo> iterator() {
if (samIterator != null) {
throw new IllegalStateException("Cannot call iterator() more than once on SamLocusIterator");
}
CloseableIterator<SAMRecord> tempIterator;
if (intervals != null) {
tempIterator = new SamRecordIntervalIteratorFactory().makeSamRecordIntervalIterator(samReader, intervals, useIndex);
} else {
tempIterator = samReader.iterator();
}
if (samFilters != null) {
tempIterator = new FilteringIterator(tempIterator, new AggregateFilter(samFilters));
}
samIterator = new PeekableIterator<SAMRecord>(tempIterator);
return this;
}
public void close() {
this.samIterator.close();
}
private boolean samHasMore() {
return !finishedAlignedReads && (samIterator.peek() != null);
}
/**
* @return true if there are more aligned reads in the SAM file, LocusInfos in some stage of accumulation,
* or loci in the target mask that have yet to be covered.
*/
public boolean hasNext() {
if (this.samIterator == null) {
iterator();
}
while (complete.isEmpty() && ((!accumulator.isEmpty()) || samHasMore() || hasRemainingMaskBases())) {
final LocusInfo locusInfo = next();
if (locusInfo != null) {
complete.addFirst(locusInfo);
}
}
return !complete.isEmpty();
}
/**
* @return true if there are loci in the target mask that have yet to be covered by LocusInfos
*/
private boolean hasRemainingMaskBases() {
// if there are more sequences in the mask, by definition some of them must have
// marked bases otherwise if we're in the last sequence, but we're not at the last marked position,
// there is also more in the mask
if (!emitUncoveredLoci) {
// If not emitting uncovered loci, this check is irrelevant
return false;
}
return (lastReferenceSequence < referenceSequenceMask.getMaxSequenceIndex() ||
(lastReferenceSequence == referenceSequenceMask.getMaxSequenceIndex() &&
lastPosition < referenceSequenceMask.nextPosition(lastReferenceSequence, lastPosition)));
}
/**
* hasNext() has been fixed so that if it returns true, next() is now guaranteed not to return null.
*/
public LocusInfo next() {
// if we don't have any completed entries to return, try and make some!
while(complete.isEmpty() && samHasMore()) {
final SAMRecord rec = samIterator.peek();
// There might be unmapped reads mixed in with the mapped ones, but when a read
// is encountered with no reference index it means that all the mapped reads have been seen.
if (rec.getReferenceIndex() == -1) {
this.finishedAlignedReads = true;
continue;
}
// Skip over an unaligned read that has been forced to be sorted with the aligned reads
if (rec.getReadUnmappedFlag()
|| rec.getMappingQuality() < this.mappingQualityScoreCutoff
|| (!this.includeNonPfReads && rec.getReadFailsVendorQualityCheckFlag())) {
samIterator.next();
continue;
}
final Locus alignmentStart = new LocusImpl(rec.getReferenceIndex(), rec.getAlignmentStart());
// emit everything that is before the start of the current read, because we know no more
// coverage will be accumulated for those loci.
while (!accumulator.isEmpty() && locusComparator.compare(accumulator.getFirst(), alignmentStart) < 0) {
final LocusInfo first = accumulator.getFirst();
populateCompleteQueue(alignmentStart);
if (!complete.isEmpty()) {
return complete.removeFirst();
}
if (!accumulator.isEmpty() && first == accumulator.getFirst()) {
throw new PicardException("Stuck in infinite loop");
}
}
// at this point, either the accumulator list is empty or the head should
// be the same position as the first base of the read
if (!accumulator.isEmpty()) {
if (accumulator.getFirst().getSequenceIndex() != rec.getReferenceIndex() ||
accumulator.getFirst().position != rec.getAlignmentStart()) {
throw new IllegalStateException("accumulator should be empty or aligned with current SAMRecord");
}
}
// Store the loci for the read in the accumulator
accumulateSamRecord(rec);
samIterator.next();
}
final Locus endLocus = new LocusImpl(Integer.MAX_VALUE, Integer.MAX_VALUE);
// if we have nothing to return to the user, and we're at the end of the SAM iterator,
// push everything into the complete queue
if (complete.isEmpty() && !samHasMore()) {
while(!accumulator.isEmpty()) {
populateCompleteQueue(endLocus);
if (!complete.isEmpty()) {
return complete.removeFirst();
}
}
}
// if there are completed entries, return those
if (!complete.isEmpty()) {
return complete.removeFirst();
} else if (emitUncoveredLoci){
final Locus afterLastMaskPositionLocus = new LocusImpl(referenceSequenceMask.getMaxSequenceIndex(),
referenceSequenceMask.getMaxPosition() + 1);
// In this case... we're past the last read from SAM so see if we can
// fill out any more (zero coverage) entries from the mask
return createNextUncoveredLocusInfo(afterLastMaskPositionLocus);
} else {
return null;
}
}
/**
* Capture the loci covered by the given SAMRecord in the LocusInfos in the accumulator,
* creating new LocusInfos as needed.
*/
private void accumulateSamRecord(final SAMRecord rec) {
// interpret the CIGAR string and add the base info
for(final AlignmentBlock alignmentBlock : rec.getAlignmentBlocks()) {
for (int i = 0; i < alignmentBlock.getLength(); ++i) {
// 0-based offset into the read of the current base
final int readOffset = alignmentBlock.getReadStart() + i - 1;
// 1-based reference position that the current base aligns to
final int refPos = alignmentBlock.getReferenceStart() + i;
// 0-based offset from the aligned position of the first base in the read to the aligned position
// of the current base.
final int refOffset = refPos - rec.getAlignmentStart();
// Ensure there are LocusInfos up to and including this position
for (int j = accumulator.size(); j <= refOffset; ++j) {
accumulator.add(new LocusInfo(getReferenceSequence(rec.getReferenceIndex()),
rec.getAlignmentStart() + j));
}
// if the quality score cutoff is met, accumulate the base info
if (rec.getBaseQualities()[readOffset] >= getQualityScoreCutoff()) {
accumulator.get(refOffset).add(rec, readOffset);
}
}
}
}
/**
* Create the next relevant zero-coverage LocusInfo
* @param stopBeforeLocus don't go up to this sequence and position
* @return a zero-coverage LocusInfo, or null if there is none before the stopBefore locus
*/
private LocusInfo createNextUncoveredLocusInfo(final Locus stopBeforeLocus) {
while (lastReferenceSequence <= stopBeforeLocus.getSequenceIndex() &&
lastReferenceSequence <= referenceSequenceMask.getMaxSequenceIndex()) {
if (lastReferenceSequence == stopBeforeLocus.getSequenceIndex() &&
lastPosition +1 >= stopBeforeLocus.getPosition()) {
return null;
}
final int nextbit = referenceSequenceMask.nextPosition(lastReferenceSequence, lastPosition);
// try the next reference sequence
if (nextbit == -1) {
// No more in this reference sequence
if (lastReferenceSequence == stopBeforeLocus.getSequenceIndex()) {
lastPosition = stopBeforeLocus.getPosition();
return null;
}
lastReferenceSequence++;
lastPosition = 0;
} else if (lastReferenceSequence < stopBeforeLocus.getSequenceIndex() ||
nextbit < stopBeforeLocus.getPosition()) {
lastPosition = nextbit;
return new LocusInfo(getReferenceSequence(lastReferenceSequence), lastPosition);
} else if (nextbit >= stopBeforeLocus.getPosition()) {
return null;
}
}
return null;
}
/**
* Pop the first entry from the LocusInfo accumulator into the complete queue. In addition,
* check the ReferenceSequenceMask and if there are intervening mask positions between the last popped base and the one
* about to be popped, put those on the complete queue as well.
* Note that a single call to this method may not empty the accumulator completely, or even
* empty it at all, because it may just put a zero-coverage LocusInfo into the complete queue.
*/
private void populateCompleteQueue(final Locus stopBeforeLocus) {
// Because of gapped alignments, it is possible to create LocusInfo's with no reads associated with them.
// Skip over these.
while (!accumulator.isEmpty() && accumulator.getFirst().getRecordAndPositions().isEmpty() &&
locusComparator.compare(accumulator.getFirst(), stopBeforeLocus) < 0) {
accumulator.removeFirst();
}
if (accumulator.isEmpty()) {
return;
}
final LocusInfo locusInfo = accumulator.getFirst();
if (locusComparator.compare(stopBeforeLocus, locusInfo) <= 0) {
return;
}
// If necessary, emit a zero-coverage LocusInfo
if (emitUncoveredLoci) {
final LocusInfo zeroCoverage = createNextUncoveredLocusInfo(locusInfo);
if (zeroCoverage != null) {
complete.addLast(zeroCoverage);
return;
}
}
// At this point we know we're going to process the LocusInfo, so remove it from the accumulator.
accumulator.removeFirst();
// fill in any gaps based on our genome mask
final int sequenceIndex = locusInfo.getSequenceIndex();
// only add to the complete queue if it's in the mask (or we have no mask!)
if (referenceSequenceMask.get(locusInfo.getSequenceIndex(), locusInfo.getPosition())) {
complete.addLast(locusInfo);
}
lastReferenceSequence = sequenceIndex;
lastPosition = locusInfo.getPosition();
}
private SAMSequenceRecord getReferenceSequence(final int referenceSequenceIndex) {
return samReader.getFileHeader().getSequence(referenceSequenceIndex);
}
public void remove() {
throw new UnsupportedOperationException("Can not remove records from a SAM file via an iterator!");
}
// Helper methods below this point...
/**
* Controls which, if any, SAMRecords are filtered. By default duplicate reads and non-primary alignments
* are filtered out. The list of filters passed here replaces any existing filters.
* @param samFilters list of filters, or null if no filtering is desired.
*/
public void setSamFilters(final List<SamRecordFilter> samFilters) {
this.samFilters = samFilters;
}
public int getQualityScoreCutoff() { return qualityScoreCutoff; }
public void setQualityScoreCutoff(final int qualityScoreCutoff) { this.qualityScoreCutoff = qualityScoreCutoff; }
public int getMappingQualityScoreCutoff() {
return mappingQualityScoreCutoff;
}
public void setMappingQualityScoreCutoff(final int mappingQualityScoreCutoff) { this.mappingQualityScoreCutoff = mappingQualityScoreCutoff; }
public boolean isIncludeNonPfReads() { return includeNonPfReads; }
public void setIncludeNonPfReads(final boolean includeNonPfReads) { this.includeNonPfReads = includeNonPfReads; }
public boolean isEmitUncoveredLoci() {
return emitUncoveredLoci;
}
public void setEmitUncoveredLoci(final boolean emitUncoveredLoci) {
this.emitUncoveredLoci = emitUncoveredLoci;
}
}
|
package io.cloudslang.lang.compiler.scorecompiler;
import io.cloudslang.lang.compiler.SlangTextualKeys;
import io.cloudslang.lang.compiler.modeller.model.Action;
import io.cloudslang.lang.compiler.modeller.model.Executable;
import io.cloudslang.lang.compiler.modeller.model.Flow;
import io.cloudslang.lang.compiler.modeller.model.Operation;
import io.cloudslang.lang.compiler.modeller.model.Step;
import io.cloudslang.lang.compiler.modeller.model.Workflow;
import io.cloudslang.lang.entities.ExecutableType;
import io.cloudslang.lang.entities.ResultNavigation;
import io.cloudslang.lang.entities.ScoreLangConstants;
import io.cloudslang.lang.entities.bindings.Argument;
import io.cloudslang.lang.entities.bindings.Input;
import io.cloudslang.lang.entities.bindings.Output;
import io.cloudslang.lang.entities.bindings.Result;
import io.cloudslang.score.api.ExecutionPlan;
import io.cloudslang.score.api.ExecutionStep;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ExecutionPlanBuilderTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@InjectMocks
private ExecutionPlanBuilder executionPlanBuilder;
@Mock
private ExecutionStepFactory stepFactory;
private Set<String> systemPropertyDependencies = Collections.emptySet();
private Step createSimpleCompiledParallelStep(String stepName) {
return createSimpleCompiledStep(stepName, true);
}
private Step createSimpleCompiledStep(String stepName) {
return createSimpleCompiledStep(stepName, false);
}
private Step createSimpleCompiledStep(String stepName, List<Map<String, Serializable>> navigationStrings) {
return createSimpleCompiledStep(stepName, false, navigationStrings);
}
private Step createSimpleCompiledStep(String stepName, boolean isParallelLoop) {
List<Map<String, Serializable>> navigationStrings = new ArrayList<>();
Map<String, Serializable> successMap = new HashMap<>();
successMap.put(ScoreLangConstants.SUCCESS_RESULT, ScoreLangConstants.SUCCESS_RESULT);
Map<String, Serializable> failureMap = new HashMap<>();
failureMap.put(ScoreLangConstants.FAILURE_RESULT, ScoreLangConstants.FAILURE_RESULT);
navigationStrings.add(successMap);
navigationStrings.add(failureMap);
return createSimpleCompiledStep(stepName, isParallelLoop, navigationStrings);
}
private Step createSimpleCompiledStep(String stepName, boolean isParallelLoop,
List<Map<String, Serializable>> navigationStrings) {
Map<String, Serializable> preStepActionData = new HashMap<>();
if (isParallelLoop) {
preStepActionData.put(SlangTextualKeys.PARALLEL_LOOP_KEY, "value in values");
}
Map<String, Serializable> postStepActionData = new HashMap<>();
String refId = "refId";
return new Step(
stepName,
preStepActionData,
postStepActionData,
null,
navigationStrings,
refId,
null,
null,
isParallelLoop,
false);
}
private List<Result> defaultFlowResults() {
List<Result> results = new ArrayList<>();
results.add(new Result(ScoreLangConstants.SUCCESS_RESULT, null));
results.add(new Result(ScoreLangConstants.FAILURE_RESULT, null));
return results;
}
private void mockStartStep(Executable executable) {
Map<String, Serializable> preExecActionData = executable.getPreExecActionData();
String execName = executable.getName();
List<Input> inputs = executable.getInputs();
when(stepFactory
.createStartStep(eq(2L), same(preExecActionData), same(inputs), same(execName),
eq(ExecutableType.FLOW))).thenReturn(new ExecutionStep(2L));
when(stepFactory
.createStartStep(eq(1L), same(preExecActionData), same(inputs), same(execName),
eq(ExecutableType.OPERATION))).thenReturn(new ExecutionStep(1L));
}
private void mockPreconditionStep(Executable executable) {
String execName = executable.getName();
when(stepFactory
.createPreconditionStep(eq(1L), same(execName))).thenReturn(new ExecutionStep(1L));
}
private void mockEndStep(Long stepId, Executable executable, ExecutableType executableType) {
Map<String, Serializable> postExecActionData = executable.getPostExecActionData();
List<Output> outputs = executable.getOutputs();
List<Result> results = executable.getResults();
String execName = executable.getName();
when(stepFactory
.createEndStep(eq(stepId), same(postExecActionData), same(outputs), same(results),
same(execName), same(executableType))).thenReturn(new ExecutionStep(stepId));
}
private void mockFinishStep(Long stepId, Step step) {
mockFinishStep(stepId, step, false);
}
private void mockFinishStep(Long stepId, Step step, boolean isParallelLoop) {
Map<String, Serializable> postStepActionData = step.getPostStepActionData();
String stepName = step.getName();
String group = step.getWorkerGroup();
when(stepFactory
.createFinishStepStep(eq(stepId), eq(postStepActionData),
anyMapOf(String.class, ResultNavigation.class), eq(stepName), eq(group),
eq(isParallelLoop))).thenReturn(new ExecutionStep(stepId));
}
private void mockFinishParallelLoopStep(Long stepId, Step step) {
mockFinishStep(stepId, step, true);
}
private void mockBeginStep(Long stepId, Step step) {
Map<String, Serializable> preStepActionData = step.getPreStepActionData();
String refId = step.getRefId();
String name = step.getName();
String group = step.getWorkerGroup();
when(stepFactory
.createBeginStepStep(eq(stepId), anyListOf(Argument.class),
eq(preStepActionData), eq(refId), eq(name), eq(group))).thenReturn(new ExecutionStep(stepId));
}
private void mockWorkerStep(Long stepId, Step step) {
Map<String, Serializable> preStepActionData = step.getPreStepActionData();
String name = step.getName();
String group = step.getWorkerGroup();
String robotGroup = step.getRobotGroup();
when(stepFactory
.createWorkerGroupStep(eq(stepId),
eq(preStepActionData), eq(name), eq(group),
eq(robotGroup))).thenReturn(new ExecutionStep(stepId));
}
private void mockAddBranchesStep(Long stepId, Long nextStepId, Long branchBeginStepId, Step step, Flow flow) {
Map<String, Serializable> preStepActionData = step.getPreStepActionData();
String refId = flow.getId();
String name = step.getName();
when(stepFactory.createAddBranchesStep(eq(stepId), eq(nextStepId),
eq(branchBeginStepId), eq(preStepActionData), eq(refId), eq(name)))
.thenReturn(new ExecutionStep(stepId));
}
private void mockJoinBranchesStep(Long stepId, Step step) {
Map<String, Serializable> postStepActionData = step.getPostStepActionData();
String stepName = step.getName();
when(stepFactory.createJoinBranchesStep(eq(stepId), eq(postStepActionData),
anyMapOf(String.class, ResultNavigation.class), eq(stepName)))
.thenReturn(new ExecutionStep(stepId));
}
@Test
public void testCreateOperationExecutionPlan() throws Exception {
Map<String, Serializable> preOpActionData = new HashMap<>();
Map<String, Serializable> postOpActionData = new HashMap<>();
Map<String, Serializable> actionData = new HashMap<>();
Action action = new Action(actionData);
String operationName = "operationName";
String opNamespace = "user.flows";
List<Input> inputs = new ArrayList<>();
List<Output> outputs = new ArrayList<>();
List<Result> results = new ArrayList<>();
Operation compiledOperation =
new Operation(preOpActionData, postOpActionData, action, opNamespace,
operationName, inputs, outputs, results, null, systemPropertyDependencies);
mockStartStep(compiledOperation);
when(stepFactory.createActionStep(eq(2L), same(actionData))).thenReturn(new ExecutionStep(2L));
mockEndStep(3L, compiledOperation, ExecutableType.OPERATION);
ExecutionPlan executionPlan = executionPlanBuilder.createOperationExecutionPlan(compiledOperation);
assertEquals("different number of execution steps than expected", 3, executionPlan.getSteps().size());
assertEquals("operation name is different than expected", operationName, executionPlan.getName());
assertEquals("language name is different than expected", "CloudSlang", executionPlan.getLanguage());
assertEquals("begin step is different than expected", Long.valueOf(1), executionPlan.getBeginStep());
}
@Test
public void createSimpleFlow() throws Exception {
Map<String, Serializable> preFlowActionData = new HashMap<>();
Map<String, Serializable> postFlowActionData = new HashMap<>();
Deque<Step> steps = new LinkedList<>();
Step step = createSimpleCompiledStep("stepName");
steps.add(step);
Workflow workflow = new Workflow(steps);
String flowName = "flowName";
String flowNamespace = "user.flows";
List<Input> inputs = new ArrayList<>();
List<Output> outputs = new ArrayList<>();
List<Result> results = defaultFlowResults();
Flow compiledFlow =
new Flow(preFlowActionData, postFlowActionData, workflow, flowNamespace,
flowName, null, inputs, outputs, results, null, systemPropertyDependencies);
mockStartStep(compiledFlow);
mockPreconditionStep(compiledFlow);
mockEndStep(0L, compiledFlow, ExecutableType.FLOW);
mockWorkerStep(3L, step);
mockBeginStep(4L, step);
mockFinishStep(5L, step);
ExecutionPlan executionPlan = executionPlanBuilder.createFlowExecutionPlan(compiledFlow);
assertEquals("different number of execution steps than expected", 6, executionPlan.getSteps().size());
assertEquals("flow name is different than expected", flowName, executionPlan.getName());
assertEquals("language name is different than expected", "CloudSlang", executionPlan.getLanguage());
assertEquals("begin step is different than expected", Long.valueOf(1), executionPlan.getBeginStep());
}
@Test
public void createSimpleFlowWithParallelLoop() throws Exception {
Map<String, Serializable> preFlowActionData = new HashMap<>();
Map<String, Serializable> postFlowActionData = new HashMap<>();
Deque<Step> steps = new LinkedList<>();
Step step = createSimpleCompiledParallelStep("stepName");
steps.add(step);
Workflow workflow = new Workflow(steps);
String flowName = "flowName";
String flowNamespace = "user.flows";
List<Input> inputs = new ArrayList<>();
List<Output> outputs = new ArrayList<>();
List<Result> results = defaultFlowResults();
Flow compiledFlow =
new Flow(preFlowActionData, postFlowActionData, workflow, flowNamespace,
flowName, null, inputs, outputs, results, null, systemPropertyDependencies);
mockPreconditionStep(compiledFlow);
mockStartStep(compiledFlow);
mockEndStep(0L, compiledFlow, ExecutableType.FLOW);
mockWorkerStep(3L, step);
mockAddBranchesStep(4L, 7L, 5L, step, compiledFlow);
mockBeginStep(5L, step);
mockFinishParallelLoopStep(6L, step);
mockJoinBranchesStep(7L, step);
final ExecutionPlan executionPlan = executionPlanBuilder.createFlowExecutionPlan(compiledFlow);
verify(stepFactory).createAddBranchesStep(
eq(4L),
eq(7L),
eq(5L),
eq(step.getPreStepActionData()),
eq(compiledFlow.getId()),
eq(step.getName()));
verify(stepFactory)
.createBeginStepStep(eq(5L), anyListOf(Argument.class), eq(step.getPreStepActionData()),
eq(step.getRefId()), eq(step.getName()), eq(step.getWorkerGroup()));
verify(stepFactory)
.createFinishStepStep(eq(6L), eq(step.getPostStepActionData()),
anyMapOf(String.class, ResultNavigation.class), eq(step.getName()),
eq(step.getWorkerGroup()), eq(step.isParallelLoop()));
verify(stepFactory)
.createJoinBranchesStep(eq(7L), eq(step.getPostStepActionData()),
anyMapOf(String.class, ResultNavigation.class), eq(step.getName()));
assertEquals("different number of execution steps than expected", 8, executionPlan.getSteps().size());
assertEquals("flow name is different than expected", flowName, executionPlan.getName());
assertEquals("language name is different than expected", "CloudSlang", executionPlan.getLanguage());
assertEquals("begin step is different than expected", Long.valueOf(1), executionPlan.getBeginStep());
}
@Test
public void createFlowWithTwoSteps() throws Exception {
final Deque<Step> steps = new LinkedList<>();
String secondStepName = "2ndStep";
List<Map<String, Serializable>> navigationStrings = new ArrayList<>();
Map<String, Serializable> successMap = new HashMap<>();
successMap.put(ScoreLangConstants.SUCCESS_RESULT, secondStepName);
Map<String, Serializable> failureMap = new HashMap<>();
failureMap.put(ScoreLangConstants.FAILURE_RESULT, ScoreLangConstants.FAILURE_RESULT);
navigationStrings.add(successMap);
navigationStrings.add(failureMap);
Step firstStep = createSimpleCompiledStep("firstStepName", navigationStrings);
Step secondStep = createSimpleCompiledStep(secondStepName);
steps.add(firstStep);
steps.add(secondStep);
Map<String, Serializable> preFlowActionData = new HashMap<>();
Map<String, Serializable> postFlowActionData = new HashMap<>();
Workflow workflow = new Workflow(steps);
String flowName = "flowName";
String flowNamespace = "user.flows";
List<Input> inputs = new ArrayList<>();
List<Output> outputs = new ArrayList<>();
List<Result> results = defaultFlowResults();
Flow compiledFlow =
new Flow(preFlowActionData, postFlowActionData, workflow, flowNamespace,
flowName, null, inputs, outputs, results, null, systemPropertyDependencies);
mockPreconditionStep(compiledFlow);
mockStartStep(compiledFlow);
mockEndStep(0L, compiledFlow, ExecutableType.FLOW);
mockWorkerStep(3L, firstStep);
mockBeginStep(4L, firstStep);
mockFinishStep(5L, firstStep);
mockWorkerStep(6L, secondStep);
mockBeginStep(7L, secondStep);
mockFinishStep(8L, secondStep);
ExecutionPlan executionPlan = executionPlanBuilder.createFlowExecutionPlan(compiledFlow);
assertEquals("different number of execution steps than expected", 9, executionPlan.getSteps().size());
assertEquals("flow name is different than expected", flowName, executionPlan.getName());
assertEquals("language name is different than expected", "CloudSlang", executionPlan.getLanguage());
assertEquals("begin step is different than expected", Long.valueOf(1), executionPlan.getBeginStep());
}
@Test
public void createFlowWithNoStepsShouldThrowException() throws Exception {
Map<String, Serializable> preFlowActionData = new HashMap<>();
Map<String, Serializable> postFlowActionData = new HashMap<>();
Deque<Step> steps = new LinkedList<>();
Workflow workflow = new Workflow(steps);
String flowName = "flowName";
String flowNamespace = "user.flows";
List<Input> inputs = new ArrayList<>();
List<Output> outputs = new ArrayList<>();
List<Result> results = new ArrayList<>();
Flow compiledFlow =
new Flow(preFlowActionData, postFlowActionData, workflow, flowNamespace,
flowName, null, inputs, outputs, results, null, systemPropertyDependencies);
mockPreconditionStep(compiledFlow);
mockStartStep(compiledFlow);
mockEndStep(0L, compiledFlow, ExecutableType.FLOW);
exception.expect(RuntimeException.class);
exception.expectMessage(flowName);
executionPlanBuilder.createFlowExecutionPlan(compiledFlow);
}
}
|
package nginx.clojure.java;
import static nginx.clojure.MiniConstants.BODY;
import static nginx.clojure.MiniConstants.BODY_FETCHER;
import static nginx.clojure.MiniConstants.CHARACTER_ENCODING;
import static nginx.clojure.MiniConstants.CHARACTER_ENCODING_FETCHER;
import static nginx.clojure.MiniConstants.CONTENT_TYPE;
import static nginx.clojure.MiniConstants.CONTENT_TYPE_FETCHER;
import static nginx.clojure.MiniConstants.DEFAULT_ENCODING;
import static nginx.clojure.MiniConstants.HEADERS;
import static nginx.clojure.MiniConstants.QUERY_STRING;
import static nginx.clojure.MiniConstants.QUERY_STRING_FETCHER;
import static nginx.clojure.MiniConstants.REMOTE_ADDR;
import static nginx.clojure.MiniConstants.REMOTE_ADDR_FETCHER;
import static nginx.clojure.MiniConstants.REQUEST_METHOD;
import static nginx.clojure.MiniConstants.REQUEST_METHOD_FETCHER;
import static nginx.clojure.MiniConstants.SCHEME;
import static nginx.clojure.MiniConstants.SCHEME_FETCHER;
import static nginx.clojure.MiniConstants.SERVER_NAME;
import static nginx.clojure.MiniConstants.SERVER_NAME_FETCHER;
import static nginx.clojure.MiniConstants.SERVER_PORT;
import static nginx.clojure.MiniConstants.SERVER_PORT_FETCHER;
import static nginx.clojure.MiniConstants.URI;
import static nginx.clojure.MiniConstants.URI_FETCHER;
import static nginx.clojure.java.Constants.HEADER_FETCHER;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nginx.clojure.ChannelListener;
import nginx.clojure.MessageListener;
import nginx.clojure.MiniConstants;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.NginxHandler;
import nginx.clojure.NginxHttpServerChannel;
import nginx.clojure.NginxRequest;
import nginx.clojure.NginxSimpleHandler;
import nginx.clojure.NginxSimpleHandler.SimpleEntry;
import nginx.clojure.RawMessageListener;
import nginx.clojure.RequestVarFetcher;
import nginx.clojure.java.PickerPoweredIterator.Picker;
import nginx.clojure.net.NginxClojureAsynSocket;
public class NginxJavaRequest implements NginxRequest, Map<String, Object> {
protected long r;
NginxHandler handler;
protected NginxJavaRingHandler ringHandler;
protected Object[] array;
protected boolean hijacked = false;
protected NginxHttpServerChannel channel;
protected int phase = -1;
protected volatile boolean released = false;
protected List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners;
public final static ChannelListener<NginxRequest> requestListener = new RawMessageListener<NginxRequest>(){
@Override
public void onClose(NginxRequest req) {
if (req.isReleased()) {
return;
}
req.tagReleased();
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onClose!", req.nativeRequest(), req.uri());
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
en.getValue().onClose(en.getKey());
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onClose Error!", req.nativeRequest()), e);
}
}
}
}
public void onClose(NginxRequest req, long message) {
if (req.isReleased()) {
return;
}
req.tagReleased();
int size = (int) (( message >> 48 ) & 0xffff) - 2;
long address = message << 16 >> 16;
int status = 0;
if (size >= 0) {
status = (0xffff & (NginxClojureRT.UNSAFE.getByte(NginxClojureRT.UNSAFE.getAddress(address)) << 8))
| (0xff & NginxClojureRT.UNSAFE.getByte(NginxClojureRT.UNSAFE.getAddress(address)+1));
}
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onClose2, status=%d", req.nativeRequest(), req.uri(), status);
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
ByteBuffer bb = NginxClojureRT.pickByteBuffer();
CharBuffer cb = NginxClojureRT.pickCharBuffer();
String txt = null;
if (size > 0) {
txt = NginxClojureRT.fetchStringValidPart(address, 2, size, MiniConstants.DEFAULT_ENCODING, bb, cb);
int invalidNum = bb.remaining();
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.getLog().debug("onClose fetchStringValidPart : %d", invalidNum);
}
NginxClojureRT.UNSAFE.putAddress(address, NginxClojureRT.UNSAFE.getAddress(address) - invalidNum);
}
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
ChannelListener<Object> l = en.getValue();
if (l instanceof MessageListener) {
((MessageListener) l).onClose(en.getKey(), status, txt);
}
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onWrite Error!", req.nativeRequest()), e);
}
}
}
}
@Override
public void onConnect(long status, NginxRequest req) {
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onConnect, status=%d", req.nativeRequest(), req.uri(), status);
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
en.getValue().onConnect(status, req);
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onRead Error!", req.nativeRequest()), e);
}
}
}
}
@Override
public void onRead(long status, NginxRequest req) {
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onRead, status=%d", req.nativeRequest(), req.uri(), status);
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
en.getValue().onRead(status, en.getKey());
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onRead Error!", req.nativeRequest()), e);
}
}
}
}
@Override
public void onWrite(long status, NginxRequest req) {
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onWrite, status=%d", req.nativeRequest(), req.uri(), status);
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
en.getValue().onWrite(status, en.getKey());
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onWrite Error!", req.nativeRequest()), e);
}
}
}
}
@Override
public void onBinaryMessage(NginxRequest req, long message, boolean remining, boolean first) {
int size = (int) (( message >> 48 ) & 0xffff);
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onBinaryMessage! size=%d, rem=%s, first=%s, pm=%d", req.nativeRequest(), req.uri(), size, remining, first, NginxClojureRT.UNSAFE.getAddress(message << 16 >> 16));
}
if (size <= 0 && !first && remining) {
return;
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
ChannelListener<Object> l = en.getValue();
if (l instanceof MessageListener) {
ByteBuffer bb = ByteBuffer.allocate(size);
NginxClojureRT.ngx_http_clojure_mem_copy_to_obj(NginxClojureRT.UNSAFE.getAddress(message << 16 >> 16), bb.array(), MiniConstants.BYTE_ARRAY_OFFSET, size);
bb.limit(size);
((MessageListener) l).onBinaryMessage(en.getKey(), bb, remining);
}
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onWrite Error!", req.nativeRequest()), e);
}
}
}
}
@Override
public void onTextMessage(NginxRequest req, long message, boolean remining, boolean first) {
int size = (int) (( message >> 48 ) & 0xffff);
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("#%d: request %s onTextMessage! size=%d, rem=%s, first=%s, pm=%d", req.nativeRequest(), req.uri(), size, remining, first, NginxClojureRT.UNSAFE.getAddress(message << 16 >> 16));
}
List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners = req.listeners();
if (listeners != null) {
ByteBuffer bb = NginxClojureRT.pickByteBuffer();
CharBuffer cb = NginxClojureRT.pickCharBuffer();
long address = message << 16 >> 16;
String txt = NginxClojureRT.fetchStringValidPart(address, 0, size, MiniConstants.DEFAULT_ENCODING, bb, cb);
int invalidNum = bb.remaining();
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.getLog().debug("onTextMessage fetchStringValidPart : %d", invalidNum);
}
NginxClojureRT.UNSAFE.putAddress(address, NginxClojureRT.UNSAFE.getAddress(address) - invalidNum);
if (txt.length() > 0 || first || !remining) {
if ( (txt.length() == 0 || !remining) && invalidNum != 0) {
return;
}
for (int i = listeners.size() - 1; i > -1; i
java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>> en = listeners.get(i);
try {
ChannelListener<Object> l = en.getValue();
if (l instanceof MessageListener) {
((MessageListener) l).onTextMessage(en.getKey(), txt, remining);
}
}catch(Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onWrite Error!", req.nativeRequest()), e);
}
}
}
}
}
};
public NginxJavaRequest(NginxHandler handler, NginxJavaRingHandler ringHandler, long r, Object[] array) {
this.r = r;
this.handler = handler;
this.array = array;
this.ringHandler = ringHandler;
if (r != 0) {
NginxClojureRT.ngx_http_clojure_add_listener(r, requestListener, this, 1);
}
}
@SuppressWarnings("unchecked")
public NginxJavaRequest(NginxHandler handler, NginxJavaRingHandler ringHandler, long r) {
//TODO: SSL_CLIENT_CERT
this(handler, ringHandler, r, new Object[] {
URI, URI_FETCHER,
BODY, BODY_FETCHER,
HEADERS, HEADER_FETCHER,
SERVER_PORT,SERVER_PORT_FETCHER,
SERVER_NAME, SERVER_NAME_FETCHER,
REMOTE_ADDR, REMOTE_ADDR_FETCHER,
QUERY_STRING, QUERY_STRING_FETCHER,
SCHEME, SCHEME_FETCHER,
REQUEST_METHOD, REQUEST_METHOD_FETCHER,
CONTENT_TYPE, CONTENT_TYPE_FETCHER,
CHARACTER_ENCODING, CHARACTER_ENCODING_FETCHER,
});
if (NginxClojureRT.log.isDebugEnabled()) {
get(URI);
}
}
public void prefetchAll() {
int len = array.length >> 1;
for (int i = 0; i < len; i++) {
val(i);
}
}
protected int index(Object key) {
for (int i = 0; i < array.length; i+=2){
if (key == array[i]) {
return i >> 1;
}
}
return -1;
}
public String key(int i) {
return (String) array[i << 1];
}
public Object val(int i) {
i = (i << 1) + 1;
Object o = array[i];
if (o instanceof RequestVarFetcher) {
if (released) {
return null;
}
if (Thread.currentThread() != NginxClojureRT.NGINX_MAIN_THREAD) {
throw new IllegalAccessError("fetching lazy value of " + array[i] + " in LazyRequestMap can only be called in main thread, please pre-access it in main thread OR call LazyRequestMap.prefetchAll() first in main thread");
}
RequestVarFetcher rf = (RequestVarFetcher) o;
array[i] = null;
Object rt = rf.fetch(r, DEFAULT_ENCODING);
array[i] = rt;
return rt;
}
return o;
}
public SimpleEntry<String, Object> entry(int i) {
return new SimpleEntry<String, Object>(key(i), val(i), NginxSimpleHandler.readOnlyEntrySetter);
}
public int setVariable(String name, String value) {
return NginxClojureRT.setNGXVariable(r, name, value);
}
public String getVariable(String name) {
return NginxClojureRT.getNGXVariable(r, name);
}
public long nativeRequest() {
return r;
}
@Override
public boolean containsKey(Object key) {
return index(key) != -1;
}
@Override
public int size() {
return array.length >> 1;
}
@Override
public boolean isEmpty() {
return array.length == 0;
}
@Override
public boolean containsValue(Object value) {
int size = size();
for (int i = 0; i < size; i++) {
if (value.equals(val(i))) {
return true;
}
}
return false;
}
@Override
public Object get(Object key) {
int i = index(key);
return i == -1 ? null : val(i);
}
@Override
public Object put(String key, Object val) {
int i = index(key);
if (i != -1) {
i = (i << 1) + 1;
Object old = array[i];
array[i] = val;
return old;
}
Object[] newArray = new Object[array.length + 2];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = key;
newArray[array.length+1] = val;
this.array = newArray;
return null;
}
@Override
public Object remove(Object key) {
int i = index(key);
if (i == -1) {
return null;
}else {
Object old = val(i);
i <<= 1;
Object[] newArray = new Object[array.length - 2];
if (i > 0) {
System.arraycopy(array, 0, newArray, 0, i);
}
System.arraycopy(array, i + 2, newArray, i, array.length - i - 2);
this.array = newArray;
return old;
}
}
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
for (Entry<? extends String, ? extends Object> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
this.array = new Object[0];
}
private class KeySet extends AbstractSet<String> {
@Override
public Iterator<String> iterator() {
return new PickerPoweredIterator<String>(new Picker<String>() {
@Override
public String pick(int i) {
return key(i);
}
@Override
public int size() {
return array.length >> 1;
}
});
}
@Override
public int size() {
return array.length >> 1;
}
}
private class ValueSet extends AbstractSet<Object> {
@Override
public Iterator<Object> iterator() {
return new PickerPoweredIterator<Object>(new Picker<Object>() {
@Override
public Object pick(int i) {
return val(i);
}
@Override
public int size() {
return array.length >> 1;
}
});
}
@Override
public int size() {
return array.length >> 1;
}
}
@Override
public Set<String> keySet() {
return new KeySet();
}
@Override
public Collection<Object> values() {
return new ValueSet();
}
private class EntrySet extends AbstractSet<Entry<String, Object>> {
@Override
public Iterator<Entry<String, Object>> iterator() {
return new PickerPoweredIterator<Entry<String, Object>>(new Picker<Entry<String, Object>>() {
@Override
public Entry<String, Object> pick(int i) {
return entry(i);
}
@Override
public int size() {
return array.length >> 1;
}
});
}
@Override
public int size() {
return array.length >> 1;
}
}
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return new EntrySet();
}
@Override
public NginxHandler handler() {
return handler;
}
@Override
public boolean isHijacked() {
return hijacked;
}
@Override
public NginxHttpServerChannel channel() {
if (!hijacked) {
NginxClojureRT.UNSAFE.throwException(new IllegalAccessException("not hijacked!"));
}
return channel;
}
@Override
public boolean isReleased() {
return released;
}
@Override
public int phase() {
return phase;
}
protected NginxJavaRequest phase(int phase) {
this.phase = phase;
return this;
}
public boolean isWebSocket() {
return NginxClojureRT.ngx_http_clojure_mem_get_module_ctx_upgrade(r) == 1;
}
@Override
public String toString() {
return String.format("request {id : %d, uri: %s}", r, val(0));
}
@Override
public <T> void addListener(T data, ChannelListener<T> listener) {
if (listeners == null) {
listeners = new ArrayList<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>>(1);
}
listeners.add(new java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>(data, (ChannelListener)listener));
if (isWebSocket()) { //handshake was complete so we need call onConnect manually
try {
listener.onConnect(NginxClojureAsynSocket.NGX_HTTP_CLOJURE_SOCKET_OK, data);
} catch (Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onConnect Error!", r), e);
}
}
}
@Override
public void tagReleased() {
this.released = true;
}
@Override
public List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners() {
return listeners;
}
@Override
public String uri() {
return (String) get(URI);
}
@Override
public NginxHttpServerChannel hijack(boolean ignoreFilter) {
return handler.hijack(this, ignoreFilter);
}
}
|
package org.phenotips.data.internal.controller;
import org.phenotips.Constants;
import org.phenotips.data.IndexedPatientData;
import org.phenotips.data.Patient;
import org.phenotips.data.PatientData;
import org.phenotips.data.PatientDataController;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseStringProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Handles the patients genes.
*
* @version $Id$
* @since 1.0RC1
*/
@Component(roles = { PatientDataController.class })
@Named("gene")
@Singleton
public class GeneListController extends AbstractComplexController<Map<String, String>>
{
/** The XClass used for storing gene data. */
private static final EntityReference GENE_CLASS_REFERENCE = new EntityReference("InvestigationClass",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
private static final String GENES_STRING = "genes";
private static final String CONTROLLER_NAME = GENES_STRING;
private static final String GENES_ENABLING_FIELD_NAME = GENES_STRING;
private static final String GENES_COMMENTS_ENABLING_FIELD_NAME = "genes_comments";
private static final String GENE_KEY = "gene";
private static final String COMMENTS_KEY = "comments";
@Override
public String getName()
{
return CONTROLLER_NAME;
}
@Override
protected String getJsonPropertyName()
{
return getName();
}
@Override
protected List<String> getProperties()
{
return Arrays.asList(GENE_KEY, COMMENTS_KEY);
}
@Override
protected List<String> getBooleanFields()
{
return Collections.emptyList();
}
@Override
protected List<String> getCodeFields()
{
return Collections.emptyList();
}
@Override
public PatientData<Map<String, String>> load(Patient patient)
{
try {
XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
List<BaseObject> geneXWikiObjects = doc.getXObjects(GENE_CLASS_REFERENCE);
if (geneXWikiObjects == null) {
throw new NullPointerException("The patient does not have any gene information");
}
List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>();
for (BaseObject geneObject : geneXWikiObjects) {
Map<String, String> singleGene = new LinkedHashMap<String, String>();
for (String property : getProperties()) {
BaseStringProperty field = (BaseStringProperty) geneObject.getField(property);
if (field != null) {
singleGene.put(property, field.getValue());
}
}
allGenes.add(singleGene);
}
return new IndexedPatientData<Map<String, String>>(getName(), allGenes);
} catch (Exception e) {
// TODO. Log an error.
}
return null;
}
@Override
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames)
{
if (selectedFieldNames != null && !selectedFieldNames.contains(GENES_ENABLING_FIELD_NAME)) {
return;
}
PatientData<Map<String, String>> data = patient.getData(getName());
if (data == null) {
return;
}
Iterator<Map<String, String>> iterator = data.iterator();
if (!iterator.hasNext()) {
return;
}
// put() is placed here because we want to create the property iff at least one field is set/enabled
// (by this point we know there is some data since iterator.hasNext() == true)
json.put(getJsonPropertyName(), new JSONArray());
JSONArray container = json.getJSONArray(getJsonPropertyName());
while (iterator.hasNext()) {
Map<String, String> item = iterator.next();
if (!StringUtils.isBlank(item.get(GENE_KEY))) {
if (StringUtils.isBlank(item.get(COMMENTS_KEY))
|| (selectedFieldNames != null && !selectedFieldNames.contains(GENES_COMMENTS_ENABLING_FIELD_NAME))) {
item.remove(COMMENTS_KEY);
}
container.add(item);
}
}
}
}
|
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//This library is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//You should have received a copy of the GNU Lesser General Public
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.tools.namefind;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import opennlp.maxent.EventStream;
import opennlp.maxent.GIS;
import opennlp.maxent.GISModel;
import opennlp.maxent.MaxentModel;
import opennlp.maxent.PlainTextByLineDataStream;
import opennlp.maxent.TwoPassDataIndexer;
import opennlp.maxent.io.SuffixSensitiveGISModelWriter;
import opennlp.tools.util.BeamSearch;
import opennlp.tools.util.Sequence;
import opennlp.tools.util.Span;
/**
* Class for creating a maximum-entropy-based name finder.
*/
public class NameFinderME implements NameFinder {
protected MaxentModel _npModel;
protected NameContextGenerator _contextGen;
private Sequence bestSequence;
private BeamSearch beam;
public static final String START = "start";
public static final String CONTINUE = "cont";
public static final String OTHER = "other";
/**
* Creates a new name finder with the specified model.
* @param mod The model to be used to find names.
*/
public NameFinderME(MaxentModel mod) {
this(mod, new DefaultNameContextGenerator(10), 10);
}
/**
* Creates a new name finder with the specified model and context generator.
* @param mod The model to be used to find names.
* @param cg The context generator to be used with this name finder.
*/
public NameFinderME(MaxentModel mod, NameContextGenerator cg) {
this(mod, cg, 10);
}
/**
* Creates a new name finder with the specified model and context generator.
* @param mod The model to be used to find names.
* @param cg The context generator to be used with this name finder.
* @param beamSize The size of the beam to be used in decoding this model.
*/
public NameFinderME(MaxentModel mod, NameContextGenerator cg, int beamSize) {
_npModel = mod;
_contextGen = cg;
beam = new NameBeamSearch(beamSize, cg, mod, beamSize);
}
/* inherieted javadoc */
public List find(List toks, Map prevTags) {
bestSequence = beam.bestSequence(toks, new Object[] { prevTags });
return bestSequence.getOutcomes();
}
/* inherieted javadoc */
public String[] find(Object[] toks, Map prevTags) {
bestSequence = beam.bestSequence(toks, new Object[] { prevTags });
List c = bestSequence.getOutcomes();
return (String[]) c.toArray(new String[c.size()]);
}
/* inherieted javadoc */
public List find(String sentence, List toks, Map prevMap) {
List tokenStrings = new LinkedList();
Iterator tokenIterator = toks.iterator();
while (tokenIterator.hasNext()) {
Span tokenSpan = (Span) tokenIterator.next();
tokenStrings.add(sentence.substring(tokenSpan.getStart(),
tokenSpan.getEnd()));
}
List result = find(tokenStrings, prevMap);
List detectedNames = new LinkedList();
Span startSpan = null;
Span endSpan = null;
boolean insideName = false;
int length = tokenStrings.size();
for (int i = 0; i < length; i++) {
Span annotation = (Span) toks.get(i);
if (insideName) {
// check if insideName ends here
if (!result.get(i).equals(NameFinderME.CONTINUE)) {
Span entitySpan = new Span(startSpan.getStart(), endSpan.getEnd());
detectedNames.add(entitySpan);
startSpan = null;
insideName = false;
endSpan = null;
}
}
else {
if (result.get(i).equals(NameFinderME.START)) {
startSpan = annotation;
insideName = true;
}
}
if (insideName) {
endSpan = annotation;
}
}
// is last start in sent
if (insideName) {
detectedNames.add(startSpan);
}
return detectedNames;
}
/* inherieted javadoc */
public Span[] find(String sentence, Span[] toks, Map prevMap) {
List tokList = new LinkedList();
Collections.addAll(tokList, toks);
List resultList = find(sentence, tokList, prevMap);
Span[] result = new Span[toks.length];
resultList.toArray(result);
return result;
}
/**
* This method determines wheter the outcome is valid for the preceeding sequence.
* This can be used to implement constraints on what sequences are valid.
* @param outcome The outcome.
* @param sequence The precceding sequence of outcomes assignments.
* @return true is the outcome is valid for the sequence, false otherwise.
*/
protected boolean validOutcome(String outcome, Sequence sequence) {
if (outcome.equals(CONTINUE)) {
List tags = sequence.getOutcomes();
int li = tags.size() - 1;
if (li == -1) {
return false;
}
else if (((String) tags.get(li)).equals(OTHER)) {
return false;
}
}
return true;
}
/**
* Implementation of the abstract beam search to allow the name finder to use the common beam search code.
*
*/
private class NameBeamSearch extends BeamSearch {
/**
* Creams a beam seach of the specified size sing the specified model with the specified context generator.
* @param size The size of the beam.
* @param cg The context generator used with the specified model.
* @param model The model used to determine names.
* @param beamSize
*/
public NameBeamSearch(int size, NameContextGenerator cg, MaxentModel model, int beamSize) {
super(size, cg, model, beamSize);
}
protected boolean validSequence(int i, List sequence, Sequence s, String outcome) {
return validOutcome(outcome, s);
}
}
/**
* Populates the specified array with the probabilities of the last decoded sequence. The
* sequence was determined based on the previous call to <code>chunk</code>. The
* specified array should be at least as large as the numbe of tokens in the previous call to <code>chunk</code>.
* @param probs An array used to hold the probabilities of the last decoded sequence.
*/
public void probs(double[] probs) {
bestSequence.getProbs(probs);
}
/**
* Returns an array with the probabilities of the last decoded sequence. The
* sequence was determined based on the previous call to <code>chunk</code>.
* @return An array with the same number of probabilities as tokens were sent to <code>chunk</code>
* when it was last called.
*/
public double[] probs() {
return bestSequence.getProbs();
}
/**
* Creates the map with the previous result.
*
* @param tokens - the previous tokens as array of String or
* null (if first time)
* @param outcomes - the previous outcome as array of String or null
* (if first time)
* @return - the previous map
*/
public static Map createPrevMap(String[] tokens, String[] outcomes) {
Map prevMap = new HashMap();
if (tokens != null | outcomes != null) {
if (tokens.length != outcomes.length) {
throw new IllegalArgumentException(
"The sent and outcome arrays MUST have the same size!");
}
for (int i = 0; i < tokens.length; i++) {
prevMap.put(tokens[i], outcomes[i]);
}
}
else {
prevMap = Collections.EMPTY_MAP;
}
return prevMap;
}
/**
* Creates the prevMap with the previous result.
*
* @param tokens - the previous tokens as List of String or null
* @param outcomes - the previous outcome as List of Strings or null
* @return - the previous map or an empty map if token or outcome is null
*/
public static Map createPrevMap(List tokens, List outcomes) {
Map prevMap = new HashMap();
if (tokens != null | outcomes != null) {
if (tokens.size() != outcomes.size()) {
throw new IllegalArgumentException(
"The sent and outcome arrays MUST have the same size!");
}
Iterator tokenIterator = tokens.iterator();
Iterator outcomeIterator = outcomes.iterator();
while (tokenIterator.hasNext() && outcomeIterator.hasNext()) {
prevMap.put(tokenIterator.next(), outcomeIterator.next());
}
}
else {
prevMap = Collections.EMPTY_MAP;
}
return prevMap;
}
/**
* Creates the prevMap with the previous result.
*
* @param sentence
* @param tokens - the previous tokens as list of Span or
* null (if first time)
* @param outcomes - the previous outcome as list of Span or null
* (if first time)
* @return - the previous map
*/
public static Map createPrevMap(String sentence, List tokens, List outcomes) {
Map prevMap;
if (sentence != null && tokens != null &&
outcomes != null & tokens.size() > 0) {
if (tokens.size() < outcomes.size()) {
throw new IllegalArgumentException("The number of tokens must be " +
"less or equal compared to the number of outcomes");
}
Iterator outcomeIterator = outcomes.iterator();
Span outcomeSpan;
if (outcomeIterator.hasNext()) {
outcomeSpan = (Span) outcomeIterator.next();
}
else {
outcomeSpan = new Span(0, 0);
}
boolean isInsideSpan = false;
prevMap = new HashMap();
for (Iterator i = tokens.iterator(); i.hasNext();) {
Span token = (Span) i.next();
if (!outcomeSpan.contains(token)) {
prevMap.put(token.getCoveredText(sentence),
NameFinderME.OTHER);
if (isInsideSpan) {
if (outcomeIterator.hasNext()) {
outcomeSpan = (Span) outcomeIterator.next();
}
isInsideSpan = false;
}
}
else if (outcomeSpan.startsWith(token)) {
prevMap.put(token.getCoveredText(sentence),
NameFinderME.START);
isInsideSpan = true;
}
// isContained
else {
prevMap.put(token.getCoveredText(sentence),
NameFinderME.CONTINUE);
}
}
}
else {
prevMap = Collections.EMPTY_MAP;
}
return prevMap;
}
private static GISModel train(EventStream es, int iterations, int cut) throws IOException {
return GIS.trainModel(iterations, new TwoPassDataIndexer(es, cut));
}
public static void usage(){
System.err.println("Usage: opennlp.tools.namefind.NameFinderME -encoding encoding training_file model");
System.exit(1);
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
usage();
}
try {
int ai=0;
String encoding = null;
while (args[ai].startsWith("-")) {
if (args[ai].equals("-encoding")) {
ai++;
if (ai < args.length) {
encoding = args[ai];
ai++;
}
else {
usage();
}
}
}
File inFile = new File(args[ai++]);
File outFile = new File(args[ai++]);
GISModel mod;
EventStream es = new NameFinderEventStream(new PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile),encoding)));
if (args.length > ai)
mod = train(es, Integer.parseInt(args[ai++]), Integer.parseInt(args[ai++]));
else
mod = train(es, 100, 5);
System.out.println("Saving the model as: " + outFile);
new SuffixSensitiveGISModelWriter(mod, outFile).persist();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.apache.commons.lang;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* The empty String <code>""</code>.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* Represents a failed index search.
* @since 2.?.?
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>An array of <code>String</code>s used for padding.</p>
*
* <p>Used for efficient space padding. The length of each String expands as needed.</p>
*/
private static final String[] PADDING = new String[Character.MAX_VALUE];
static {
// space padding is most common, start with 64 chars
PADDING[32] = " ";
}
/**
* <p><code>StringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>StringUtils.trim(" foo ");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
}
// Empty checks
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return (str == null || str.length() == 0);
}
/**
* <p>Checks if a String is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is not empty and not null
*/
public static boolean isNotEmpty(String str) {
return (str != null && str.length() > 0);
}
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* <p>Checks if a String is not empty (""), not null and not whitespace only.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is
* not empty and not null and not whitespace
* @since 2.0
*/
public static boolean isNotBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return false;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return true;
}
}
return false;
}
// Trim
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling <code>null</code> by returning
* an empty String ("").</p>
*
* <pre>
* StringUtils.clean(null) = ""
* StringUtils.clean("") = ""
* StringUtils.clean("abc") = "abc"
* StringUtils.clean(" abc ") = "abc"
* StringUtils.clean(" ") = ""
* </pre>
*
* @see java.lang.String#trim()
* @param str the String to clean, may be null
* @return the trimmed text, never <code>null</code>
* @deprecated Use the clearer named {@link #trimToEmpty(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String clean(String str) {
return (str == null ? EMPTY : str.trim());
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling <code>null</code> by returning
* <code>null</code>.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, <code>null</code> if null String input
*/
public static String trim(String str) {
return (str == null ? null : str.trim());
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning <code>null</code> if the String is
* empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* <code>null</code> if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(String str) {
String ts = trim(str);
return (ts == null || ts.length() == 0 ? null : ts);
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String trimToEmpty(String str) {
return (str == null ? EMPTY : str.trim());
}
// Stripping
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str) {
return strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* <code>null</code> if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = null
* StringUtils.strip(" ") = null
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* <code>null</code> if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return (str.length() == 0 ? null : str);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if <code>null</code> input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.strip(null) = ""
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String stripToEmpty(String str) {
return (str == null ? EMPTY : strip(str, null));
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str, String stripChars) {
if (str == null || str.length() == 0) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripStart(String str, String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
end
}
}
return str.substring(0, end);
}
// StripAll
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.
* A <code>null</code> stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs, String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
// Equals
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see java.lang.String#equals(Object)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return <code>true</code> if the Strings are equal, case sensitive, or
* both <code>null</code>
*/
public static boolean equals(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
* the case.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered equal. Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @see java.lang.String#equalsIgnoreCase(String)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return <code>true</code> if the Strings are equal, case insensitive, or
* both <code>null</code>
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2));
}
// IndexOf
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, char searchChar) {
if (str == null || str.length() == 0) {
return -1;
}
return str.indexOf(searchChar);
}
/**
* <p>Finds the first index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#indexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
* A negative start position is treated as zero.
* A start position greater than the string length returns <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, char searchChar, int startPos) {
if (str == null || str.length() == 0) {
return -1;
}
return str.indexOf(searchChar, startPos);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return -1;
}
return str.indexOf(searchStr);
}
/**
* <p>Finds the n-th index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th <code>searchStr</code> to find
* @return the n-th index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
* @since 2.?.?
*/
public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return 0;
}
int found = 0;
int index = INDEX_NOT_FOUND;
do {
index = str.indexOf(searchStr, index + 1);
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return -1;
}
// JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence
if (searchStr.length() == 0 && startPos >= str.length()) {
return str.length();
}
return str.indexOf(searchStr, startPos);
}
// LastIndexOf
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, char searchChar) {
if (str == null || str.length() == 0) {
return -1;
}
return str.lastIndexOf(searchChar);
}
/**
* <p>Finds the last index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, char searchChar, int startPos) {
if (str == null || str.length() == 0) {
return -1;
}
return str.lastIndexOf(searchChar, startPos);
}
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 0
* StringUtils.lastIndexOf("aabaabaa", "b") = 2
* StringUtils.lastIndexOf("aabaabaa", "ab") = 1
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the last index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return -1;
}
return str.lastIndexOf(searchStr);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return -1;
}
return str.lastIndexOf(searchStr, startPos);
}
// Contains
/**
* <p>Checks if String contains a search character, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return true if the String contains the search character,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, char searchChar) {
if (str == null || str.length() == 0) {
return false;
}
return (str.indexOf(searchChar) >= 0);
}
/**
* <p>Find the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return true if the String contains the search character,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
return (str.indexOf(searchStr) >= 0);
}
// IndexOfAny chars
/**
* <p>Search a String to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
* StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAny(String str, char[] searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
}
/**
* <p>Search a String to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba","z") = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAny(String str, String searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return -1;
}
return indexOfAny(str, searchChars.toCharArray());
}
// IndexOfAnyBut chars
/**
* <p>Search a String to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
* StringUtils.indexOfAnyBut("aba", 'ab') = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAnyBut(String str, char[] searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
return -1;
}
outer : for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* <p>Search a String to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
* StringUtils.indexOfAnyBut("aba","ab") = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAnyBut(String str, String searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
if (searchChars.indexOf(str.charAt(i)) < 0) {
return i;
}
}
return -1;
}
// ContainsOnly
/**
* <p>Checks if the String contains only certain characters.</p>
*
* <p>A <code>null</code> String will return <code>false</code>.
* A <code>null</code> valid character array will return <code>false</code>.
* An empty String ("") always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param str the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
*/
public static boolean containsOnly(String str, char[] valid) {
// All these pre-checks are to maintain API with an older version
if ((valid == null) || (str == null)) {
return false;
}
if (str.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(str, valid) == -1;
}
/**
* <p>Checks if the String contains only certain characters.</p>
*
* <p>A <code>null</code> String will return <code>false</code>.
* A <code>null</code> valid character String will return <code>false</code>.
* An empty String ("") always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param str the String to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
*/
public static boolean containsOnly(String str, String validChars) {
if (str == null || validChars == null) {
return false;
}
return containsOnly(str, validChars.toCharArray());
}
// ContainsNone
/**
* <p>Checks that the String does not contain certain characters.</p>
*
* <p>A <code>null</code> String will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param str the String to check, may be null
* @param invalidChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
*/
public static boolean containsNone(String str, char[] invalidChars) {
if (str == null || invalidChars == null) {
return true;
}
int strSize = str.length();
int validSize = invalidChars.length;
for (int i = 0; i < strSize; i++) {
char ch = str.charAt(i);
for (int j = 0; j < validSize; j++) {
if (invalidChars[j] == ch) {
return false;
}
}
}
return true;
}
/**
* <p>Checks that the String does not contain certain characters.</p>
*
* <p>A <code>null</code> String will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param str the String to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
*/
public static boolean containsNone(String str, String invalidChars) {
if (str == null || invalidChars == null) {
return true;
}
return containsNone(str, invalidChars.toCharArray());
}
// IndexOfAny strings
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.
* A <code>null</code> search array entry will be ignored, but a search
* array containing "" will return <code>0</code> if <code>str</code> is not
* null. This method uses {@link String#indexOf(String)}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
*/
public static int indexOfAny(String str, String[] searchStrs) {
if ((str == null) || (searchStrs == null)) {
return -1;
}
int sz = searchStrs.length;
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.indexOf(search);
if (tmp == -1) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return (ret == Integer.MAX_VALUE) ? -1 : ret;
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search array will return <code>-1</code>.
* A <code>null</code> or zero length search array entry will be ignored,
* but a search array containing "" will return the length of <code>str</code>
* if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the last index of any of the Strings, -1 if no match
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
if ((str == null) || (searchStrs == null)) {
return -1;
}
int sz = searchStrs.length;
int ret = -1;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.lastIndexOf(search);
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
// Substring
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start <code>n</code>
* characters from the end of the String.</p>
*
* <p>A <code>null</code> String will return <code>null</code>.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, <code>null</code> if null String input
*/
public static String substring(String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end <code>n</code>
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the <code>start</code>
* position and ends before the <code>end</code> position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* <code>start = 0</code>. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If <code>start</code> is not strictly to the left of <code>end</code>, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end positon,
* <code>null</code> if null String input
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
// Left/Right/Mid
/**
* <p>Gets the leftmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the
* String is <code>null</code>, the String will be returned without
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the leftmost characters, <code>null</code> if null String input
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
} else {
return str.substring(0, len);
}
}
/**
* <p>Gets the rightmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the String
* is <code>null</code>, the String will be returned without an
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the rightmost characters, <code>null</code> if null String input
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
} else {
return str.substring(str.length() - len);
}
}
/**
* <p>Gets <code>len</code> characters from the middle of a String.</p>
*
* <p>If <code>len</code> characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is <code>null</code>, <code>null</code> will be returned.
* An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String, must be zero or positive
* @return the middle characters, <code>null</code> if null String input
*/
public static String mid(String str, int pos, int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= (pos + len)) {
return str.substring(pos);
} else {
return str.substring(pos, pos + len);
}
}
// SubStringAfter/SubStringBefore
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the input string.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBefore(String str, String separator) {
if (str == null || separator == null || str.length() == 0) {
return str;
}
if (separator.length() == 0) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == -1) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the empty string if the
* input string is not <code>null</code>.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfter(String str, String separator) {
if (str == null || str.length() == 0) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == -1) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the input string.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBeforeLast(String str, String separator) {
if (str == null || separator == null || str.length() == 0 || separator.length() == 0) {
return str;
}
int pos = str.lastIndexOf(separator);
if (pos == -1) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the empty string if
* the input string is not <code>null</code>.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfterLast(String str, String separator) {
if (str == null || str.length() == 0) {
return str;
}
if (separator == null || separator.length() == 0) {
return EMPTY;
}
int pos = str.lastIndexOf(separator);
if (pos == -1 || pos == (str.length() - separator.length())) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// Substring between
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> tag returns <code>null</code>.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open/close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "tag") = null
* StringUtils.substringBetween("", "tag", "tag") = null
* StringUtils.substringBetween("yabcz", null, null) = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String open, String close) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open);
if (start != -1) {
int end = str.indexOf(close, start + open.length());
if (end != -1) {
return str.substring(start + open.length(), end);
}
}
return null;
}
// Nested extraction
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> tag returns <code>null</code>.</p>
*
* <pre>
* StringUtils.getNestedString(null, *) = null
* StringUtils.getNestedString("", "") = ""
* StringUtils.getNestedString("", "tag") = null
* StringUtils.getNestedString("tagabctag", null) = null
* StringUtils.getNestedString("tagabctag", "") = ""
* StringUtils.getNestedString("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing nested-string, may be null
* @param tag the String before and after nested-string, may be null
* @return the nested String, <code>null</code> if no match
* @deprecated Use the better named {@link #substringBetween(String, String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String getNestedString(String str, String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open/close returns an empty string.</p>
*
* <pre>
* StringUtils.getNestedString(null, *, *) = null
* StringUtils.getNestedString("", "", "") = ""
* StringUtils.getNestedString("", "", "tag") = null
* StringUtils.getNestedString("", "tag", "tag") = null
* StringUtils.getNestedString("yabcz", null, null) = null
* StringUtils.getNestedString("yabcz", "", "") = ""
* StringUtils.getNestedString("yabcz", "y", "z") = "abc"
* StringUtils.getNestedString("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing nested-string, may be null
* @param open the String before nested-string, may be null
* @param close the String after nested-string, may be null
* @return the nested String, <code>null</code> if no match
* @deprecated Use the better named {@link #substringBetween(String, String, String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String getNestedString(String str, String open, String close) {
return substringBetween(str, open, close);
}
// Splitting
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.0
*/
public static String[] split(String str, char separatorChar) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List list = new ArrayList();
int i = 0, start = 0;
boolean match = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if (match) {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(new String[list.size()]);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars) {
return split(str, separatorChars, -1);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cdef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars, int max) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List list = new ArrayList();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match) {
if (sizePlus1++ == max) {
i = len;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match) {
if (sizePlus1++ == max) {
i = len;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match) {
if (sizePlus1++ == max) {
i = len;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
}
if (match) {
list.add(str.substring(start, i));
}
return (String[]) list.toArray(new String[list.size()]);
}
// Joining
/**
* <p>Concatenates elements of an array into a single String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.concatenate(null) = null
* StringUtils.concatenate([]) = ""
* StringUtils.concatenate([null]) = ""
* StringUtils.concatenate(["a", "b", "c"]) = "abc"
* StringUtils.concatenate([null, "", "a"]) = "a"
* </pre>
*
* @param array the array of values to concatenate, may be null
* @return the concatenated String, <code>null</code> if null array input
* @deprecated Use the better named {@link #join(Object[])} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String concatenate(Object[] array) {
return join(array, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param array the array of values to join together, may be null
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array) {
return join(array, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator) {
if (array == null) {
return null;
}
int arraySize = array.length;
int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
StringBuffer buf = new StringBuffer(bufSize);
for (int i = 0; i < arraySize; i++) {
if (i > 0) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
int arraySize = array.length;
// ArraySize == 0: Len = 0
// ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize =
((arraySize == 0)
? 0
: arraySize
* ((array[0] == null ? 16 : array[0].toString().length())
+ ((separator != null) ? separator.length() : 0)));
StringBuffer buf = new StringBuffer(bufSize);
for (int i = 0; i < arraySize; i++) {
if ((separator != null) && (i > 0)) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.0
*/
public static String join(Iterator iterator, char separator) {
if (iterator == null) {
return null;
}
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
if (iterator.hasNext()) {
buf.append(separator);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
*/
public static String join(Iterator iterator, String separator) {
if (iterator == null) {
return null;
}
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
if ((separator != null) && iterator.hasNext()) {
buf.append(separator);
}
}
return buf.toString();
}
// Delete
/**
* <p>Deletes all 'space' characters from a String as defined by
* {@link Character#isSpace(char)}.</p>
*
* <p>This is the only StringUtils method that uses the
* <code>isSpace</code> definition. You are advised to use
* {@link #deleteWhitespace(String)} instead as whitespace is much
* better localized.</p>
*
* <pre>
* StringUtils.deleteSpaces(null) = null
* StringUtils.deleteSpaces("") = ""
* StringUtils.deleteSpaces("abc") = "abc"
* StringUtils.deleteSpaces(" \t abc \n ") = "abc"
* StringUtils.deleteSpaces("ab c") = "abc"
* StringUtils.deleteSpaces("a\nb\tc ") = "abc"
* </pre>
*
* <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code>
* in line with the deprecated <code>isSpace</code> method.</p>
*
* @param str the String to delete spaces from, may be null
* @return the String without 'spaces', <code>null</code> if null String input
* @deprecated Use the better localized {@link #deleteWhitespace(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String deleteSpaces(String str) {
if (str == null) {
return null;
}
return CharSetUtils.delete(str, " \t\r\n\b");
}
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, <code>null</code> if null String input
*/
public static String deleteWhitespace(String str) {
if (str == null || str.length() == 0) {
return str;
}
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Replacing
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("aba", null, null) = "aba"
* StringUtils.replaceOnce("aba", null, null) = "aba"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "aba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String repl, String with, int max)
* @param text text to search and replace in, may be null
* @param repl the String to search for, may be null
* @param with the String to replace with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replaceOnce(String text, String repl, String with) {
return replace(text, repl, with, 1);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("aba", null, null) = "aba"
* StringUtils.replace("aba", null, null) = "aba"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "aba"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String repl, String with, int max)
* @param text text to search and replace in, may be null
* @param repl the String to search for, may be null
* @param with the String to replace with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String repl, String with) {
return replace(text, repl, with, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first <code>max</code> values of the search String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("abaa", null, null, 1) = "abaa"
* StringUtils.replace("abaa", null, null, 1) = "abaa"
* StringUtils.replace("abaa", "a", null, 1) = "abaa"
* StringUtils.replace("abaa", "a", "", 1) = "abaa"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param repl the String to search for, may be null
* @param with the String to replace with, may be null
* @param max maximum number of values to replace, or <code>-1</code> if no maximum
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String repl, String with, int max) {
if (text == null || repl == null || with == null || repl.length() == 0 || max == 0) {
return text;
}
StringBuffer buf = new StringBuffer(text.length());
int start = 0, end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
if (--max == 0) {
break;
}
}
buf.append(text.substring(start));
return buf.toString();
}
// Replace, character based
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, char searchChar, char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br />
* <code>replaceChars("hello", "ho", "jy") = jelly</code>.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return str;
}
char[] chars = str.toCharArray();
int len = chars.length;
boolean modified = false;
for (int i = 0, isize = searchChars.length(); i < isize; i++) {
char searchChar = searchChars.charAt(i);
if (replaceChars == null || i >= replaceChars.length()) {
// delete
int pos = 0;
for (int j = 0; j < len; j++) {
if (chars[j] != searchChar) {
chars[pos++] = chars[j];
} else {
modified = true;
}
}
len = pos;
} else {
// replace
for (int j = 0; j < len; j++) {
if (chars[j] == searchChar) {
chars[j] = replaceChars.charAt(i);
modified = true;
}
}
}
}
if (modified == false) {
return str;
}
return new String(chars, 0, len);
}
// Overlay
/**
* <p>Overlays part of a String with another String.</p>
*
* <pre>
* StringUtils.overlayString(null, *, *, *) = NullPointerException
* StringUtils.overlayString(*, null, *, *) = NullPointerException
* StringUtils.overlayString("", "abc", 0, 0) = "abc"
* StringUtils.overlayString("abcdef", null, 2, 4) = "abef"
* StringUtils.overlayString("abcdef", "", 2, 4) = "abef"
* StringUtils.overlayString("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlayString("abcdef", "zzzz", 4, 2) = "abcdzzzzcdef"
* StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
* StringUtils.overlayString("abcdef", "zzzz", 2, 8) = IndexOutOfBoundsException
* </pre>
*
* @param text the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at, must be valid
* @param end the position to stop overlaying before, must be valid
* @return overlayed String, <code>null</code> if null String input
* @throws NullPointerException if text or overlay is null
* @throws IndexOutOfBoundsException if either position is invalid
* @deprecated Use better named {@link #overlay(String, String, int, int)} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String overlayString(String text, String overlay, int start, int end) {
return new StringBuffer(start + overlay.length() + text.length() - end + 1)
.append(text.substring(0, start))
.append(overlay)
.append(text.substring(end))
.toString();
}
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, <code>null</code> if null String input
* @since 2.0
*/
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
int temp = start;
start = end;
end = temp;
}
return new StringBuffer(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
.toString();
}
// Chomping
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "<code>\n</code>",
* "<code>\r</code>", or "<code>\r\n</code>".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, <code>null</code> if null String input
*/
public static String chomp(String str) {
if (str == null || str.length() == 0) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
if (ch == '\r' || ch == '\n') {
return EMPTY;
} else {
return str;
}
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == '\n') {
if (str.charAt(lastIdx - 1) == '\r') {
lastIdx
}
} else if (last == '\r') {
} else {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes <code>separator</code> from the end of
* <code>str</code> if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo"
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, <code>null</code> if null String input
*/
public static String chomp(String str, String separator) {
if (str == null || str.length() == 0 || separator == null) {
return str;
}
if (str.endsWith(separator)) {
return str.substring(0, str.length() - separator.length());
}
return str;
}
/**
* <p>Remove any "\n" if and only if it is at the end
* of the supplied String.</p>
*
* @param str the String to chomp from, must not be null
* @return String without chomped ending
* @throws NullPointerException if str is <code>null</code>
* @deprecated Use {@link #chomp(String)} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String chompLast(String str) {
return chompLast(str, "\n");
}
/**
* <p>Remove a value if and only if the String ends with that value.</p>
*
* @param str the String to chomp from, must not be null
* @param sep the String to chomp, must not be null
* @return String without chomped ending
* @throws NullPointerException if str or sep is <code>null</code>
* @deprecated Use {@link #chomp(String,String)} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String chompLast(String str, String sep) {
if (str.length() == 0) {
return str;
}
String sub = str.substring(str.length() - sep.length());
if (sep.equals(sub)) {
return str.substring(0, str.length() - sep.length());
} else {
return str;
}
}
/**
* <p>Remove everything and return the last value of a supplied String, and
* everything after it from a String.</p>
*
* @param str the String to chomp from, must not be null
* @param sep the String to chomp, must not be null
* @return String chomped
* @throws NullPointerException if str or sep is <code>null</code>
* @deprecated Use {@link #substringAfterLast(String, String)} instead
* (although this doesn't include the separator)
* Method will be removed in Commons Lang 3.0.
*/
public static String getChomp(String str, String sep) {
int idx = str.lastIndexOf(sep);
if (idx == str.length() - sep.length()) {
return sep;
} else if (idx != -1) {
return str.substring(idx);
} else {
return EMPTY;
}
}
/**
* <p>Remove the first value of a supplied String, and everything before it
* from a String.</p>
*
* @param str the String to chomp from, must not be null
* @param sep the String to chomp, must not be null
* @return String without chomped beginning
* @throws NullPointerException if str or sep is <code>null</code>
* @deprecated Use {@link #substringAfter(String,String)} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String prechomp(String str, String sep) {
int idx = str.indexOf(sep);
if (idx != -1) {
return str.substring(idx + sep.length());
} else {
return str;
}
}
/**
* <p>Remove and return everything before the first value of a
* supplied String from another String.</p>
*
* @param str the String to chomp from, must not be null
* @param sep the String to chomp, must not be null
* @return String prechomped
* @throws NullPointerException if str or sep is <code>null</code>
* @deprecated Use {@link #substringBefore(String,String)} instead
* (although this doesn't include the separator).
* Method will be removed in Commons Lang 3.0.
*/
public static String getPrechomp(String str, String sep) {
int idx = str.indexOf(sep);
if (idx != -1) {
return str.substring(0, idx + sep.length());
} else {
return EMPTY;
}
}
// Chopping
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in <code>\r\n</code>, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, <code>null</code> if null String input
*/
public static String chop(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == '\n') {
if (ret.charAt(lastIdx - 1) == '\r') {
return ret.substring(0, lastIdx - 1);
}
}
return ret;
}
/**
* <p>Removes <code>\n</code> from end of a String if it's there.
* If a <code>\r</code> precedes it, then remove that too.</p>
*
* @param str the String to chop a newline from, must not be null
* @return String without newline
* @throws NullPointerException if str is <code>null</code>
* @deprecated Use {@link #chomp(String)} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static String chopNewline(String str) {
int lastIdx = str.length() - 1;
if (lastIdx <= 0) {
return EMPTY;
}
char last = str.charAt(lastIdx);
if (last == '\n') {
if (str.charAt(lastIdx - 1) == '\r') {
lastIdx
}
} else {
lastIdx++;
}
return str.substring(0, lastIdx);
}
// Conversion
/**
* <p>Escapes any values it finds into their String form.</p>
*
* <p>So a tab becomes the characters <code>'\\'</code> and
* <code>'t'</code>.</p>
*
* <p>As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(String)}
* behind the scenes.
* </p>
* @see StringEscapeUtils#escapeJava(java.lang.String)
* @param str String to escape values in
* @return String with escaped values
* @throws NullPointerException if str is <code>null</code>
* @deprecated Use {@link StringEscapeUtils#escapeJava(String)}
* This method will be removed in Commons Lang 3.0
*/
public static String escape(String str) {
return StringEscapeUtils.escapeJava(str);
}
// Padding
/**
* <p>Repeat a String <code>repeat</code> times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* <code>null</code> if null String input
*/
public static String repeat(String str, int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return padding(repeat, str.charAt(0));
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
char ch = str.charAt(0);
char[] output1 = new char[outputLength];
for (int i = repeat - 1; i >= 0; i
output1[i] = ch;
}
return new String(output1);
case 2 :
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
StringBuffer buf = new StringBuffer(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, 'e') = ""
* StringUtils.padding(3, 'e') = "eee"
* StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
* </pre>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
*/
private static String padding(int repeat, char padChar) {
// be careful of synchronization in this method
// we are assuming that get and set from an array index is atomic
String pad = PADDING[padChar];
if (pad == null) {
pad = String.valueOf(padChar);
}
while (pad.length() < repeat) {
pad = pad.concat(pad);
}
PADDING[padChar] = pad;
return pad.substring(0, repeat);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String rightPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(padding(pads, padChar));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (padStr == null || padStr.length() == 0) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size<code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String leftPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return padding(pads, padChar).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (padStr == null || padStr.length() == 0) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
// Centering
/**
* <p>Centers a String in a larger String of size <code>size</code>
* using the space character (' ').<p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to <code>center(str, size, " ")</code>.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, <code>null</code> if null String input
*/
public static String center(String str, int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab"
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, <code>null</code> if null String input
* @since 2.0
*/
public static String center(String str, int size, char padChar) {
if (str == null || size <= 0) {
return str;
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
public static String center(String str, int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (padStr == null || padStr.length() == 0) {
padStr = " ";
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Case conversion
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @return the upper cased String, <code>null</code> if null String input
*/
public static String upperCase(String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @return the lower cased String, <code>null</code> if null String input
*/
public static String lowerCase(String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link WordUtils#capitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, <code>null</code> if null String input
* @see WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, <code>null</code> if null String input
* @deprecated Use the standardly named {@link #capitalize(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String capitalise(String str) {
return capitalize(str);
}
/**
* <p>Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link WordUtils#uncapitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> if null String input
* @see WordUtils#uncapitalize(String)
* @see #capitalize(String)
* @since 2.0
*/
public static String uncapitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toLowerCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
/**
* <p>Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> if null String input
* @deprecated Use the standardly named {@link #uncapitalize(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String uncapitalise(String str) {
return uncapitalize(str);
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link WordUtils#swapCase(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, <code>null</code> if null String input
*/
public static String swapCase(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
StringBuffer buffer = new StringBuffer(strLen);
char ch = 0;
for (int i = 0; i < strLen; i++) {
ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isTitleCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
}
buffer.append(ch);
}
return buffer.toString();
}
/**
* <p>Capitalizes all the whitespace separated words in a String.
* Only the first letter of each word is changed.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* @param str the String to capitalize, may be null
* @return capitalized String, <code>null</code> if null String input
* @deprecated Use the relocated {@link WordUtils#capitalize(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static String capitaliseAllWords(String str) {
return WordUtils.capitalize(str);
}
// Count matches
/**
* <p>Counts how many times the substring appears in the larger String.</p>
*
* <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the String to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either String is <code>null</code>
*/
public static int countMatches(String str, String sub) {
if (str == null || str.length() == 0 || sub == null || sub.length() == 0) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
// Character Tests
/**
* <p>Checks if the String contains only unicode letters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = true
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains letters, and is non-null
*/
public static boolean isAlpha(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetter(str.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only unicode letters and
* space (' ').</p>
*
* <p><code>null</code> will return <code>false</code>
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains letters and space,
* and is non-null
*/
public static boolean isAlphaSpace(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only unicode letters or digits.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains letters or digits,
* and is non-null
*/
public static boolean isAlphanumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetterOrDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only unicode letters, digits
* or space (<code>' '</code>).</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = true
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = true
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains letters, digits or space,
* and is non-null
*/
public static boolean isAlphanumericSpace(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only unicode digits.
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
*/
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only unicode digits or space
* (<code>' '</code>).
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = true
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = true
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains digits or space,
* and is non-null
*/
public static boolean isNumericSpace(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the String contains only whitespace.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains whitespace, and is non-null
* @since 2.0
*/
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
// Defaults
/**
* <p>Returns either the passed in String,
* or if the String is <code>null</code>, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was <code>null</code>
*/
public static String defaultString(String str) {
return (str == null ? EMPTY : str);
}
/**
* <p>Returns either the passed in String,
* or if the String is <code>null</code>, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null, "null") = "null"
* StringUtils.defaultString("", "null") = ""
* StringUtils.defaultString("bat", "null") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is <code>null</code>, may be null
* @return the passed in String, or the default if it was <code>null</code>
*/
public static String defaultString(String str, String defaultStr) {
return (str == null ? defaultStr : str);
}
// Reversing
/**
* <p>Reverses a String as per {@link StringBuffer#reverse()}.</p>
*
* <p><A code>null</code> String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, <code>null</code> if null String input
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuffer(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is <code>'.'</code>).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, <code>null</code> if null String input
* @since 2.0
*/
public static String reverseDelimited(String str, char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is <code>"."</code>).</p>
*
* <pre>
* StringUtils.reverseDelimitedString(null, *) = null
* StringUtils.reverseDelimitedString("",*) = ""
* StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c"
* StringUtils.reverseDelimitedString("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChars the separator characters to use, null treated as whitespace
* @return the reversed String, <code>null</code> if null String input
* @deprecated Use {@link #reverseDelimited(String, char)} instead.
* This method is broken as the join doesn't know which char to use.
* Method will be removed in Commons Lang 3.0.
*
*/
public static String reverseDelimitedString(String str, String separatorChars) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChars);
ArrayUtils.reverse(strs);
if (separatorChars == null) {
return join(strs, ' ');
}
return join(strs, separatorChars);
}
// Abbreviating
public static String abbreviate(String str, int maxWidth) {
return abbreviate(str, 0, maxWidth);
}
public static String abbreviate(String str, int offset, int maxWidth) {
if (str == null) {
return null;
}
if (maxWidth < 4) {
throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if ((str.length() - offset) < (maxWidth - 3)) {
offset = str.length() - (maxWidth - 3);
}
if (offset <= 4) {
return str.substring(0, maxWidth - 3) + "...";
}
if (maxWidth < 7) {
throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
}
if ((offset + (maxWidth - 3)) < str.length()) {
return "..." + abbreviate(str.substring(offset), maxWidth - 3);
}
return "..." + str.substring(str.length() - (maxWidth - 3));
}
// Difference
/**
* <p>Compares two Strings, and returns the portion where they differ.
* (More precisely, return the remainder of the second String,
* starting from where it's different from the first.)</p>
*
* <p>For example,
* <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @since 2.0
*/
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int at = indexOfDifference(str1, str2);
if (at == -1) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Compares two Strings, and returns the index at which the
* Strings begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the index where str2 and str1 begin to differ; -1 if they are equal
* @since 2.0
*/
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2) {
return -1;
}
if (str1 == null || str2 == null) {
return 0;
}
int i;
for (i = 0; i < str1.length() && i < str2.length(); ++i) {
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
}
if (i < str2.length() || i < str1.length()) {
return i;
}
return -1;
}
// Misc
public static int getLevenshteinDistance(String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int d[][]; // matrix
int n; // length of s
int m; // length of t
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
// Step 1
n = s.length();
m = t.length();
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
d = new int[n + 1][m + 1];
// Step 2
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
// Step 3
for (i = 1; i <= n; i++) {
s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
// Step 5
if (s_i == t_j) {
cost = 0;
} else {
cost = 1;
}
// Step 6
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
}
}
// Step 7
return d[n][m];
}
/**
* <p>Gets the minimum of three <code>int</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
private static int min(int a, int b, int c) {
// Method copied from NumberUtils to avoid dependency on subpackage
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
}
|
package model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Kgram {
/**All of the k-grams and their mappings to words that match it*/
private HashMap <String, List<String>> k_gram;
public Kgram() {
k_gram = new HashMap<String, List<String>> ();
}
public void add(String term) {
// Add the dollar signs
term = "$" + term + "$";
for(int i = 1; i <= 3; i++) {
split(i,term);
}
}
public HashMap<String, List<String>> getKGram() {
return k_gram;
}
/**
* Splits the term into grams of k-size, and adds each term into the index.
* @param k The size of the gram
* @param term The term
*/
private void split(int k, String term) {
int i = 0;
// Split into grams and add into list then return list
while(i + k < term.length()) {
String key = "";
key = term.substring(i, i + k);
addKey(key, term);
i++;
}
}
/**
* Adds the gram and the term associated with it to the k-gram index.
* @param key The key for this term.
* @param term The term this key maps to.
*/
private void addKey(String key, String term) {
// Then check current k_gram hashmap to see if gram already exists
if(k_gram.containsKey(key)) {
// Check if k_gram's list contains term
if(!(k_gram.get(key)).contains(term)) {
(k_gram.get(key)).add(term);
}
}
else {
// Create a new list for k_gram and insert term into it
ArrayList <String> list = new ArrayList <String> ();
list.add(term);
k_gram.put(key, list);
}
}
public List<String> getTerms(String key) {
return k_gram.get(key);
}
}
|
package org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.sorter;
import java.util.Comparator;
import org.jetbrains.annotations.NotNull;
import org.mustbe.consulo.csharp.lang.psi.CSharpReferenceExpression;
import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpReferenceExpressionImplUtil;
import org.mustbe.consulo.csharp.lang.psi.resolve.CSharpElementGroup;
import org.mustbe.consulo.dotnet.psi.DotNetGenericParameterListOwner;
import org.mustbe.consulo.dotnet.psi.DotNetVariable;
import org.mustbe.consulo.dotnet.resolve.DotNetNamespaceAsElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.ResolveResult;
/**
* @author VISTALL
* @since 27.10.14
*/
public class TypeLikeComparator implements Comparator<ResolveResult>
{
@NotNull
public static TypeLikeComparator create(@NotNull PsiElement element)
{
int size = 0;
if(element instanceof CSharpReferenceExpression)
{
size = CSharpReferenceExpressionImplUtil.getTypeArgumentListSize((CSharpReferenceExpression) element);
}
return new TypeLikeComparator(size);
}
private final int myGenericCount;
public TypeLikeComparator(int genericCount)
{
myGenericCount = genericCount;
}
@Override
public int compare(ResolveResult o1, ResolveResult o2)
{
return getWeight(o2) - getWeight(o1);
}
public int getWeight(ResolveResult resolveResult)
{
PsiElement element = resolveResult.getElement();
if(element instanceof DotNetVariable || element instanceof CSharpElementGroup)
{
return 100000;
}
if(element instanceof DotNetGenericParameterListOwner)
{
if(((DotNetGenericParameterListOwner) element).getGenericParametersCount() == myGenericCount)
{
return 50000;
}
return -((DotNetGenericParameterListOwner) element).getGenericParametersCount() * 100;
}
if(element instanceof DotNetNamespaceAsElement)
{
return 0;
}
return 10;
}
}
|
package com.bazaarvoice.ostrich.dropwizard.healthcheck;
import com.bazaarvoice.ostrich.HealthCheckResult;
import com.bazaarvoice.ostrich.HealthCheckResults;
import com.bazaarvoice.ostrich.ServicePool;
import com.bazaarvoice.ostrich.pool.ServicePoolProxies;
import com.google.common.base.Strings;
import com.yammer.metrics.core.HealthCheck;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A simple health check that verifies a pool has a healthy end point. Will perform a health check on at least one end
* point, so beware the possibility of overloading your services with health checks if this is run excessively.
*/
public class ContainsHealthyEndPointCheck extends HealthCheck {
private final ServicePool<?> _pool;
/**
* @deprecated Use {@link #forPool(com.bazaarvoice.ostrich.ServicePool, String)} instead.
*/
public ContainsHealthyEndPointCheck(ServicePool<?> pool, String name) {
super(name);
checkArgument(!Strings.isNullOrEmpty(name));
_pool = checkNotNull(pool);
}
/**
* Returns a newly constructed health check for the given pool that will show as healthy if it has at least one healthy end point.
*
* @param pool The {@code ServicePool} to look for healthy end points in.
* @param name The name of the health check. May not be empty or null.
*/
public static ContainsHealthyEndPointCheck forPool(ServicePool<?> pool, String name) {
return new ContainsHealthyEndPointCheck(pool, name);
}
/**
* Returns a newly constructed health check for the pool of the given proxy that will show as healthy if
* it has at least one healthy end point.
*
* @param proxy The {@code ServicePoolProxy} containing the service pool to look for valid end points in.
* @param name The name of the health check. May not be empty or null.
*/
public static ContainsHealthyEndPointCheck forProxy(Object proxy, String name) {
return new ContainsHealthyEndPointCheck(ServicePoolProxies.getPool(proxy), name);
}
@Override
public Result check() throws Exception {
HealthCheckResults results = _pool.checkForHealthyEndPoint();
boolean healthy = results.hasHealthyResult();
HealthCheckResult healthyResult = results.getHealthyResult();
// Get stats about any failed health checks
int numUnhealthy = 0;
long totalUnhealthyResponseTimeInMicros = 0;
for (HealthCheckResult unhealthy : results.getUnhealthyResults()) {
++numUnhealthy;
totalUnhealthyResponseTimeInMicros += unhealthy.getResponseTime(TimeUnit.MICROSECONDS);
}
if (!healthy && numUnhealthy == 0) {
return Result.unhealthy("No end points.");
}
String unhealthyMessage = numUnhealthy + " failures in " + totalUnhealthyResponseTimeInMicros + "us";
if (!healthy) {
return Result.unhealthy(unhealthyMessage);
}
return Result.healthy(healthyResult.getEndPointId() + " succeeded in " +
healthyResult.getResponseTime(TimeUnit.MICROSECONDS) + "us; " + unhealthyMessage);
}
}
|
package graph;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.batik.dom.*;
import org.apache.batik.svggen.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.event.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.category.*;
import org.jfree.data.xy.*;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.w3c.dom.*;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import biomodelsim.*;
import buttons.*;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private String savedPics; // directory for saved pictures
private BioSim biomodelsim; // tstubd gui
private JButton save, saveAs;
private JButton export; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(String printer_track_quantity, String label, String printer_id, String outDir,
String time, BioSim biomodelsim, String open, Log log, String graphName, boolean timeSeries) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (timeSeries) {
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
topLevel = false;
}
}
else {
if (graphName != null) {
this.graphName = graphName;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset,
String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file, Component component) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
graphSpecies = new ArrayList<String>();
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha == '\''
|| cha == '(' || cha == ')' || cha == '[' || cha == ']') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
int read = 0;
while (read != -1) {
read = input.read();
}
}
}
catch (Exception e1) {
if (word.equals("")) {
}
else {
graphSpecies.add(word);
}
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
}
/**
* This private helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
private ArrayList<ArrayList<Double>> readData(String file, Component component,
String printer_track_quantity, String label, String directory) {
boolean warning = false;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if (label.contains("variance")) {
return calculateAverageVarianceDeviation(file, stem, 1, directory);
}
else if (label.contains("deviation")) {
return calculateAverageVarianceDeviation(file, stem, 2, directory);
}
else if (label.contains("average")) {
return calculateAverageVarianceDeviation(file, stem, 0, directory);
}
else {
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{'
|| cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*'
|| cha == '=' || cha == '
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
for (int i = 0; i < graphSpecies.size(); i++) {
data.add(new ArrayList<Double>());
}
(data.get(0)).add(0.0);
int counter = 1;
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (word.equals("nan")) {
if (!warning) {
JOptionPane.showMessageDialog(component, "Found NAN in data."
+ "\nReplacing with 0s.", "NAN In Data", JOptionPane.WARNING_MESSAGE);
warning = true;
}
word = "0";
}
if (counter < graphSpecies.size()) {
insert = counter;
}
else {
insert = counter % graphSpecies.size();
}
(data.get(insert)).add(Double.parseDouble(word));
counter++;
}
}
}
}
catch (Exception e1) {
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(series.getY(k).doubleValue(), maxY);
minY = Math.min(series.getY(k).doubleValue(), minY);
maxX = Math.max(series.getX(k).doubleValue(), maxX);
minX = Math.min(series.getX(k).doubleValue(), minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxY - minY) < .001) {
axis.setRange(minY - 1, maxY + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minY - (Math.abs(minY) * .1))), Double
.parseDouble(num.format(maxY + (Math.abs(maxY) * .1))));
}
axis.setAutoTickUnitSelection(true);
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxX - minX) < .001) {
axis.setRange(minX - 1, maxX + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minX)), Double.parseDouble(num.format(maxX)));
}
axis.setAutoTickUnitSelection(true);
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit the
* title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
colors.put("Red ", draw.getNextPaint());
colors.put("Blue ", draw.getNextPaint());
colors.put("Green ", draw.getNextPaint());
colors.put("Yellow ", draw.getNextPaint());
colors.put("Magenta ", draw.getNextPaint());
colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray (Light)", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
private void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3
&& file.substring(file.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-")) {
add = true;
}
else {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
for (int i = 1; i < files3.length; i++) {
String index = files3[i];
int j = i;
while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > 0) {
files3[j] = files3[j - 1];
j = j - 1;
}
files3[j] = index;
}
for (String getFile : files3) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
boolean add2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-")) {
add2 = true;
}
else {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
for (int i = 1; i < files2.length; i++) {
String index = files2[i];
int j = i;
while ((j > 0) && files2[j - 1].compareToIgnoreCase(index) > 0) {
files2[j] = files2[j - 1];
j = j - 1;
}
files2[j] = index;
}
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
DefaultMutableTreeNode d2 = new DefaultMutableTreeNode(f);
boolean add3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f2.contains("run-")) {
add3 = true;
}
else {
d2.add(new DefaultMutableTreeNode(f2.substring(0, f2.length() - 4)));
}
}
}
if (add3) {
d2.add(new DefaultMutableTreeNode("Average"));
d2.add(new DefaultMutableTreeNode("Variance"));
d2.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-"
+ (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
d2.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
d.add(d2);
}
}
}
if (add2) {
d.add(new DefaultMutableTreeNode("Average"));
d.add(new DefaultMutableTreeNode("Variance"));
d.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
d.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
simDir.add(d);
}
}
}
if (add) {
simDir.add(new DefaultMutableTreeNode("Average"));
simDir.add(new DefaultMutableTreeNode("Variance"));
simDir.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
simDir.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
// final JFrame f = new JFrame("Edit Graph");
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString()) && node.getParent() != null
&& !directories.contains(node.getParent().toString() + separator + node.toString())) {
selected = node.toString();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixGraphChoices(node.getParent().toString()));
}
else if (node.getParent().getParent() != null
&& directories.contains(node.getParent().getParent().toString() + separator
+ node.getParent().toString())) {
specPanel.add(fixGraphChoices(node.getParent().getParent().toString() + separator
+ node.getParent().toString()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (node.getParent().getParent() != null
&& directories.contains(node.getParent().getParent().toString() + separator
+ node.getParent().toString())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
node.getParent().getParent().toString() + separator
+ node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else if (node.getParent().getParent() != null
&& directories.contains(node.getParent().getParent().toString() + separator
+ node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else if (node.getParent().getParent() != null
&& directories.contains(node.getParent().getParent().toString() + separator
+ node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().getParent().toString() + separator
+ node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true; try {
* minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected =
* ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
* XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer)
* chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i <
* graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i;
* while ((j > 0) && (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); }
* ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
* HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if
* (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), null);
* for (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j =
* i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) >
* 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j,
* index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(),
* data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if (s.length() >
* 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } }
* catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int
* next = 1; while (!new File(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), null); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies( outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(),
* g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) {
* String index = graphSpecies.get(i); ArrayList<Double> index2 =
* data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; }
* graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) {
* ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new
* File(outDir + separator + g.getDirectory() + separator + "run-" + next +
* "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
* next++; } readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getDirectory() + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new
* XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) {
* dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(),
* x.getText().trim(), y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot();
* if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis =
* (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minY, maxY); axis.setTickUnit(new
* NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX);
* axis.setTickUnit(new NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
titlePanel2.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(resize);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
JPanel all = new JPanel(new BorderLayout());
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs "
+ "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
else {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connected");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Filled");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), colory
.get(colorsCombo.get(i).getSelectedItem()), filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i)
.getName(), series.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true,
true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
if (timeSeries) {
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
}
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
if (timeSeries) {
ButtonHolder.add(saveAs);
}
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
File file;
if (savedPics != null) {
file = new File(savedPics);
}
else {
file = null;
}
String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY,
"Export");
if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
savedPics = filename;
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile,
String fileStem, int choice, String directory) {
boolean warning = false;
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
try {
FileInputStream fileInput = new FileInputStream(new File(startFile));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From " + new File(startFile).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}'
|| cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '='
|| cha == '
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
boolean first = true;
int runsToMake = 1;
String[] findNum = startFile.split(separator);
String search = findNum[findNum.length - 1];
int firstOne = Integer.parseInt(search.substring(4, search.length() - 4));
if (directory == null) {
for (String f : new File(outDir).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
else {
for (String f : new File(outDir + separator + directory).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
(average.get(0)).add(0.0);
(variance.get(0)).add(0.0);
int count = 0;
int skip = firstOne;
for (int j = 0; j < runsToMake; j++) {
int counter = 1;
if (!first) {
if (firstOne != 1) {
j
firstOne = 1;
}
boolean loop = true;
while (loop && j < runsToMake && (j + 1) != skip) {
if (directory == null) {
if (new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + fileStem
+ (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
else {
if (new File(outDir + separator + directory + separator + fileStem + (j + 1)
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + directory
+ separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + directory + separator + fileStem
+ (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
}
}
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
first = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (word.equals("nan")) {
if (!warning) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Found NAN in data."
+ "\nReplacing with 0s.", "NAN In Data", JOptionPane.WARNING_MESSAGE);
warning = true;
}
word = "0";
}
if (first) {
if (counter < graphSpecies.size()) {
insert = counter;
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
else {
insert = counter % graphSpecies.size();
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
if (counter < graphSpecies.size()) {
insert = counter;
try {
double old = (average.get(insert)).get(insert / graphSpecies.size());
(average.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(insert / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(insert
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(insert / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
insert = counter % graphSpecies.size();
try {
double old = (average.get(insert)).get(counter / graphSpecies.size());
(average.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(counter / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(counter
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(counter / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
}
counter++;
}
}
}
}
}
catch (Exception e1) {
}
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
String graphName = JOptionPane.showInputDialog(biomodelsim.frame(), "Enter Graph Name:",
"Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
System.gc();
del.delete();
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir
.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir
.split(separator).length - 1]
+ "/" + graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.refreshTree();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)),
colors.get(graph.getProperty("species.paint." + next)), filled, visible, connected,
graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refresh();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
int next = 0;
while (graph.containsKey("species.name." + next)) {
probGraphed.add(new GraphProbs(colors.get(graph.getProperty("species.paint." + next)),
graph.getProperty("species.paint." + next), graph.getProperty("species.id." + next),
graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void refresh() {
if (timeSeries) {
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame(), chart.getXYPlot().getRangeAxis().getLabel(), g
.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), g
.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart
.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(),
chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend);
}
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, Paint p) {
shape = s;
paint = p;
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Color";
}
public void setPaint(String paint) {
this.paint = colors.get(paint);
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int number;
private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected,
String runNumber, String id, String species, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
public void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(),
PlotOrientation.VERTICAL, true, true, false);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt = true;
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
for (String f : new File(outDir + separator + file).list()) {
if (f.equals("sim-rep.txt")) {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
simDir.add(d);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString())) {
selected = node.toString();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixProbChoices(node.getParent().toString()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel2.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
JPanel all = new JPanel(new BorderLayout());
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Probability Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset,
rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
probGraphed.add(new GraphProbs(colory.get(colorsCombo.get(i).getSelectedItem()),
(String) colorsCombo.get(i).getSelectedItem(), boxes.get(i).getName(), series
.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
});
colorsCombo.add(colBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel,
DefaultCategoryDataset dataset, BarRenderer rend) {
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL,
true, true, false);
chart.getCategoryPlot().setRenderer(rend);
ChartPanel graph = new ChartPanel(chart);
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(),
chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend);
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number,
String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
}
}
|
package org.apache.lucene.store;
import java.io.IOException;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.lucene.util.Constants;
/**
* Straightforward implementation of {@link Directory} as a directory of files.
* <p>If the system property 'disableLuceneLocks' has the String value of
* "true", lock creation will be disabled.
*
* @see Directory
* @author Doug Cutting
*/
public final class FSDirectory extends Directory {
/** This cache of directories ensures that there is a unique Directory
* instance per path, so that synchronization on the Directory can be used to
* synchronize access between readers and writers.
*
* This should be a WeakHashMap, so that entries can be GC'd, but that would
* require Java 1.2. Instead we use refcounts...
*/
private static final Hashtable DIRECTORIES = new Hashtable();
private static final boolean DISABLE_LOCKS =
Boolean.getBoolean("disableLuceneLocks") || Constants.JAVA_1_1;
private static MessageDigest DIGESTER;
static {
try {
DIGESTER = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.toString());
}
}
/** A buffer optionally used in renameTo method */
private byte[] buffer = null;
/** Returns the directory instance for the named location.
*
* <p>Directories are cached, so that, for a given canonical path, the same
* FSDirectory instance will always be returned. This permits
* synchronization on directories.
*
* @param path the path to the directory.
* @param create if true, create, or erase any existing contents.
* @return the FSDirectory for the named file. */
public static FSDirectory getDirectory(String path, boolean create)
throws IOException {
return getDirectory(new File(path), create);
}
/** Returns the directory instance for the named location.
*
* <p>Directories are cached, so that, for a given canonical path, the same
* FSDirectory instance will always be returned. This permits
* synchronization on directories.
*
* @param file the path to the directory.
* @param create if true, create, or erase any existing contents.
* @return the FSDirectory for the named file. */
public static FSDirectory getDirectory(File file, boolean create)
throws IOException {
file = new File(file.getCanonicalPath());
FSDirectory dir;
synchronized (DIRECTORIES) {
dir = (FSDirectory)DIRECTORIES.get(file);
if (dir == null) {
dir = new FSDirectory(file, create);
DIRECTORIES.put(file, dir);
} else if (create) {
dir.create();
}
}
synchronized (dir) {
dir.refCount++;
}
return dir;
}
private File directory = null;
private int refCount;
private FSDirectory(File path, boolean create) throws IOException {
directory = path;
if (create)
create();
if (!directory.isDirectory())
throw new IOException(path + " not a directory");
}
private synchronized void create() throws IOException {
if (!directory.exists())
if (!directory.mkdir())
throw new IOException("Cannot create directory: " + directory);
String[] files = directory.list(); // clear old files
for (int i = 0; i < files.length; i++) {
File file = new File(directory, files[i]);
if (!file.delete())
throw new IOException("couldn't delete " + files[i]);
}
String lockPrefix = getLockPrefix().toString(); // clear old locks
File tmpdir = new File(System.getProperty("java.io.tmpdir"));
files = tmpdir.list();
for (int i = 0; i < files.length; i++) {
if (!files[i].startsWith(lockPrefix))
continue;
File file = new File(tmpdir, files[i]);
if (!file.delete())
throw new IOException("couldn't delete " + files[i]);
}
}
/** Returns an array of strings, one for each file in the directory. */
public final String[] list() throws IOException {
return directory.list();
}
/** Returns true iff a file with the given name exists. */
public final boolean fileExists(String name) throws IOException {
File file = new File(directory, name);
return file.exists();
}
/** Returns the time the named file was last modified. */
public final long fileModified(String name) throws IOException {
File file = new File(directory, name);
return file.lastModified();
}
/** Returns the time the named file was last modified. */
public static final long fileModified(File directory, String name)
throws IOException {
File file = new File(directory, name);
return file.lastModified();
}
/** Set the modified time of an existing file to now. */
public void touchFile(String name) throws IOException {
File file = new File(directory, name);
file.setLastModified(System.currentTimeMillis());
}
/** Returns the length in bytes of a file in the directory. */
public final long fileLength(String name) throws IOException {
File file = new File(directory, name);
return file.length();
}
/** Removes an existing file in the directory. */
public final void deleteFile(String name) throws IOException {
File file = new File(directory, name);
if (!file.delete())
throw new IOException("couldn't delete " + name);
}
/** Renames an existing file in the directory. */
public final synchronized void renameFile(String from, String to)
throws IOException {
File old = new File(directory, from);
File nu = new File(directory, to);
/* This is not atomic. If the program crashes between the call to
delete() and the call to renameTo() then we're screwed, but I've
been unable to figure out how else to do this... */
if (nu.exists())
if (!nu.delete())
throw new IOException("couldn't delete " + to);
// Rename the old file to the new one. Unfortunately, the renameTo()
// method does not work reliably under some JVMs. Therefore, if the
// rename fails, we manually rename by copying the old file to the new one
if (!old.renameTo(nu)) {
java.io.InputStream in = null;
java.io.OutputStream out = null;
try {
in = new FileInputStream(old);
out = new FileOutputStream(nu);
// see if the buffer needs to be initialized. Initialization is
// only done on-demand since many VM's will never run into the renameTo
// bug and hence shouldn't waste 1K of mem for no reason.
if (buffer == null) {
buffer = new byte[1024];
}
int len;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
// delete the old file.
old.delete();
}
catch (IOException ioe) {
throw new IOException("couldn't rename " + from + " to " + to);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("could not close input stream: " + e.getMessage());
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException("could not close output stream: " + e.getMessage());
}
}
}
}
}
/** Creates a new, empty file in the directory with the given name.
Returns a stream writing this file. */
public final OutputStream createFile(String name) throws IOException {
return new FSOutputStream(new File(directory, name));
}
/** Returns a stream reading an existing file. */
public final InputStream openFile(String name) throws IOException {
return new FSInputStream(new File(directory, name));
}
/**
* So we can do some byte-to-hexchar conversion below
*/
private static final char[] HEX_DIGITS =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
/** Constructs a {@link Lock} with the specified name. Locks are implemented
* with {@link File#createNewFile() }.
*
* <p>In JDK 1.1 or if system property <I>disableLuceneLocks</I> is the
* string "true", locks are disabled. Assigning this property any other
* string will <B>not</B> prevent creation of lock files. This is useful for
* using Lucene on read-only medium, such as CD-ROM.
*
* @param name the name of the lock file
* @return an instance of <code>Lock</code> holding the lock
*/
public final Lock makeLock(String name) {
StringBuffer buf = getLockPrefix();
buf.append("-");
buf.append(name);
// make the lock file in tmp, where anyone can create files.
final File lockFile = new File(System.getProperty("java.io.tmpdir"),
buf.toString());
return new Lock() {
public boolean obtain() throws IOException {
if (DISABLE_LOCKS)
return true;
return lockFile.createNewFile();
}
public void release() {
if (DISABLE_LOCKS)
return;
lockFile.delete();
}
public boolean isLocked() {
if (DISABLE_LOCKS)
return false;
return lockFile.exists();
}
public String toString() {
return "Lock@" + lockFile;
}
};
}
private StringBuffer getLockPrefix() {
String dirName; // name to be hashed
try {
dirName = directory.getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
byte digest[];
synchronized (DIGESTER) {
digest = DIGESTER.digest(dirName.getBytes());
}
StringBuffer buf = new StringBuffer();
buf.append("lucene-");
for (int i = 0; i < digest.length; i++) {
int b = digest[i];
buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.append(HEX_DIGITS[b & 0xf]);
}
return buf;
}
/** Closes the store to future operations. */
public final synchronized void close() throws IOException {
if (--refCount <= 0) {
synchronized (DIRECTORIES) {
DIRECTORIES.remove(directory);
}
}
}
/** For debug output. */
public String toString() {
return "FSDirectory@" + directory;
}
}
final class FSInputStream extends InputStream {
private class Descriptor extends RandomAccessFile {
public long position;
public Descriptor(File file, String mode) throws IOException {
super(file, mode);
}
}
Descriptor file = null;
boolean isClone;
public FSInputStream(File path) throws IOException {
file = new Descriptor(path, "r");
length = file.length();
}
/** InputStream methods */
protected final void readInternal(byte[] b, int offset, int len)
throws IOException {
synchronized (file) {
long position = getFilePointer();
if (position != file.position) {
file.seek(position);
file.position = position;
}
int total = 0;
do {
int i = file.read(b, offset+total, len-total);
if (i == -1)
throw new IOException("read past EOF");
file.position += i;
total += i;
} while (total < len);
}
}
public final void close() throws IOException {
if (!isClone)
file.close();
}
/** Random-access methods */
protected final void seekInternal(long position) throws IOException {
}
protected final void finalize() throws IOException {
close(); // close the file
}
public Object clone() {
FSInputStream clone = (FSInputStream)super.clone();
clone.isClone = true;
return clone;
}
}
final class FSOutputStream extends OutputStream {
RandomAccessFile file = null;
public FSOutputStream(File path) throws IOException {
file = new RandomAccessFile(path, "rw");
}
/** output methods: */
public final void flushBuffer(byte[] b, int size) throws IOException {
file.write(b, 0, size);
}
public final void close() throws IOException {
super.close();
file.close();
}
/** Random-access methods */
public final void seek(long pos) throws IOException {
super.seek(pos);
file.seek(pos);
}
public final long length() throws IOException {
return file.length();
}
protected final void finalize() throws IOException {
file.close(); // close the file
}
}
|
package com.oracle.graal.phases.common.inlining.walker;
import com.oracle.graal.api.code.Assumptions;
import com.oracle.graal.api.code.BailoutException;
import com.oracle.graal.api.meta.JavaTypeProfile;
import com.oracle.graal.api.meta.ResolvedJavaMethod;
import com.oracle.graal.api.meta.ResolvedJavaType;
import com.oracle.graal.compiler.common.GraalInternalError;
import com.oracle.graal.compiler.common.type.ObjectStamp;
import com.oracle.graal.debug.Debug;
import com.oracle.graal.debug.DebugMetric;
import com.oracle.graal.graph.Graph;
import com.oracle.graal.graph.Node;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.java.MethodCallTargetNode;
import com.oracle.graal.nodes.spi.Replacements;
import com.oracle.graal.phases.OptimisticOptimizations;
import com.oracle.graal.phases.common.CanonicalizerPhase;
import com.oracle.graal.phases.common.inlining.InliningUtil;
import com.oracle.graal.phases.common.inlining.info.*;
import com.oracle.graal.phases.common.inlining.policy.InliningPolicy;
import com.oracle.graal.phases.graph.FixedNodeProbabilityCache;
import com.oracle.graal.phases.tiers.HighTierContext;
import com.oracle.graal.phases.util.Providers;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleFunction;
import static com.oracle.graal.compiler.common.GraalOptions.MegamorphicInliningMinMethodProbability;
import static com.oracle.graal.compiler.common.GraalOptions.OptCanonicalizer;
/**
* Holds the data for building the callee graphs recursively: graphs and invocations (each
* invocation can have multiple graphs).
*/
public class InliningData {
private static final CallsiteHolder DUMMY_CALLSITE_HOLDER = new CallsiteHolder(null, 1.0, 1.0);
// Metrics
private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed");
private static final DebugMetric metricInliningRuns = Debug.metric("InliningRuns");
private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered");
/**
* Call hierarchy from outer most call (i.e., compilation unit) to inner most callee.
*/
private final ArrayDeque<CallsiteHolder> graphQueue = new ArrayDeque<>();
private final ArrayDeque<MethodInvocation> invocationQueue = new ArrayDeque<>();
private final ToDoubleFunction<FixedNode> probabilities = new FixedNodeProbabilityCache();
private final HighTierContext context;
private final int maxMethodPerInlining;
private final CanonicalizerPhase canonicalizer;
private final InliningPolicy inliningPolicy;
private int maxGraphs;
public InliningData(StructuredGraph rootGraph, HighTierContext context, int maxMethodPerInlining, CanonicalizerPhase canonicalizer, InliningPolicy inliningPolicy) {
assert rootGraph != null;
this.context = context;
this.maxMethodPerInlining = maxMethodPerInlining;
this.canonicalizer = canonicalizer;
this.inliningPolicy = inliningPolicy;
this.maxGraphs = 1;
Assumptions rootAssumptions = context.getAssumptions();
invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0));
pushGraph(rootGraph, 1.0, 1.0);
}
/**
* Determines if inlining is possible at the given invoke node.
*
* @param invoke the invoke that should be inlined
* @return an instance of InlineInfo, or null if no inlining is possible at the given invoke
*/
public InlineInfo getInlineInfo(Invoke invoke, Replacements replacements, Assumptions assumptions, OptimisticOptimizations optimisticOpts) {
final String failureMessage = InliningUtil.checkInvokeConditions(invoke);
if (failureMessage != null) {
InliningUtil.logNotInlinedMethod(invoke, failureMessage);
return null;
}
MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget();
ResolvedJavaMethod targetMethod = callTarget.targetMethod();
if (callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Special || targetMethod.canBeStaticallyBound()) {
return getExactInlineInfo(invoke, replacements, optimisticOpts, targetMethod);
}
assert callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Virtual || callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Interface;
ResolvedJavaType holder = targetMethod.getDeclaringClass();
if (!(callTarget.receiver().stamp() instanceof ObjectStamp)) {
return null;
}
ObjectStamp receiverStamp = (ObjectStamp) callTarget.receiver().stamp();
if (receiverStamp.alwaysNull()) {
// Don't inline if receiver is known to be null
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
if (receiverStamp.type() != null) {
// the invoke target might be more specific than the holder (happens after inlining:
// parameters lose their declared type...)
ResolvedJavaType receiverType = receiverStamp.type();
if (receiverType != null && holder.isAssignableFrom(receiverType)) {
holder = receiverType;
if (receiverStamp.isExactType()) {
assert targetMethod.getDeclaringClass().isAssignableFrom(holder) : holder + " subtype of " + targetMethod.getDeclaringClass() + " for " + targetMethod;
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, replacements, optimisticOpts, resolvedMethod);
}
}
}
}
if (holder.isArray()) {
// arrays can be treated as Objects
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, replacements, optimisticOpts, resolvedMethod);
}
}
if (assumptions.useOptimisticAssumptions()) {
ResolvedJavaType uniqueSubtype = holder.findUniqueConcreteSubtype();
if (uniqueSubtype != null) {
ResolvedJavaMethod resolvedMethod = uniqueSubtype.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getAssumptionInlineInfo(invoke, replacements, optimisticOpts, resolvedMethod, new Assumptions.ConcreteSubtype(holder, uniqueSubtype));
}
}
ResolvedJavaMethod concrete = holder.findUniqueConcreteMethod(targetMethod);
if (concrete != null) {
return getAssumptionInlineInfo(invoke, replacements, optimisticOpts, concrete, new Assumptions.ConcreteMethod(targetMethod, holder, concrete));
}
}
// type check based inlining
return getTypeCheckedInlineInfo(invoke, maxMethodPerInlining, replacements, targetMethod, optimisticOpts);
}
public InlineInfo getTypeCheckedInlineInfo(Invoke invoke, int maxNumberOfMethods, Replacements replacements, ResolvedJavaMethod targetMethod, OptimisticOptimizations optimisticOpts) {
JavaTypeProfile typeProfile;
ValueNode receiver = invoke.callTarget().arguments().get(0);
if (receiver instanceof TypeProfileProxyNode) {
TypeProfileProxyNode typeProfileProxyNode = (TypeProfileProxyNode) receiver;
typeProfile = typeProfileProxyNode.getProfile();
} else {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no type profile exists");
return null;
}
JavaTypeProfile.ProfiledType[] ptypes = typeProfile.getTypes();
if (ptypes == null || ptypes.length <= 0) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no types in profile");
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
double notRecordedTypeProbability = typeProfile.getNotRecordedProbability();
if (ptypes.length == 1 && notRecordedTypeProbability == 0) {
if (!optimisticOpts.inlineMonomorphicCalls()) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "inlining monomorphic calls is disabled");
return null;
}
ResolvedJavaType type = ptypes[0].getType();
assert type.isArray() || !type.isAbstract();
ResolvedJavaMethod concrete = type.resolveMethod(targetMethod, contextType);
if (!InliningUtil.checkTargetConditions(this, replacements, invoke, concrete, optimisticOpts)) {
return null;
}
return new TypeGuardInlineInfo(invoke, concrete, type);
} else {
invoke.setPolymorphic(true);
if (!optimisticOpts.inlinePolymorphicCalls() && notRecordedTypeProbability == 0) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining polymorphic calls is disabled (%d types)", ptypes.length);
return null;
}
if (!optimisticOpts.inlineMegamorphicCalls() && notRecordedTypeProbability > 0) {
// due to filtering impossible types, notRecordedTypeProbability can be > 0 although
// the number of types is lower than what can be recorded in a type profile
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining megamorphic calls is disabled (%d types, %f %% not recorded types)", ptypes.length,
notRecordedTypeProbability * 100);
return null;
}
// Find unique methods and their probabilities.
ArrayList<ResolvedJavaMethod> concreteMethods = new ArrayList<>();
ArrayList<Double> concreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < ptypes.length; i++) {
ResolvedJavaMethod concrete = ptypes[i].getType().resolveMethod(targetMethod, contextType);
if (concrete == null) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "could not resolve method");
return null;
}
int index = concreteMethods.indexOf(concrete);
double curProbability = ptypes[i].getProbability();
if (index < 0) {
index = concreteMethods.size();
concreteMethods.add(concrete);
concreteMethodsProbabilities.add(curProbability);
} else {
concreteMethodsProbabilities.set(index, concreteMethodsProbabilities.get(index) + curProbability);
}
}
if (concreteMethods.size() > maxNumberOfMethods) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "polymorphic call with more than %d target methods", maxNumberOfMethods);
return null;
}
// Clear methods that fall below the threshold.
if (notRecordedTypeProbability > 0) {
ArrayList<ResolvedJavaMethod> newConcreteMethods = new ArrayList<>();
ArrayList<Double> newConcreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < concreteMethods.size(); ++i) {
if (concreteMethodsProbabilities.get(i) >= MegamorphicInliningMinMethodProbability.getValue()) {
newConcreteMethods.add(concreteMethods.get(i));
newConcreteMethodsProbabilities.add(concreteMethodsProbabilities.get(i));
}
}
if (newConcreteMethods.size() == 0) {
// No method left that is worth inlining.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no methods remaining after filtering less frequent methods (%d methods previously)",
concreteMethods.size());
return null;
}
concreteMethods = newConcreteMethods;
concreteMethodsProbabilities = newConcreteMethodsProbabilities;
}
// Clean out types whose methods are no longer available.
ArrayList<JavaTypeProfile.ProfiledType> usedTypes = new ArrayList<>();
ArrayList<Integer> typesToConcretes = new ArrayList<>();
for (JavaTypeProfile.ProfiledType type : ptypes) {
ResolvedJavaMethod concrete = type.getType().resolveMethod(targetMethod, contextType);
int index = concreteMethods.indexOf(concrete);
if (index == -1) {
notRecordedTypeProbability += type.getProbability();
} else {
assert type.getType().isArray() || !type.getType().isAbstract() : type + " " + concrete;
usedTypes.add(type);
typesToConcretes.add(index);
}
}
if (usedTypes.size() == 0) {
// No type left that is worth checking for.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no types remaining after filtering less frequent types (%d types previously)", ptypes.length);
return null;
}
for (ResolvedJavaMethod concrete : concreteMethods) {
if (!InliningUtil.checkTargetConditions(this, replacements, invoke, concrete, optimisticOpts)) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "it is a polymorphic method call and at least one invoked method cannot be inlined");
return null;
}
}
return new MultiTypeGuardInlineInfo(invoke, concreteMethods, concreteMethodsProbabilities, usedTypes, typesToConcretes, notRecordedTypeProbability);
}
}
public InlineInfo getAssumptionInlineInfo(Invoke invoke, Replacements replacements, OptimisticOptimizations optimisticOpts, ResolvedJavaMethod concrete, Assumptions.Assumption takenAssumption) {
assert !concrete.isAbstract();
if (!InliningUtil.checkTargetConditions(this, replacements, invoke, concrete, optimisticOpts)) {
return null;
}
return new AssumptionInlineInfo(invoke, concrete, takenAssumption);
}
public InlineInfo getExactInlineInfo(Invoke invoke, Replacements replacements, OptimisticOptimizations optimisticOpts, ResolvedJavaMethod targetMethod) {
assert !targetMethod.isAbstract();
if (!InliningUtil.checkTargetConditions(this, replacements, invoke, targetMethod, optimisticOpts)) {
return null;
}
return new ExactInlineInfo(invoke, targetMethod);
}
private void doInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, Assumptions callerAssumptions) {
StructuredGraph callerGraph = callerCallsiteHolder.graph();
Graph.Mark markBeforeInlining = callerGraph.getMark();
InlineInfo callee = calleeInfo.callee();
try {
try (Debug.Scope scope = Debug.scope("doInline", callerGraph)) {
List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot();
callee.inline(new Providers(context), callerAssumptions);
callerAssumptions.record(calleeInfo.assumptions());
metricInliningRuns.increment();
Debug.dump(callerGraph, "after %s", callee);
if (OptCanonicalizer.getValue()) {
Graph.Mark markBeforeCanonicalization = callerGraph.getMark();
canonicalizer.applyIncremental(callerGraph, context, invokeUsages, markBeforeInlining);
// process invokes that are possibly created during canonicalization
for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) {
if (newNode instanceof Invoke) {
callerCallsiteHolder.pushInvoke((Invoke) newNode);
}
}
}
callerCallsiteHolder.computeProbabilities();
metricInliningPerformed.increment();
}
} catch (BailoutException bailout) {
throw bailout;
} catch (AssertionError | RuntimeException e) {
throw new GraalInternalError(e).addContext(callee.toString());
} catch (GraalInternalError e) {
throw e.addContext(callee.toString());
}
}
/**
* @return true iff inlining was actually performed
*/
private boolean tryToInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, MethodInvocation parentInvocation, int inliningDepth) {
InlineInfo callee = calleeInfo.callee();
Assumptions callerAssumptions = parentInvocation.assumptions();
metricInliningConsidered.increment();
if (inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), callee, inliningDepth, calleeInfo.probability(), calleeInfo.relevance(), true)) {
doInline(callerCallsiteHolder, calleeInfo, callerAssumptions);
return true;
}
if (context.getOptimisticOptimizations().devirtualizeInvokes()) {
callee.tryToDevirtualizeInvoke(context.getMetaAccess(), callerAssumptions);
}
return false;
}
/**
* Process the next invoke and enqueue all its graphs for processing.
*/
void processNextInvoke() {
CallsiteHolder callsiteHolder = currentGraph();
Invoke invoke = callsiteHolder.popInvoke();
MethodInvocation callerInvocation = currentInvocation();
Assumptions parentAssumptions = callerInvocation.assumptions();
InlineInfo info = getInlineInfo(invoke, context.getReplacements(), parentAssumptions, context.getOptimisticOptimizations());
if (info != null) {
double invokeProbability = callsiteHolder.invokeProbability(invoke);
double invokeRelevance = callsiteHolder.invokeRelevance(invoke);
MethodInvocation calleeInvocation = pushInvocation(info, parentAssumptions, invokeProbability, invokeRelevance);
for (int i = 0; i < info.numberOfMethods(); i++) {
InliningUtil.Inlineable elem = DepthSearchUtil.getInlineableElement(info.methodAt(i), info.invoke(), context.replaceAssumptions(calleeInvocation.assumptions()), canonicalizer);
info.setInlinableElement(i, elem);
if (elem instanceof InliningUtil.InlineableGraph) {
pushGraph(((InliningUtil.InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i));
} else {
assert elem instanceof InliningUtil.InlineableMacroNode;
pushDummyGraph();
}
}
}
}
public int graphCount() {
return graphQueue.size();
}
private void pushGraph(StructuredGraph graph, double probability, double relevance) {
assert graph != null;
assert !contains(graph);
graphQueue.push(new CallsiteHolder(graph, probability, relevance));
assert graphQueue.size() <= maxGraphs;
}
private void pushDummyGraph() {
graphQueue.push(DUMMY_CALLSITE_HOLDER);
}
public boolean hasUnprocessedGraphs() {
return !graphQueue.isEmpty();
}
public CallsiteHolder currentGraph() {
return graphQueue.peek();
}
public void popGraph() {
graphQueue.pop();
assert graphQueue.size() <= maxGraphs;
}
public void popGraphs(int count) {
assert count >= 0;
for (int i = 0; i < count; i++) {
graphQueue.pop();
}
}
private static final Object[] NO_CONTEXT = {};
/**
* Gets the call hierarchy of this inlining from outer most call to inner most callee.
*/
public Object[] inliningContext() {
if (!Debug.isDumpEnabled()) {
return NO_CONTEXT;
}
Object[] result = new Object[graphQueue.size()];
int i = 0;
for (CallsiteHolder g : graphQueue) {
result[i++] = g.method();
}
return result;
}
public MethodInvocation currentInvocation() {
return invocationQueue.peekFirst();
}
private MethodInvocation pushInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
MethodInvocation methodInvocation = new MethodInvocation(info, new Assumptions(assumptions.useOptimisticAssumptions()), probability, relevance);
invocationQueue.addFirst(methodInvocation);
maxGraphs += info.numberOfMethods();
assert graphQueue.size() <= maxGraphs;
return methodInvocation;
}
public void popInvocation() {
maxGraphs -= invocationQueue.peekFirst().callee().numberOfMethods();
assert graphQueue.size() <= maxGraphs;
invocationQueue.removeFirst();
}
public int countRecursiveInlining(ResolvedJavaMethod method) {
int count = 0;
for (CallsiteHolder callsiteHolder : graphQueue) {
if (method.equals(callsiteHolder.method())) {
count++;
}
}
return count;
}
public int inliningDepth() {
assert invocationQueue.size() > 0;
return invocationQueue.size() - 1;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("Invocations: ");
for (MethodInvocation invocation : invocationQueue) {
if (invocation.callee() != null) {
result.append(invocation.callee().numberOfMethods());
result.append("x ");
result.append(invocation.callee().invoke());
result.append("; ");
}
}
result.append("\nGraphs: ");
for (CallsiteHolder graph : graphQueue) {
result.append(graph.graph());
result.append("; ");
}
return result.toString();
}
private boolean contains(StructuredGraph graph) {
for (CallsiteHolder info : graphQueue) {
if (info.graph() == graph) {
return true;
}
}
return false;
}
/**
* @return true iff inlining was actually performed
*/
public boolean moveForward() {
final MethodInvocation currentInvocation = currentInvocation();
final boolean backtrack = (!currentInvocation.isRoot() && !inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), currentInvocation.callee(), inliningDepth(),
currentInvocation.probability(), currentInvocation.relevance(), false));
if (backtrack) {
int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs();
assert remainingGraphs > 0;
popGraphs(remainingGraphs);
popInvocation();
return false;
}
final boolean delve = currentGraph().hasRemainingInvokes() && inliningPolicy.continueInlining(currentGraph().graph());
if (delve) {
processNextInvoke();
return false;
}
popGraph();
if (currentInvocation.isRoot()) {
return false;
}
// try to inline
assert currentInvocation.callee().invoke().asNode().isAlive();
currentInvocation.incrementProcessedGraphs();
if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) {
popInvocation();
final MethodInvocation parentInvoke = currentInvocation();
try (Debug.Scope s = Debug.scope("Inlining", inliningContext())) {
return tryToInline(currentGraph(), currentInvocation, parentInvoke, inliningDepth() + 1);
} catch (Throwable e) {
throw Debug.handle(e);
}
}
return false;
}
}
|
package reb2sac;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.swing.*;
import parser.*;
import lhpn2sbml.gui.LHPNEditor;
import lhpn2sbml.parser.Abstraction;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Translator;
import gillespieSSAjava.GillespieSSAJavaSingleStep;
import biomodelsim.*;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.util.GlobalConstants;
import graph.*;
import buttons.*;
import sbmleditor.*;
import stategraph.BuildStateGraphThread;
import stategraph.PerfromSteadyStateMarkovAnalysisThread;
import stategraph.PerfromTransientMarkovAnalysisThread;
import stategraph.StateGraph;
import verification.AbstPane;
/**
* This class creates the properties file that is given to the reb2sac program.
* It also executes the reb2sac program.
*
* @author Curtis Madsen
*/
public class Run implements ActionListener {
private Process reb2sac;
private String separator;
private Reb2Sac r2s;
StateGraph sg;
public Run(Reb2Sac reb2sac) {
r2s = reb2sac;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
}
/**
* This method is given which buttons are selected and creates the
* properties file from all the other information given.
*
* @param useInterval
*
* @param stem
*/
public void createProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, double absError, String outDir, long rndSeed,
int run, String[] termCond, String[] intSpecies, String printer_id,
String printer_track_quantity, String[] getFilename, String selectedButtons,
Component component, String filename, double rap1, double rap2, double qss, int con,
JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs,
JList loopAbs, JList postAbs, AbstPane abstPane) {
Properties abs = new Properties();
if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) {
for (int i = 0; i < preAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs
.getModel().getElementAt(i));
}
for (int i = 0; i < loopAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs
.getModel().getElementAt(i));
}
// abs.setProperty("reb2sac.abstraction.method.0.1",
// "enzyme-kinetic-qssa-1");
// abs.setProperty("reb2sac.abstraction.method.0.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.0.3",
// "multiple-products-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.4",
// "multiple-reactants-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.5",
// "single-reactant-product-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.6",
// "dimer-to-monomer-substitutor");
// abs.setProperty("reb2sac.abstraction.method.0.7",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.1",
// "modifier-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.2",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.1",
// "operator-site-forward-binding-remover");
// abs.setProperty("reb2sac.abstraction.method.2.3",
// "enzyme-kinetic-rapid-equilibrium-1");
// abs.setProperty("reb2sac.abstraction.method.2.4",
// "irrelevant-species-remover");
// abs.setProperty("reb2sac.abstraction.method.2.5",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.2.6",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.7",
// "similar-reaction-combiner");
// abs.setProperty("reb2sac.abstraction.method.2.8",
// "modifier-constant-propagation");
}
// if (selectedButtons.contains("abs")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction");
// else if (selectedButtons.contains("nary")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction-level-assignment");
for (int i = 0; i < postAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel()
.getElementAt(i));
}
abs.setProperty("simulation.printer", printer_id);
abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
// if (selectedButtons.contains("monteCarlo")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "distribute-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.3",
// "kinetic-law-constants-simplifier");
// else if (selectedButtons.contains("none")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "kinetic-law-constants-simplifier");
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]);
if (split.length > 1) {
String[] levels = split[1].split(",");
for (int j = 0; j < levels.length; j++) {
abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1),
levels[j]);
}
}
}
}
abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
abs.setProperty("reb2sac.qssa.condition.1", "" + qss);
abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
if (selectedButtons.contains("none")) {
abs.setProperty("reb2sac.abstraction.method", "none");
}
if (selectedButtons.contains("abs")) {
abs.setProperty("reb2sac.abstraction.method", "abs");
}
else if (selectedButtons.contains("nary")) {
abs.setProperty("reb2sac.abstraction.method", "nary");
}
if (abstPane != null) {
for (Integer i = 0; i < abstPane.preAbsModel.size(); i++) {
abs
.setProperty("abstraction.transform."
+ abstPane.preAbsModel.getElementAt(i).toString(), "preloop"
+ i.toString());
}
for (Integer i = 0; i < abstPane.loopAbsModel.size(); i++) {
if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) {
String value = abs
.getProperty(abstPane.loopAbsModel.getElementAt(i).toString());
value = value + "mainloop" + i.toString();
abs.setProperty("abstraction.transform."
+ abstPane.loopAbsModel.getElementAt(i).toString(), value);
}
else {
abs.setProperty("abstraction.transform."
+ abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop"
+ i.toString());
}
}
for (Integer i = 0; i < abstPane.postAbsModel.size(); i++) {
if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i))
|| abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) {
String value = abs
.getProperty(abstPane.postAbsModel.getElementAt(i).toString());
value = value + "postloop" + i.toString();
abs.setProperty("abstraction.transform."
+ abstPane.postAbsModel.getElementAt(i).toString(), value);
}
else {
abs.setProperty("abstraction.transform."
+ abstPane.postAbsModel.getElementAt(i).toString(), "postloop"
+ i.toString());
}
}
for (String s : abstPane.transforms) {
if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s)
&& !abstPane.postAbsModel.contains(s)) {
abs.remove(s);
}
}
}
if (selectedButtons.contains("ODE")) {
abs.setProperty("reb2sac.simulation.method", "ODE");
}
else if (selectedButtons.contains("monteCarlo")) {
abs.setProperty("reb2sac.simulation.method", "monteCarlo");
}
else if (selectedButtons.contains("markov")) {
abs.setProperty("reb2sac.simulation.method", "markov");
}
else if (selectedButtons.contains("sbml")) {
abs.setProperty("reb2sac.simulation.method", "SBML");
}
else if (selectedButtons.contains("dot")) {
abs.setProperty("reb2sac.simulation.method", "Network");
}
else if (selectedButtons.contains("xhtml")) {
abs.setProperty("reb2sac.simulation.method", "Browser");
}
else if (selectedButtons.contains("lhpn")) {
abs.setProperty("reb2sac.simulation.method", "LPN");
}
if (!selectedButtons.contains("monteCarlo")) {
// if (selectedButtons.equals("none_ODE") ||
// selectedButtons.equals("abs_ODE")) {
abs.setProperty("ode.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("ode.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval);
}
else {
abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("ode.simulation.time.step", "inf");
}
else {
abs.setProperty("ode.simulation.time.step", "" + timeStep);
}
abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("ode.simulation.absolute.error", "" + absError);
abs.setProperty("ode.simulation.out.dir", outDir);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
}
if (!selectedButtons.contains("ODE")) {
// if (selectedButtons.equals("none_monteCarlo") ||
// selectedButtons.equals("abs_monteCarlo")) {
abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs
.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
abs.setProperty("monte.carlo.simulation.out.dir", outDir);
if (usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "sad");
abs.setProperty("computation.analysis.sad.path", sadFile.getName());
}
}
if (!usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "constraint");
}
if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) {
abs.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
abs
.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
if (!getFilename[getFilename.length - 1].contains(".")) {
getFilename[getFilename.length - 1] += ".";
filename += ".";
}
int cut = 0;
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename
.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties"));
abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for abstraction.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method is given what data is entered into the nary frame and creates
* the nary properties file from that information.
*/
public void createNaryProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, String outDir, long rndSeed, int run,
String printer_id, String printer_track_quantity, String[] getFilename,
Component component, String filename, JRadioButton monteCarlo, String stopE,
double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel,
ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond,
String[] intSpecies, double rap1, double rap2, double qss, int con,
ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) {
Properties nary = new Properties();
try {
FileInputStream load = new FileInputStream(new File(outDir + separator
+ "species.properties"));
nary.load(load);
load.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Species Properties File Not Found!",
"File Not Found", JOptionPane.ERROR_MESSAGE);
}
nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1");
nary
.setProperty("reb2sac.abstraction.method.0.2",
"reversible-to-irreversible-transformer");
nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator");
nary
.setProperty("reb2sac.abstraction.method.0.4",
"multiple-reactants-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.5",
"single-reactant-product-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor");
nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover");
nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1");
nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover");
nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner");
nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction");
nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer");
nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator");
nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator");
nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator");
nary.setProperty("reb2sac.nary.order.decider", "distinct");
nary.setProperty("simulation.printer", printer_id);
nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
nary.setProperty("reb2sac.analysis.stop.enabled", stopE);
nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR);
for (int i = 0; i < getSpeciesProps.size(); i++) {
if (!(inhib.get(i).getText().trim() != "<<none>>")) {
nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i),
inhib.get(i).getText().trim());
}
String[] consLevels = Buttons.getList(conLevel.get(i), consLevel.get(i));
for (int j = 0; j < counts.get(i); j++) {
nary
.remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1));
}
for (int j = 0; j < consLevels.length; j++) {
nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1), consLevels[j]);
}
}
if (monteCarlo.isSelected()) {
nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
nary.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
nary.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
nary.setProperty("monte.carlo.simulation.runs", "" + run);
nary.setProperty("monte.carlo.simulation.out.dir", ".");
}
for (int i = 0; i < finalS.length; i++) {
if (finalS[i].trim() != "<<unknown>>") {
nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]);
}
}
if (usingSSA.isSelected() && monteCarlo.isSelected()) {
nary.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < intSpecies.length; i++) {
if (intSpecies[i] != "") {
nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]);
}
}
nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
nary.setProperty("reb2sac.qssa.condition.1", "" + qss);
nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
nary.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
FileOutputStream store = new FileOutputStream(new File(filename.replace(".sbml", "")
.replace(".xml", "")
+ ".properties"));
nary.store(store, getFilename[getFilename.length - 1].replace(".sbml", "").replace(
".xml", "")
+ " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for simulation.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Executes the reb2sac program. If ODE, monte carlo, or markov is selected,
* this method creates a Graph object.
*
* @param runTime
*/
public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml,
JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo,
String sim, String printer_id, String printer_track_quantity, String outDir,
JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA,
String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root,
JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct,
double timeLimit, double runTime, String modelFile, AbstPane abstPane,
JRadioButton abstraction, String lpnProperty, double absError, double timeStep,
double printInterval, int runs) {
Runtime exec = Runtime.getRuntime();
int exitValue = 255;
while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) {
outDir = outDir.substring(0, outDir.length() - 1
- outDir.split(separator)[outDir.split(separator).length - 1].length());
}
try {
long time1;
String directory = "";
String theFile = "";
String sbmlName = "";
String lhpnName = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
if (nary.isSelected() && gcmEditor != null
&& (monteCarlo.isSelected() || xhtml.isSelected())) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml",
"")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
GCMFile paramGCM = gcmEditor.getGCM();
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + gcmEditor.getRefFile());
HashMap<String, Properties> elements = paramGCM.getSpecies();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop));
}
}
}
elements = paramGCM.getInfluences();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.PROMOTER)
&& !prop.equals(GlobalConstants.BIO)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop));
}
}
}
elements = paramGCM.getPromoters();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) {
gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop));
}
}
}
HashMap<String, String> params = paramGCM.getGlobalParameters();
ArrayList<Object> remove = new ArrayList<Object>();
for (String key : params.keySet()) {
gcm.setParameter(key, params.get(key));
remove.add(key);
}
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName + ".temp");
t1.BuildTemplate(
root + separator + simName + separator + lpnName + ".temp",
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + simName + separator
+ lpnName.replace(".lpn", ".sbml"));
t1.outputSBML();
}
else {
return 0;
}
}
if (nary.isSelected() && gcmEditor == null && !sim.contains("markov-chain-analysis")
&& !lhpn.isSelected() && naryRun == 1) {
log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work);
}
else if (sbml.isSelected()) {
sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (sbmlName != null && !sbmlName.trim().equals("")) {
sbmlName = sbmlName.trim();
if (sbmlName.length() > 4) {
if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml")
|| !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) {
sbmlName += ".xml";
}
}
else {
sbmlName += ".xml";
}
File f = new File(root + separator + sbmlName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + sbmlName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
progress.setIndeterminate(true);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + modelFile);
t1.BuildTemplate(root + separator + simName + separator + modelFile,
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + modelFile, lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
exitValue = 0;
}
else if (gcmEditor != null && nary.isSelected()) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "")
.replace(".xml", "")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile paramGCM = gcmEditor.getGCM();
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + gcmEditor.getRefFile());
HashMap<String, Properties> elements = paramGCM.getSpecies();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getSpecies().get(key)
.put(prop, elements.get(key).get(prop));
}
}
}
elements = paramGCM.getInfluences();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.PROMOTER)
&& !prop.equals(GlobalConstants.BIO)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getInfluences().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
elements = paramGCM.getPromoters();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)) {
gcm.getPromoters().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
HashMap<String, String> params = paramGCM.getGlobalParameters();
ArrayList<Object> remove = new ArrayList<Object>();
for (String key : params.keySet()) {
gcm.setParameter(key, params.get(key));
remove.add(key);
}
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName
+ ".temp");
t1.BuildTemplate(root + separator + simName + separator + lpnName
+ ".temp", lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
}
else {
time1 = System.nanoTime();
return 0;
}
exitValue = 0;
}
else {
if (abstraction.isSelected() || nary.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + theFile, null, work);
}
else {
log.addText("Outputting SBML file:\n" + root + separator + sbmlName
+ "\n");
time1 = System.nanoTime();
FileOutputStream fileOutput = new FileOutputStream(new File(root
+ separator + sbmlName));
FileInputStream fileInput = new FileInputStream(new File(filename));
int read = fileInput.read();
while (read != -1) {
fileOutput.write(read);
read = fileInput.read();
}
fileInput.close();
fileOutput.close();
exitValue = 0;
}
}
}
else {
time1 = System.nanoTime();
}
}
else if (lhpn.isSelected()) {
lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 4) {
if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
File f = new File(root + separator + lhpnName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + lhpnName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + lhpnName);
time1 = System.nanoTime();
exitValue = 0;
}
else {
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile paramGCM = gcmEditor.getGCM();
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + gcmEditor.getRefFile());
HashMap<String, Properties> elements = paramGCM.getSpecies();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getSpecies().get(key)
.put(prop, elements.get(key).get(prop));
}
}
}
elements = paramGCM.getInfluences();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.PROMOTER)
&& !prop.equals(GlobalConstants.BIO)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getInfluences().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
elements = paramGCM.getPromoters();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)) {
gcm.getPromoters().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
HashMap<String, String> params = paramGCM.getGlobalParameters();
ArrayList<Object> remove = new ArrayList<Object>();
for (String key : params.keySet()) {
gcm.setParameter(key, params.get(key));
remove.add(key);
}
if (gcm.flattenGCM(false) != null) {
LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(root + separator + lhpnName);
log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName
+ "\n");
}
else {
return 0;
}
time1 = System.nanoTime();
exitValue = 0;
}
}
else {
time1 = System.nanoTime();
exitValue = 0;
}
}
else if (dot.isSelected()) {
if (nary.isSelected() && gcmEditor != null) {
// String cmd = "atacs -cPllodpl "
// + theFile.replace(".sbml", "").replace(".xml", "") +
// ".lpn";
LhpnFile lhpnFile = new LhpnFile(log);
lhpnFile.load(directory + separator
+ theFile.replace(".sbml", "").replace(".xml", "") + ".lpn");
lhpnFile.printDot(directory + separator
+ theFile.replace(".sbml", "").replace(".xml", "") + ".dot");
time1 = System.nanoTime();
// Process ATACS = exec.exec(cmd, null, work);
// ATACS.waitFor();
// log.addText("Executing:\n" + cmd);
exitValue = 0;
}
else if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + simName + separator + modelFile);
lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot"));
// String cmd = "atacs -cPllodpl " + modelFile;
// time1 = System.nanoTime();
// Process ATACS = exec.exec(cmd, null, work);
// ATACS.waitFor();
// log.addText("Executing:\n" + cmd);
time1 = System.nanoTime();
exitValue = 0;
}
else {
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
}
}
else if (xhtml.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ theFile, null, work);
}
else if (usingSSA.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile,
null, work);
}
else {
if (sim.equals("atacs")) {
log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work);
}
else if (sim.contains("markov-chain-analysis")) {
time1 = System.nanoTime();
LhpnFile lhpnFile = null;
if (modelFile.contains(".lpn")) {
lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
}
else {
new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml",
"")
+ ".lpn").delete();
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile paramGCM = gcmEditor.getGCM();
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + gcmEditor.getRefFile());
HashMap<String, Properties> elements = paramGCM.getSpecies();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getSpecies().get(key)
.put(prop, elements.get(key).get(prop));
}
}
}
elements = paramGCM.getInfluences();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.PROMOTER)
&& !prop.equals(GlobalConstants.BIO)
&& !prop.equals(GlobalConstants.TYPE)) {
gcm.getInfluences().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
elements = paramGCM.getPromoters();
for (String key : elements.keySet()) {
for (Object prop : elements.get(key).keySet()) {
if (!prop.equals(GlobalConstants.NAME)
&& !prop.equals(GlobalConstants.ID)) {
gcm.getPromoters().get(key).put(prop,
elements.get(key).get(prop));
}
}
}
HashMap<String, String> params = paramGCM.getGlobalParameters();
ArrayList<Object> remove = new ArrayList<Object>();
for (String key : params.keySet()) {
gcm.setParameter(key, params.get(key));
remove.add(key);
}
if (!direct.equals("")) {
String[] d = direct.split("_");
ArrayList<String> dd = new ArrayList<String>();
for (int i = 0; i < d.length; i++) {
if (!d[i].contains("=")) {
String di = d[i];
while (!d[i].contains("=")) {
i++;
di += "_" + d[i];
}
dd.add(di);
}
else {
dd.add(d[i]);
}
}
for (String di : dd) {
if (di.contains("-")) {
if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) {
Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("-")[0]);
promoterProps.put(CompatibilityFixer.convertSBMLName(di.split("=")[0].split("-")[1]),
di.split("=")[1]);
}
if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) {
Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("-")[0]);
speciesProps.put(CompatibilityFixer.convertSBMLName(di.split("=")[0].split("-")[1]),
di.split("=")[1]);
}
if (gcm.getInfluences().containsKey(di.split("=")[0].split("-")[0].substring(1))) {
Properties influenceProps = gcm.getInfluences().get(
di.split("=")[0].split("-")[0].substring(1));
influenceProps.put(CompatibilityFixer.convertSBMLName(di.split("=")[0].split("-")[1])
.replace("\"", ""), di.split("=")[1]);
}
}
else {
if (gcm.getGlobalParameters().containsKey(CompatibilityFixer.convertSBMLName(di.split("=")[0]))) {
gcm.getGlobalParameters().put(CompatibilityFixer.convertSBMLName(di.split("=")[0]), di.split("=")[1]);
}
if (gcm.getParameters().containsKey(CompatibilityFixer.convertSBMLName(di.split("=")[0]))) {
gcm.getParameters().put(CompatibilityFixer.convertSBMLName(di.split("=")[0]), di.split("=")[1]);
}
}
}
}
if (gcm.flattenGCM(false) != null) {
lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "")
.replace(".xml", "")
+ ".lpn");
log.addText("Saving GCM file as LHPN:\n"
+ filename.replace(".gcm", "").replace(".sbml", "").replace(
".xml", "") + ".lpn" + "\n");
}
else {
return 0;
}
}
// gcmEditor.getGCM().createLogicalModel(
// filename.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn",
// log,
// biomodelsim,
// theFile.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn");
// LHPNFile lhpnFile = new LHPNFile();
// while (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn.temp").exists()) {
// if (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(".xml",
// + ".lpn").exists()) {
// lhpnFile.load(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn");
if (lhpnFile != null) {
sg = new StateGraph(lhpnFile);
BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg);
buildStateGraph.start();
buildStateGraph.join();
if (sim.equals("steady-state-markov-chain-analysis")) {
if (!sg.getStop()) {
log.addText("Performing steady state Markov chain analysis.\n");
PerfromSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerfromSteadyStateMarkovAnalysisThread(
sg);
time1 = System.nanoTime();
if (modelFile.contains(".lpn")) {
performMarkovAnalysis.start(absError, null);
}
else {
ArrayList<String> conditions = new ArrayList<String>();
for (int i = 0; i < gcmEditor.getGCM().getConditions().size(); i++) {
if (gcmEditor.getGCM().getConditions().get(i).startsWith(
"St")) {
conditions.add(Translator
.getProbpropExpression(gcmEditor.getGCM()
.getConditions().get(i)));
}
}
performMarkovAnalysis.start(absError, conditions);
}
performMarkovAnalysis.join();
if (!sg.getStop()) {
String simrep = sg.getMarkovResults();
if (simrep != null) {
FileOutputStream simrepstream = new FileOutputStream(
new File(directory + separator + "sim-rep.txt"));
simrepstream.write((simrep).getBytes());
simrepstream.close();
}
sg.outputStateGraph(filename.replace(".gcm", "").replace(
".sbml", "").replace(".xml", "")
+ "_sg.dot", true);
biomodelsim.enableTabMenu(biomodelsim.getTab()
.getSelectedIndex());
}
}
}
else if (sim.equals("transient-markov-chain-analysis")) {
if (!sg.getStop()) {
log
.addText("Performing transient Markov chain analysis with uniformization.\n");
PerfromTransientMarkovAnalysisThread performMarkovAnalysis = new PerfromTransientMarkovAnalysisThread(
sg, progress);
time1 = System.nanoTime();
if (lpnProperty != null && !lpnProperty.equals("")) {
performMarkovAnalysis.start(timeLimit, timeStep, absError,
Translator.getProbpropParts(Translator
.getProbpropExpression(lpnProperty)));
}
else {
performMarkovAnalysis
.start(timeLimit, timeStep, absError, null);
}
performMarkovAnalysis.join();
if (!sg.getStop()) {
String simrep = sg.getMarkovResults();
if (simrep != null) {
FileOutputStream simrepstream = new FileOutputStream(
new File(directory + separator + "sim-rep.txt"));
simrepstream.write((simrep).getBytes());
simrepstream.close();
}
sg.outputStateGraph(filename.replace(".gcm", "").replace(
".sbml", "").replace(".xml", "")
+ "_sg.dot", true);
if (sg.outputTSD(directory + separator
+ "percent-term-time.tsd")) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals(
"TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
}
}
}
biomodelsim.enableTabMenu(biomodelsim.getTab()
.getSelectedIndex());
}
// String simrep = sg.getMarkovResults();
// if (simrep != null) {
// FileOutputStream simrepstream = new
// FileOutputStream(new File(
// directory + separator + "sim-rep.txt"));
// simrepstream.write((simrep).getBytes());
// simrepstream.close();
// sg.outputStateGraph(filename.replace(".gcm",
// "").replace(".sbml",
// "").replace(".xml", "")
// + "_sg.dot", true);
// biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex());
}
}
// if (sg.getNumberOfStates() > 30) {
// String[] options = { "Yes", "No" };
// int value = JOptionPane
// .showOptionDialog(
// BioSim.frame,
// "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?",
// "More Than 30 States", JOptionPane.YES_NO_OPTION,
// JOptionPane.WARNING_MESSAGE, null, options,
// options[0]);
// if (value == JOptionPane.YES_OPTION) {
// (System.getProperty("os.name").contentEquals("Linux"))
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// else if
// (System.getProperty("os.name").toLowerCase().startsWith(
// "mac os")) {
// log.addText("Executing:\nopen "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("open "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// else {
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
exitValue = 0;
}
else {
Preferences biosimrc = Preferences.userRoot();
if (sim.equals("gillespieJava")) {
time1 = System.nanoTime();
// Properties props = new Properties();
// props.load(new FileInputStream(new File(directory +
// separator + modelFile.substring(0,
// modelFile.indexOf('.')) + ".properties")));
int index = -1;
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
simTab.setSelectedIndex(i);
index = i;
}
}
GillespieSSAJavaSingleStep javaSim = new GillespieSSAJavaSingleStep();
String SBMLFileName = directory + separator + theFile;
javaSim.PerformSim(SBMLFileName, outDir, timeLimit, timeStep,((Graph) simTab
.getComponentAt(index)));
exitValue = 0;
return exitValue;
}
else if (biosimrc.get("biosim.sim.command", "").equals("")) {
time1 = System.nanoTime();
log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename
+ "\n");
reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile,
null, work);
}
else {
String command = biosimrc.get("biosim.sim.command", "");
String fileStem = theFile.replaceAll(".xml", "");
fileStem = fileStem.replaceAll(".sbml", "");
command = command.replaceAll("filename", fileStem);
command = command.replaceAll("sim", sim);
log.addText(command + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec(command, null, work);
}
}
}
String error = "";
try {
InputStream reb = reb2sac.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
// int count = 0;
String line;
double time = 0;
double oldTime = 0;
int runNum = 0;
int prog = 0;
while ((line = br.readLine()) != null) {
try {
if (line.contains("Time")) {
time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line
.length()));
if (oldTime > time) {
runNum++;
}
oldTime = time;
time += (runNum * timeLimit);
double d = ((time * 100) / runTime);
String s = d + "";
double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s
.length()));
if (decimal >= 0.5) {
prog = (int) (Math.ceil(d));
}
else {
prog = (int) (d);
}
}
}
catch (Exception e) {
}
progress.setValue(prog);
// if (steps > 0) {
// count++;
// progress.setValue(count);
// log.addText(output);
}
InputStream reb2 = reb2sac.getErrorStream();
int read = reb2.read();
while (read != -1) {
error += (char) read;
read = reb2.read();
}
br.close();
isr.close();
reb.close();
reb2.close();
}
catch (Exception e) {
}
if (reb2sac != null) {
exitValue = reb2sac.waitFor();
}
long time2 = System.nanoTime();
long minutes;
long hours;
long days;
double secs = ((time2 - time1) / 1000000000.0);
long seconds = ((time2 - time1) / 1000000000);
secs = secs - seconds;
minutes = seconds / 60;
secs = seconds % 60 + secs;
hours = minutes / 60;
minutes = minutes % 60;
days = hours / 24;
hours = hours % 60;
String time;
String dayLabel;
String hourLabel;
String minuteLabel;
String secondLabel;
if (days == 1) {
dayLabel = " day ";
}
else {
dayLabel = " days ";
}
if (hours == 1) {
hourLabel = " hour ";
}
else {
hourLabel = " hours ";
}
if (minutes == 1) {
minuteLabel = " minute ";
}
else {
minuteLabel = " minutes ";
}
if (seconds == 1) {
secondLabel = " second";
}
else {
secondLabel = " seconds";
}
if (days != 0) {
time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs
+ secondLabel;
}
else if (hours != 0) {
time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel;
}
else if (minutes != 0) {
time = minutes + minuteLabel + secs + secondLabel;
}
else {
time = secs + secondLabel;
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n");
if (exitValue != 0) {
if (exitValue == 143) {
JOptionPane.showMessageDialog(BioSim.frame, "The simulation was"
+ " canceled by the user.", "Canceled Simulation",
JOptionPane.ERROR_MESSAGE);
}
else if (exitValue == 139) {
JOptionPane.showMessageDialog(BioSim.frame,
"The selected model is not a valid sbml file."
+ "\nYou must select an sbml file.", "Not An SBML File",
JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!\n"
+ "Bad Return Value!\n" + "The reb2sac program returned " + exitValue
+ " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) {
}
else if (sbml.isSelected()) {
if (sbmlName != null && !sbmlName.trim().equals("")) {
if (!biomodelsim.updateOpenSBML(sbmlName)) {
biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator
+ sbmlName, null, log, biomodelsim, null, null), "SBML Editor");
biomodelsim.addToTree(sbmlName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName));
}
biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex());
}
}
else if (lhpn.isSelected()) {
if (lhpnName != null && !lhpnName.trim().equals("")) {
if (!biomodelsim.updateOpenLHPN(lhpnName)) {
biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null,
biomodelsim, log), "LHPN Editor");
biomodelsim.addToTree(lhpnName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName));
}
biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex());
}
}
else if (dot.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
else if (xhtml.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n");
exec.exec("gnome-open " + out + ".xhtml", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n");
exec.exec("open " + out + ".xhtml", null, work);
}
else {
log
.addText("Executing:\ncmd /c start " + directory + out + ".xhtml"
+ "\n");
exec.exec("cmd /c start " + out + ".xhtml", null, work);
}
}
else if (usingSSA.isSelected()) {
if (!printer_id.equals("null.printer")) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory + separator
+ "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data.get(k).add(
data.get(k).get(data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator + "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory + separator
+ "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data.get(k).add(
data.get(k).get(data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator + "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
else if (sim.equals("atacs")) {
log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA "
+ filename
.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "out.hse\n");
exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work);
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir.split(separator).length - 1]
+ " simulation results", printer_id, outDir,
"time", biomodelsim, null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
// simTab.add("Probability Graph", new
// Graph(printer_track_quantity,
// outDir.split(separator)[outDir.split(separator).length -
// simulation results",
// printer_id, outDir, "time", biomodelsim, null, log, null,
// false));
// simTab.getComponentAt(simTab.getComponentCount() -
// 1).setName("ProbGraph");
}
else {
if (!printer_id.equals("null.printer")) {
if (ode.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory
+ separator + "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data
.get(k)
.add(
data.get(k).get(
data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator
+ "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory
+ separator + "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data
.get(k)
.add(
data.get(k).get(
data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator
+ "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
else if (monteCarlo.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory
+ separator + "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data
.get(k)
.add(
data.get(k).get(
data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator
+ "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean outputTerm = false;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
else if (f.equals("term-time.txt")) {
outputTerm = true;
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
if (outputTerm) {
ArrayList<String> dataLabels = new ArrayList<String>();
dataLabels.add("time");
ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>();
Scanner scan = new Scanner(new File(directory
+ separator + "term-time.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] term = line.split(" ");
if (!dataLabels.contains(term[0])) {
dataLabels.add(term[0]);
ArrayList<Double> times = new ArrayList<Double>();
times.add(Double.parseDouble(term[1]));
terms.add(times);
}
else {
terms.get(dataLabels.indexOf(term[0]) - 1).add(
Double.parseDouble(term[1]));
}
}
scan.close();
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>();
for (int j = 0; j < dataLabels.size(); j++) {
ArrayList<Double> temp = new ArrayList<Double>();
temp.add(0.0);
data.add(temp);
temp = new ArrayList<Double>();
temp.add(0.0);
percentData.add(temp);
}
for (double j = printInterval; j <= timeLimit; j += printInterval) {
data.get(0).add(j);
percentData.get(0).add(j);
for (int k = 1; k < dataLabels.size(); k++) {
data
.get(k)
.add(
data.get(k).get(
data.get(k).size() - 1));
percentData.get(k).add(
percentData.get(k).get(
percentData.get(k).size() - 1));
for (int l = terms.get(k - 1).size() - 1; l >= 0; l
if (terms.get(k - 1).get(l) < j) {
data
.get(k)
.set(
data.get(k).size() - 1,
data
.get(k)
.get(
data
.get(
k)
.size() - 1) + 1);
percentData.get(k).set(
percentData.get(k).size() - 1,
((data.get(k).get(data.get(k)
.size() - 1)) * 100)
/ runs);
terms.get(k - 1).remove(l);
}
}
}
}
Parser probData = new Parser(dataLabels, data);
probData.outputTSD(directory + separator
+ "term-time.tsd");
probData = new Parser(dataLabels, percentData);
probData.outputTSD(directory + separator
+ "percent-term-time.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
}
}
}
catch (InterruptedException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!",
"Error In Execution", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "File I/O Error!", "File I/O Error",
JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
return exitValue;
}
/**
* This method is called if a button that cancels the simulation is pressed.
*/
public void actionPerformed(ActionEvent e) {
if (reb2sac != null) {
reb2sac.destroy();
}
if (sg != null) {
sg.stop();
}
}
}
|
package jsettlers.mapcreator.mapview;
import jsettlers.common.Color;
import jsettlers.common.CommonConstants;
import jsettlers.common.landscape.ELandscapeType;
import jsettlers.common.map.IGraphicsBackgroundListener;
import jsettlers.common.map.IGraphicsGrid;
import jsettlers.common.mapobject.IMapObject;
import jsettlers.common.movable.IMovable;
import jsettlers.mapcreator.data.MapData;
import jsettlers.mapcreator.data.objects.ObjectContainer;
public class MapGraphics implements IGraphicsGrid {
private final MapData data;
private boolean showResources = false;
public MapGraphics(MapData data) {
this.data = data;
}
@Override
public short getHeight() {
return (short) data.getWidth();
}
@Override
public short getWidth() {
return (short) data.getHeight();
}
@Override
public IMovable getMovableAt(int x, int y) {
return data.getMovableContainer(x, y);
}
@Override
public IMapObject getMapObjectsAt(int x, int y) {
if (showResources) {
byte amount = data.getResourceAmount((short) x, (short) y);
if (amount > 0) {
return ResourceMapObject.get(data.getResourceType((short) x, (short) y), amount);
} else {
return null;
}
} else {
ObjectContainer container = data.getMapObjectContainer(x, y);
if (container instanceof IMapObject) {
return (IMapObject) container;
} else {
return null;
}
}
}
@Override
public byte getHeightAt(int x, int y) {
return data.getLandscapeHeight(x, y);
}
@Override
public ELandscapeType getLandscapeTypeAt(int x, int y) {
return data.getLandscape(x, y);
}
@Override
public int getDebugColorAt(int x, int y) {
return data.isFailpoint(x, y) ? Color.RED.getARGB() : -1;
}
@Override
public boolean isBorder(int x, int y) {
return data.isBorder(x, y);
}
@Override
public byte getPlayerIdAt(int x, int y) {
return data.getPlayer(x, y);
}
@Override
public byte getVisibleStatus(int x, int y) {
return CommonConstants.FOG_OF_WAR_VISIBLE;
}
@Override
public boolean isFogOfWarVisible(int x, int y) {
return true;
}
@Override
public void setBackgroundListener(IGraphicsBackgroundListener backgroundListener) {
data.setListener(backgroundListener);
}
public void setShowResources(boolean b) {
showResources = b;
}
@Override
public int nextDrawableX(int x, int y, int maxX) {
return x + 1;
}
}
|
package eu.nimble.core.infrastructure.identity.controller.ubl;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import eu.nimble.core.infrastructure.identity.controller.IdentityUtils;
import eu.nimble.core.infrastructure.identity.repository.PartyRepository;
import eu.nimble.core.infrastructure.identity.repository.PersonRepository;
import eu.nimble.core.infrastructure.identity.uaa.OAuthClient;
import eu.nimble.service.model.ubl.commonaggregatecomponents.PartyType;
import eu.nimble.service.model.ubl.commonaggregatecomponents.PersonType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Controller
@Api(value = "party", description = "API for handling parties on the platform.")
public class PartyController {
private static final Logger logger = LoggerFactory.getLogger(PartyController.class);
@Autowired
private PartyRepository partyRepository;
@Autowired
private PersonRepository personRepository;
@Autowired
private IdentityUtils identityUtils;
@SuppressWarnings("PointlessBooleanExpression")
@ApiOperation(value = "", notes = "Get Party for Id.", response = PartyType.class, tags = {})
@RequestMapping(value = "/party/{partyId}", method = RequestMethod.GET)
ResponseEntity<PartyType> getParty(
@ApiParam(value = "Id of party to retrieve.", required = true) @PathVariable Long partyId,
@RequestHeader(value = "Authorization") String bearer) throws IOException {
// search relevant parties
List<PartyType> parties = partyRepository.findByHjid(partyId);
// check if party was found
if (parties.isEmpty()) {
logger.info("Requested party with Id {} not found", partyId);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
PartyType party = parties.get(0);
// remove person depending on access rights
if (identityUtils.hasRole(bearer, OAuthClient.Role.LEGAL_REPRESENTATIVE) == false)
party.setPerson(new ArrayList<>());
logger.debug("Returning requested party with Id {0}", party.getHjid());
return new ResponseEntity<>(party, HttpStatus.OK);
}
@SuppressWarnings("PointlessBooleanExpression")
@ApiOperation(value = "", notes = "Get multiple parties for Ids.", response = Iterable.class)
@RequestMapping(value = "/parties/{partyIds}", method = RequestMethod.GET)
ResponseEntity<?> getParty(
@ApiParam(value = "Ids of parties to retrieve.", required = true) @PathVariable List<Long> partyIds) {
logger.debug("Requesting parties with Ids {0}", partyIds);
// search relevant parties
List<PartyType> parties = new ArrayList<>();
for (Long partyId : partyIds) {
Optional<PartyType> party = partyRepository.findByHjid(partyId).stream().findFirst();
// check if party was found
if (party.isPresent() == false) {
String message = String.format("Requested party with Id %s not found", partyId);
logger.info(message);
return new ResponseEntity<>(message, HttpStatus.NOT_FOUND);
}
parties.add(party.get());
}
logger.debug("Returning requested parties with Ids {0}", partyIds);
return new ResponseEntity<>(parties, HttpStatus.OK);
}
@ApiOperation(value = "", notes = "Get Party for person ID.", response = PartyType.class, tags = {})
@RequestMapping(value = "/party_by_person/{personId}", produces = {"application/json"}, method = RequestMethod.GET)
ResponseEntity<List<PartyType>> getPartyByPersonID(
@ApiParam(value = "Id of party to retrieve.", required = true) @PathVariable Long personId) {
// search for persons
List<PersonType> foundPersons = personRepository.findByHjid(personId);
// check if person was found
if (foundPersons.isEmpty()) {
logger.info("Requested person with Id {} not found", personId);
return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
}
PersonType person = foundPersons.get(0);
List<PartyType> parties = partyRepository.findByPerson(person);
return new ResponseEntity<>(parties, HttpStatus.OK);
}
@SuppressWarnings("PointlessBooleanExpression")
@ApiOperation(value = "", notes = "Get Party for Id in the UBL format.", response = PartyType.class, tags = {})
@RequestMapping(value = "/party/ubl/{partyId}", produces = {"text/xml"}, method = RequestMethod.GET)
ResponseEntity<String> getPartyUbl(
@ApiParam(value = "Id of party to retrieve.", required = true) @PathVariable Long partyId,
@RequestHeader(value = "Authorization") String bearer) throws IOException, JAXBException {
// search relevant parties
List<PartyType> parties = partyRepository.findByHjid(partyId);
// check if party was found
if (parties.isEmpty()) {
logger.info("Requested party with Id {} not found", partyId);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
PartyType party = parties.get(0);
// remove person depending on access rights
if (identityUtils.hasRole(bearer, OAuthClient.Role.LEGAL_REPRESENTATIVE) == false)
party.setPerson(new ArrayList<>());
StringWriter serializedCatalogueWriter = new StringWriter();
String packageName = party.getClass().getPackage().getName();
JAXBContext jc = JAXBContext.newInstance(packageName);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Marshaller marsh = jc.createMarshaller();
marsh.setProperty("jaxb.formatted.output", true);
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
@SuppressWarnings("unchecked")
JAXBElement element = new JAXBElement(new QName("urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", "Party"), party.getClass(), party);
marsh.marshal(element, serializedCatalogueWriter);
// log the catalogue to be transformed
String xmlParty = serializedCatalogueWriter.toString();
xmlParty = xmlParty.replaceAll(" Hjid=\"[0-9]+\"", "");
serializedCatalogueWriter.flush();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_XML);
return new ResponseEntity<>(xmlParty, responseHeaders, HttpStatus.OK);
}
@ApiOperation(value = "", notes = "Get all party ids", response = String.class, responseContainer = "Set")
@RequestMapping(value = "/party/all", produces = {"application/json"}, method = RequestMethod.GET)
ResponseEntity<Set<String>> getAllPartyIds(
@ApiParam(value = "Excluded ids") @RequestParam(value = "exclude", required = false) List<String> exclude) {
Set<String> partyIds = StreamSupport.stream(partyRepository.findAll().spliterator(), false)
.map(PartyType::getID)
.collect(Collectors.toSet());
if (exclude != null)
partyIds.removeAll(exclude);
return ResponseEntity.ok(partyIds);
}
}
|
package org.innovateuk.ifs.invite.repository;
import org.innovateuk.ifs.category.domain.InnovationArea;
import org.innovateuk.ifs.invite.domain.CompetitionParticipant;
import org.innovateuk.ifs.invite.domain.CompetitionParticipantRole;
import org.innovateuk.ifs.invite.domain.ParticipantStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CompetitionParticipantRepository extends CrudRepository<CompetitionParticipant, Long> {
@Override
List<CompetitionParticipant> findAll();
CompetitionParticipant getByInviteHash(String hash);
List<CompetitionParticipant> getByUserIdAndRole(Long userId, CompetitionParticipantRole role);
List<CompetitionParticipant> getByCompetitionIdAndRole(Long competitionId, CompetitionParticipantRole role);
List<CompetitionParticipant> getByCompetitionIdAndRoleAndStatus(Long competitionId, CompetitionParticipantRole role, ParticipantStatus status);
List<CompetitionParticipant> getByInviteEmail(String email);
int countByCompetitionIdAndRole(Long competitionId, CompetitionParticipantRole role);
int countByCompetitionIdAndRoleAndStatus(Long competitionId, CompetitionParticipantRole role, ParticipantStatus status);
@Query("SELECT cp FROM CompetitionParticipant cp WHERE cp.competition.id = :compId " +
"AND cp.role = :role " +
"AND cp.status = :status " +
"AND NOT EXISTS " +
"(SELECT 'found' FROM Assessment a WHERE " +
"a.participant.user = cp.user " +
"AND a.target.id = :appId) " +
"AND (:innovationAreaId is null OR EXISTS " +
"(SELECT 'area' FROM Profile p JOIN p.innovationAreas ia WHERE " +
"p.id = cp.user.profileId " +
"AND ia.category.id = :innovationAreaId ))")
Page<CompetitionParticipant> findParticipantsWithoutAssessments(@Param("compId") Long competitionId,
@Param("role") CompetitionParticipantRole role,
@Param("status") ParticipantStatus status,
@Param("appId") Long applicationId,
@Param("innovationAreaId") Long filterInnovationArea,
Pageable pageable);
@Query("SELECT cp FROM CompetitionParticipant cp WHERE " +
"cp.competition.id = :compId " +
"AND cp.role = :role " +
"AND cp.status = :status " +
"AND EXISTS (SELECT 'found' FROM Assessment a WHERE a.participant.user = cp.user AND a.target.id = :appId)")
List<CompetitionParticipant> findParticipantsWithAssessments(
@Param("compId") Long competitionId,
@Param("role") CompetitionParticipantRole role,
@Param("status") ParticipantStatus status,
@Param("appId") Long applicationId);
}
|
package com.hp.octane.plugins.jenkins.tests.detection;
import com.hp.octane.plugins.jenkins.ExtensionUtil;
import com.hp.octane.plugins.jenkins.tests.CopyResourceSCM;
import com.hp.octane.plugins.jenkins.tests.TestUtils;
import com.hp.octane.plugins.jenkins.tests.junit.JUnitExtension;
import hudson.model.AbstractBuild;
import hudson.model.FreeStyleProject;
import hudson.tasks.Maven;
import hudson.tasks.junit.JUnitResultArchiver;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.ToolInstallations;
import org.mockito.Mockito;
import java.io.File;
import java.io.FileReader;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ResultFieldsDetectionTest {
@Rule
public final JenkinsRule rule = new JenkinsRule();
private static FreeStyleProject project;
private static ResultFieldsDetectionService detectionService;
@Before
public void setUp() throws Exception {
project = rule.createFreeStyleProject("junit - job");
JUnitExtension junitExtension = ExtensionUtil.getInstance(rule, JUnitExtension.class);
detectionService = Mockito.mock(ResultFieldsDetectionService.class);
junitExtension._setResultFieldsDetectionService(detectionService);
Maven.MavenInstallation mavenInstallation = ToolInstallations.configureMaven3();
project.getBuildersList().add(new Maven("-s settings.xml -U test", mavenInstallation.getName(), null, null, "-Dmaven.test.failure.ignore=true"));
project.setScm(new CopyResourceSCM("/helloWorldRoot"));
}
@Test
public void testDetectionNotRun() throws Exception {
//there is no test publisher set up in this project, detection will not run
AbstractBuild build = TestUtils.runAndCheckBuild(project);
verify(detectionService, Mockito.never()).getDetectedFields(build);
}
@Test
public void testDetectionRunOnce() throws Exception {
project.getPublishersList().add(new JUnitResultArchiver("**/target/surefire-reports/*.xml"));
AbstractBuild build = TestUtils.runAndCheckBuild(project);
verify(detectionService, Mockito.times(1)).getDetectedFields(build);
}
@Test
public void testDetectedFieldsInXml() throws Exception {
when(detectionService.getDetectedFields(any(AbstractBuild.class))).thenReturn(new ResultFields("HOLA", "CIAO", "SALUT"));
project.getPublishersList().add(new JUnitResultArchiver("**/target/surefire-reports/*.xml"));
AbstractBuild build = TestUtils.runAndCheckBuild(project);
File mqmTestsXml = new File(build.getRootDir(), "mqmTests.xml");
ResultFieldsXmlReader xmlReader = new ResultFieldsXmlReader(new FileReader(mqmTestsXml));
ResultFields resultFields = xmlReader.readXml().getResultFields();
Assert.assertNotNull(resultFields);
Assert.assertEquals("HOLA", resultFields.getFramework());
Assert.assertEquals("CIAO", resultFields.getTestingTool());
Assert.assertEquals("SALUT", resultFields.getTestLevel());
}
@Test
public void testNoDetectedFieldsInXml() throws Exception {
when(detectionService.getDetectedFields(any(AbstractBuild.class))).thenReturn(null);
project.getPublishersList().add(new JUnitResultArchiver("**/target/surefire-reports/*.xml"));
AbstractBuild build = TestUtils.runAndCheckBuild(project);
File mqmTestsXml = new File(build.getRootDir(), "mqmTests.xml");
ResultFieldsXmlReader xmlReader = new ResultFieldsXmlReader(new FileReader(mqmTestsXml));
ResultFields resultFields = xmlReader.readXml().getResultFields();
;
Assert.assertNull(resultFields.getFramework());
Assert.assertNull(resultFields.getTestingTool());
Assert.assertNull(resultFields.getTestLevel());
}
@Test
public void testEmptyDetectedFieldsInXml() throws Exception {
when(detectionService.getDetectedFields(any(AbstractBuild.class))).thenReturn(new ResultFields(null, null, null));
project.getPublishersList().add(new JUnitResultArchiver("**/target/surefire-reports/*.xml"));
AbstractBuild build = TestUtils.runAndCheckBuild(project);
File mqmTestsXml = new File(build.getRootDir(), "mqmTests.xml");
ResultFieldsXmlReader xmlReader = new ResultFieldsXmlReader(new FileReader(mqmTestsXml));
ResultFields resultFields = xmlReader.readXml().getResultFields();
;
Assert.assertNull(resultFields.getFramework());
Assert.assertNull(resultFields.getTestingTool());
Assert.assertNull(resultFields.getTestLevel());
}
/**
* We do not detect Junit yet.
*/
@Test
public void testNotDetectableConfigurationInXml() throws Exception {
project.getPublishersList().add(new JUnitResultArchiver("**/target/surefire-reports/*.xml"));
AbstractBuild build = TestUtils.runAndCheckBuild(project);
File mqmTestsXml = new File(build.getRootDir(), "mqmTests.xml");
ResultFieldsXmlReader xmlReader = new ResultFieldsXmlReader(new FileReader(mqmTestsXml));
ResultFields resultFields = xmlReader.readXml().getResultFields();
Assert.assertNull(resultFields.getFramework());
Assert.assertNull(resultFields.getTestingTool());
Assert.assertNull(resultFields.getTestLevel());
}
}
|
package org.eclipse.jetty.websocket.servlet;
import java.io.IOException;
import java.util.Iterator;
import java.util.ServiceLoader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.websocket.api.WebSocketBehavior;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
/**
* Abstract Servlet used to bridge the Servlet API to the WebSocket API.
* <p>
* To use this servlet, you will be required to register your websockets with the {@link WebSocketServerFactory} so that it can create your websockets under the
* appropriate conditions.
* <p>
* The most basic implementation would be as follows.
*
* <pre>
* package my.example;
*
* import javax.servlet.http.HttpServletRequest;
* import org.eclipse.jetty.websocket.WebSocket;
* import org.eclipse.jetty.websocket.server.WebSocketServlet;
*
* public class MyEchoServlet extends WebSocketServlet
* {
* @Override
* public void registerWebSockets(WebSocketServerFactory factory)
* {
* factory.register(MyEchoSocket.class);
* }
* }
* </pre>
*
* Note: that only request that conforms to a "WebSocket: Upgrade" handshake request will trigger the {@link WebSocketServerFactory} handling of creating
* WebSockets.<br>
* All other requests are treated as normal servlet requests.
*
* <p>
* <b>Configuration / Init-Parameters:</b><br>
* Note: If you use the {@link WebSocket @WebSocket} annotation, these configuration settings can be specified on a per WebSocket basis, vs a per Servlet
* basis.
*
* <dl>
* <dt>maxIdleTime</dt>
* <dd>set the time in ms that a websocket may be idle before closing<br>
*
* <dt>maxMessagesSize</dt>
* <dd>set the size in bytes that a websocket may be accept before closing<br>
*
* <dt>inputBufferSize</dt>
* <dd>set the size in bytes of the buffer used to read raw bytes from the network layer<br>
* </dl>
*/
@SuppressWarnings("serial")
public abstract class WebSocketServlet extends HttpServlet
{
private WebSocketServletFactory factory;
public abstract void configure(WebSocketServletFactory factory);
@Override
public void destroy()
{
factory.cleanup();
}
/**
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException
{
try
{
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
String max = getInitParameter("maxIdleTime");
if (max != null)
{
policy.setIdleTimeout(Long.parseLong(max));
}
max = getInitParameter("maxMessageSize");
if (max != null)
{
policy.setMaxMessageSize(Long.parseLong(max));
}
max = getInitParameter("inputBufferSize");
if (max != null)
{
policy.setInputBufferSize(Integer.parseInt(max));
}
WebSocketServletFactory baseFactory;
Iterator<WebSocketServletFactory> factories = ServiceLoader.load(WebSocketServletFactory.class).iterator();
if (factories.hasNext())
{
baseFactory = factories.next();
}
else
{
// Load the default class if ServiceLoader mechanism isn't valid in this environment. (such as OSGi)
ClassLoader loader = Thread.currentThread().getContextClassLoader();
@SuppressWarnings("unchecked")
Class<WebSocketServletFactory> wssf = (Class<WebSocketServletFactory>)loader
.loadClass("org.eclipse.jetty.websocket.server.WebSocketServerFactory");
baseFactory = wssf.newInstance();
}
factory = baseFactory.createFactory(policy);
configure(factory);
factory.init();
}
catch (Exception x)
{
throw new ServletException(x);
}
}
/**
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (factory.isUpgradeRequest(request,response))
{
// We have an upgrade request
if (factory.acceptWebSocket(request,response))
{
// We have a socket instance created
return;
}
// If we reach this point, it means we had an incoming request to upgrade
// but it was either not a proper websocket upgrade, or it was possibly rejected
// due to incoming request constraints (controlled by WebSocketCreator)
if (response.isCommitted())
{
// not much we can do at this point.
return;
}
}
// All other processing
super.service(request,response);
}
}
|
package com.parrot.arsdk.libsal;
/**
* Interface for all C data that may pass through different libs of AR.SDK<br>
* <br>
* AR.SDK Is mainly implemented in C, and thus libs often use C structures to hold data.<br>
* This is a wrapper interface onto these kind of data, so java can pass them around libs without copy into JVM memory space.
*/
public interface SALNativeData {
/**
* Get the C data pointer (equivalent C type : uint8_t *)<br>
* This function must return 0 (C-NULL) if the data is not valid (i.e. disposed or uninitialized)
* @return Native data pointer
*/
public long getData ();
/**
* Get the C data size (in bytes)<br>
* This function must return 0 (no data) if the data is not valid
* @return Size of the native data
*/
public int getDataSize ();
/**
* Get a byte array which is a copy of the C native data<br>
* This function allow Java code to access (but not modify) the content of a SALNativeData
* @note This function creates a new byte [], and thus should not be called in a loop
* @return A Java copy of the Native data (byte equivalent)
*/
public byte [] getByteData ();
/**
* Mark a native data as unused (so C-allocated memory can be freed)<br>
* Using a disposed data leads to undefined behavior, and must be avoided !
*/
public void dispose ();
}
|
package it.restart.com.atlassian.jira.plugins.dvcs.test;
import com.atlassian.jira.pageobjects.JiraTestedProduct;
import com.atlassian.jira.plugins.dvcs.pageobjects.JiraLoginPageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.common.MagicVisitor;
import com.atlassian.jira.plugins.dvcs.pageobjects.common.OAuth;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.BitBucketCommitEntry;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.OrganizationDiv;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.RepositoryDiv;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.JiraViewIssuePage;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.JiraViewIssuePageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.OAuthCredentials;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.RepositoriesPageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.RepositoriesPageController.AccountType;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.AccountsPage;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.AccountsPageAccount;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.AccountsPageAccountRepository;
import com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.ChangesetLocalRestpoint;
import com.atlassian.pageobjects.TestedProductFactory;
import com.atlassian.pageobjects.elements.PageElement;
import it.com.atlassian.jira.plugins.dvcs.DvcsWebDriverTestCase;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubLoginPage;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubOAuthApplicationPage;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubOAuthPage;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static it.restart.com.atlassian.jira.plugins.dvcs.test.GithubTestHelper.GITHUB_API_URL;
import static it.restart.com.atlassian.jira.plugins.dvcs.test.GithubTestHelper.REPOSITORY_NAME;
import static it.util.TestAccounts.DVCS_CONNECTOR_TEST_ACCOUNT;
import static it.util.TestAccounts.JIRA_BB_CONNECTOR_ACCOUNT;
import static org.fest.assertions.api.Assertions.assertThat;
public class GithubTests extends DvcsWebDriverTestCase implements BasicTests
{
private static JiraTestedProduct jira = TestedProductFactory.create(JiraTestedProduct.class);
private static final List<String> BASE_REPOSITORY_NAMES = Arrays.asList(new String[] { "missingcommits", "repo1", "noauthor", "test-project" });
private OAuth oAuth;
@BeforeClass
public void beforeClass()
{
jira.backdoor().restoreDataFromResource(TEST_DATA);
// log in to JIRA
new JiraLoginPageController(jira).login();
// log in to github
new MagicVisitor(jira).visit(GithubLoginPage.class).doLogin();
// setup up OAuth from github
oAuth = new MagicVisitor(jira).visit(GithubOAuthPage.class).addConsumer(jira.getProductInstance().getBaseUrl());
jira.backdoor().plugins().disablePlugin("com.atlassian.jira.plugins.jira-development-integration-plugin");
}
@AfterClass
public void afterClass()
{
// delete all organizations
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.getPage().deleteAllOrganizations();
// remove OAuth in github
new MagicVisitor(jira).visit(GithubOAuthApplicationPage.class).removeConsumer(oAuth);
// log out from github
new MagicVisitor(jira).visit(GithubLoginPage.class).doLogout();
}
@BeforeMethod
public void beforeMethod()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.getPage().deleteAllOrganizations();
}
@Override
@Test
public void addOrganization()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, getOAuthCredentials(), false);
assertThat(organization).isNotNull();
assertThat(organization.getRepositoryNames()).containsAll(BASE_REPOSITORY_NAMES);
}
@Override
@Test
public void addOrganizationWaitForSync()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, getOAuthCredentials(), false);
assertThat(organization).isNotNull();
assertThat(organization.getRepositoryNames()).containsAll(BASE_REPOSITORY_NAMES);
final String expectedMessage = "Mon Feb 06 2012";
RepositoryDiv repositoryDiv = organization.findRepository(REPOSITORY_NAME);
assertThat(repositoryDiv).isNotNull();
repositoryDiv.enableSync();
repositoryDiv.sync();
assertThat(repositoryDiv.getMessage()).isEqualTo(expectedMessage);
ChangesetLocalRestpoint changesetLocalRestpoint = new ChangesetLocalRestpoint();
List<String> commitsForQA2 = changesetLocalRestpoint.getCommitMessages("QA-2", 6);
assertThat(commitsForQA2).contains("BB modified 1 file to QA-2 and QA-3 from TestRepo-QA");
List<String> commitsForQA3 = changesetLocalRestpoint.getCommitMessages("QA-3", 1);
assertThat(commitsForQA3).contains("BB modified 1 file to QA-2 and QA-3 from TestRepo-QA");
}
@Override
@Test (expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = ".*Error!\\nThe url \\[https://nonexisting.org\\] is incorrect or the server is not responding.*")
public void addOrganizationInvalidUrl()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.addOrganization(AccountType.GITHUB, "https://nonexisting.org/someaccount", getOAuthCredentials(), false, true);
}
@Override
@Test (expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = ".*Error!\\nInvalid user/team account.*")
public void addOrganizationInvalidAccount()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.addOrganization(AccountType.GITHUB, "I_AM_SURE_THIS_ACCOUNT_IS_INVALID", getOAuthCredentials(), false, true);
}
@Override
@Test (expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = "Invalid OAuth")
public void addOrganizationInvalidOAuth()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, new OAuthCredentials("xxx", "yyy"), true, true);
}
@Test
@Override
public void testPostCommitHookAddedAndRemoved()
{
testPostCommitHookAddedAndRemoved(JIRA_BB_CONNECTOR_ACCOUNT, AccountType.GITHUB, REPOSITORY_NAME, jira, getOAuthCredentials());
}
@Override
protected boolean postCommitHookExists(final String accountName, final String jiraCallbackUrl)
{
List<String> actualHookUrls = GithubTestHelper.getHookUrls(accountName, GITHUB_API_URL, REPOSITORY_NAME);
return actualHookUrls.contains(jiraCallbackUrl);
}
@Test
@Override
public void testCommitStatistics()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT,
getOAuthCredentials(), false);
final RepositoryDiv repositoryDiv = organization.findRepository("test-project");
repositoryDiv.enableSync();
repositoryDiv.sync();
// QA-2
List<BitBucketCommitEntry> commitMessages = new JiraViewIssuePageController(jira, "QA-3").getCommits(1); // throws AssertionError with other than 1 message
assertThat(commitMessages).hasSize(1);
BitBucketCommitEntry commitMessage = commitMessages.get(0);
List<PageElement> statistics = commitMessage.getStatistics();
assertThat(statistics).hasSize(1);
assertThat(commitMessage.getAdditions(statistics.get(0))).isEqualTo("+1");
assertThat(commitMessage.getDeletions(statistics.get(0))).isEqualTo("-");
// QA-4
commitMessages = new JiraViewIssuePageController(jira, "QA-4").getCommits(1); // throws AssertionError with other than 1 message
assertThat(commitMessages).hasSize(1);
commitMessage = commitMessages.get(0);
statistics = commitMessage.getStatistics();
assertThat(statistics).hasSize(1);
assertThat(commitMessage.isAdded(statistics.get(0))).isTrue();
}
@Override
@Test
public void shouldBeAbleToSeePrivateRepositoriesFromTeamAccount()
{
// we should see 'private-dvcs-connector-test' repo
RepositoriesPageController rpc = new RepositoriesPageController(jira);
OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, "atlassian",
getOAuthCredentials(), false);
assertThat(organization.containsRepository("private-dvcs-connector-test"));
}
@Test
public void linkingRepositoryWithoutAdminPermission()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.addOrganization(AccountType.GITHUB, DVCS_CONNECTOR_TEST_ACCOUNT, getOAuthCredentials(), false);
AccountsPage accountsPage = jira.visit(AccountsPage.class);
AccountsPageAccount account = accountsPage.getAccount(AccountsPageAccount.AccountType.GIT_HUB, DVCS_CONNECTOR_TEST_ACCOUNT);
AccountsPageAccountRepository repository = account.enableRepository("testemptyrepo", true);
// check that repository is enabled
Assert.assertTrue(repository.isEnabled());
Assert.assertTrue(repository.hasWarning());
}
@Test
public void linkingRepositoryWithAdminPermission()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, getOAuthCredentials(), false);
AccountsPage accountsPage = jira.visit(AccountsPage.class);
AccountsPageAccount account = accountsPage.getAccount(AccountsPageAccount.AccountType.GIT_HUB, JIRA_BB_CONNECTOR_ACCOUNT);
AccountsPageAccountRepository repository = account.enableRepository(REPOSITORY_NAME, false);
// check that repository is enabled
Assert.assertTrue(repository.isEnabled());
Assert.assertFalse(repository.hasWarning());
}
@Test
public void autoLinkingRepositoryWithoutAdminPermission()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, DVCS_CONNECTOR_TEST_ACCOUNT, getOAuthCredentials(), false);
organization.enableAllRepos();
AccountsPage accountsPage = jira.visit(AccountsPage.class);
AccountsPageAccount account = accountsPage.getAccount(AccountsPageAccount.AccountType.GIT_HUB, DVCS_CONNECTOR_TEST_ACCOUNT);
for (AccountsPageAccountRepository repository : account.getRepositories())
{
Assert.assertTrue(repository.isEnabled());
}
}
@Test
public void autoLinkingRepositoryWithAdminPermission()
{
RepositoriesPageController rpc = new RepositoriesPageController(jira);
final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, getOAuthCredentials(), false);
organization.enableAllRepos();
AccountsPage accountsPage = jira.visit(AccountsPage.class);
AccountsPageAccount account = accountsPage.getAccount(AccountsPageAccount.AccountType.GIT_HUB, JIRA_BB_CONNECTOR_ACCOUNT);
for (AccountsPageAccountRepository repository : account.getRepositories())
{
Assert.assertTrue(repository.isEnabled());
Assert.assertFalse(repository.hasWarning());
}
}
private OAuthCredentials getOAuthCredentials()
{
return new OAuthCredentials(oAuth.key, oAuth.secret);
}
private List<BitBucketCommitEntry> getCommitsForIssue(String issueKey, int exectedNumberOfCommits)
{
return jira.visit(JiraViewIssuePage.class, issueKey)
.openBitBucketPanel()
.waitForNumberOfMessages(exectedNumberOfCommits, 1000L, 5);
}
}
|
package org.eclipse.persistence.internal.jpa.metadata;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.persistence.annotations.ExistenceType;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
import org.eclipse.persistence.descriptors.ReturningPolicy;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.descriptors.OptimisticLockingPolicy;
import org.eclipse.persistence.internal.jpa.CMP3Policy;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.BasicCollectionAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.CollectionAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.ManyToManyAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.OneToOneAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.RelationshipAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataField;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataMethod;
import org.eclipse.persistence.internal.jpa.metadata.accessors.MetadataAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.PropertyMetadata;
import org.eclipse.persistence.internal.jpa.metadata.columns.AssociationOverrideMetadata;
import org.eclipse.persistence.internal.jpa.metadata.columns.AttributeOverrideMetadata;
import org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListener;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.internal.helper.DatabaseTable;
import org.eclipse.persistence.mappings.DatabaseMapping;
/**
* INTERNAL:
* Common metatata descriptor for the annotation and xml processors. This class
* is a wrap on an actual TopLink descriptor.
*
* @author Guy Pelletier
* @since TopLink EJB 3.0 Reference Implementation
*/
public class MetadataDescriptor {
// Access types
private static final String FIELD = "FIELD";
private static final String PROPERTY = "PROPERTY";
private Class m_javaClass;
private ClassAccessor m_accessor;
private ClassDescriptor m_descriptor;
private DatabaseTable m_primaryTable;
private ExistenceType m_existenceChecking;
// This is the parent class that defines the inheritance strategy, and
// not necessarily the immediate parent class.
private MetadataDescriptor m_inheritanceParentDescriptor;
private boolean m_isCascadePersist;
private boolean m_ignoreAnnotations; // XML metadata complete
private boolean m_hasCache;
private boolean m_hasChangeTracking;
private boolean m_hasCustomizer;
private boolean m_hasReadOnly;
private boolean m_hasCopyPolicy;
private Boolean m_usesPropertyAccess;
private Boolean m_usesCascadedOptimisticLocking;
private String m_xmlAccess;
private String m_xmlSchema;
private String m_xmlCatalog;
private String m_embeddedIdAttributeName;
private List<String> m_idAttributeNames;
private List<String> m_orderByAttributeNames;
private List<String> m_idOrderByAttributeNames;
private List<MetadataDescriptor> m_embeddableDescriptors;
private List<RelationshipAccessor> m_relationshipAccessors;
private List<BasicCollectionAccessor> m_basicCollectionAccessors;
private Map<String, Type> m_pkClassIDs;
private Map<String, MappingAccessor> m_accessors;
private Map<String, PropertyMetadata> m_properties;
private Map<String, String> m_pkJoinColumnAssociations;
private Map<String, AttributeOverrideMetadata> m_attributeOverrides;
private Map<String, AssociationOverrideMetadata> m_associationOverrides;
private Map<String, Map<String, MetadataAccessor>> m_biDirectionalManyToManyAccessors;
/**
* INTERNAL:
*/
public MetadataDescriptor(Class javaClass) {
m_xmlAccess = null;
m_xmlSchema = null;
m_xmlCatalog = null;
m_inheritanceParentDescriptor = null;
m_hasCache = false;
m_hasChangeTracking = false;
m_hasCustomizer = false;
m_hasReadOnly = false;
m_isCascadePersist = false;
m_ignoreAnnotations = false;
m_idAttributeNames = new ArrayList<String>();
m_orderByAttributeNames = new ArrayList<String>();
m_idOrderByAttributeNames = new ArrayList<String>();
m_embeddableDescriptors = new ArrayList<MetadataDescriptor>();
m_relationshipAccessors = new ArrayList<RelationshipAccessor>();
m_basicCollectionAccessors = new ArrayList<BasicCollectionAccessor>();
m_pkClassIDs = new HashMap<String, Type>();
m_accessors = new HashMap<String, MappingAccessor>();
m_properties = new HashMap<String, PropertyMetadata>();
m_pkJoinColumnAssociations = new HashMap<String, String>();
m_attributeOverrides = new HashMap<String, AttributeOverrideMetadata>();
m_associationOverrides = new HashMap<String, AssociationOverrideMetadata>();
m_biDirectionalManyToManyAccessors = new HashMap<String, Map<String, MetadataAccessor>>();
m_descriptor = new RelationalDescriptor();
m_descriptor.setAlias("");
// This is the default, set it in case no existence-checking is set.
m_descriptor.getQueryManager().checkDatabaseForDoesExist();
setJavaClass(javaClass);
}
/**
* INTERNAL:
*/
public MetadataDescriptor(Class javaClass, ClassAccessor classAccessor) {
this(javaClass);
setClassAccessor(classAccessor);
}
/**
* INTERNAL:
*/
public void addAccessor(MappingAccessor accessor) {
m_accessors.put(accessor.getAttributeName(), accessor);
}
/**
* INTERNAL:
*/
public void addAssociationOverride(AssociationOverrideMetadata associationOverride) {
m_associationOverrides.put(associationOverride.getName(), associationOverride);
}
/**
* INTERNAL:
*/
public void addAttributeOverride(AttributeOverrideMetadata attributeOverride) {
m_attributeOverrides.put(attributeOverride.getName(), attributeOverride);
}
/**
* INTERNAL:
* Store basic collection accessors for later processing and quick look up.
*/
public void addBasicCollectionAccessor(MetadataAccessor accessor) {
m_basicCollectionAccessors.add((BasicCollectionAccessor) accessor);
}
/**
* INTERNAL:
*/
public void addClassIndicator(Class entityClass, String value) {
if (isInheritanceSubclass()) {
getInheritanceParentDescriptor().addClassIndicator(entityClass, value);
} else {
m_descriptor.getInheritancePolicy().addClassNameIndicator(entityClass.getName(), value);
}
}
/**
* INTERNAL:
*/
public void addDefaultEventListener(EntityListener listener) {
m_descriptor.getEventManager().addDefaultEventListener(listener);
}
/**
* INTERNAL:
*/
public void addEmbeddableDescriptor(MetadataDescriptor embeddableDescriptor) {
m_embeddableDescriptors.add(embeddableDescriptor);
}
/**
* INTERNAL:
*/
public void addEntityListenerEventListener(EntityListener listener) {
m_descriptor.getEventManager().addEntityListenerEventListener(listener);
}
/**
* INTERNAL:
*/
public void addFieldForInsert(DatabaseField field) {
getReturningPolicy().addFieldForInsert(field);
}
/**
* INTERNAL:
*/
public void addFieldForInsertReturnOnly(DatabaseField field) {
getReturningPolicy().addFieldForInsertReturnOnly(field);
}
/**
* INTERNAL:
*/
public void addFieldForUpdate(DatabaseField field) {
getReturningPolicy().addFieldForUpdate(field);
}
/**
* INTERNAL:
*/
public void addIdAttributeName(String idAttributeName) {
m_idAttributeNames.add(idAttributeName);
}
/**
* INTERNAL:
*/
public void addMapping(DatabaseMapping mapping) {
m_descriptor.addMapping(mapping);
}
/**
* INTERNAL:
*/
public void addForeignKeyFieldForMultipleTable(DatabaseField fkField, DatabaseField pkField) {
m_descriptor.addForeignKeyFieldForMultipleTable(fkField, pkField);
m_pkJoinColumnAssociations.put(fkField.getName(), pkField.getName());
}
/**
* INTERNAL:
* We store these to validate the primary class when processing
* the entity class.
*/
public void addPKClassId(String attributeName, Type type) {
m_pkClassIDs.put(attributeName, type);
}
/**
* INTERNAL:
* Add a property to the descriptor. Will check for an override/ignore case.
*/
public void addProperty(PropertyMetadata property) {
if (property.shouldOverride(m_properties.get(property.getName()))) {
m_properties.put(property.getName(), property);
m_descriptor.getProperties().put(property.getName(), property.getConvertedValue());
}
}
/**
* INTERNAL:
*/
public void addPrimaryKeyField(DatabaseField field) {
m_descriptor.addPrimaryKeyField(field);
}
/**
* INTERNAL:
* Store relationship accessors for later processing and quick look up.
*/
public void addRelationshipAccessor(MetadataAccessor accessor) {
m_relationshipAccessors.add((RelationshipAccessor) accessor);
// Store bidirectional ManyToMany relationships so that we may look at
// attribute names when defaulting join columns.
if (accessor.isManyToMany()) {
String mappedBy = ((ManyToManyAccessor) accessor).getMappedBy();
if (mappedBy != null && ! mappedBy.equals("")) {
String referenceClassName = ((ManyToManyAccessor) accessor).getReferenceClassName();
// Initialize the map of bi-directional mappings for this class.
if (! m_biDirectionalManyToManyAccessors.containsKey(referenceClassName)) {
m_biDirectionalManyToManyAccessors.put(referenceClassName, new HashMap<String, MetadataAccessor>());
}
m_biDirectionalManyToManyAccessors.get(referenceClassName).put(mappedBy, accessor);
}
}
m_accessor.getProject().addAccessorWithRelationships(m_accessor);
}
/**
* INTERNAL:
*/
public void addTable(DatabaseTable table) {
m_descriptor.addTable(table);
}
/**
* INTERNAL:
*/
public boolean excludeSuperclassListeners() {
return m_descriptor.getEventManager().excludeSuperclassListeners();
}
/**
* INTERNAL:
* This method will first check for an accessor with name equal to
* fieldOrPropertyName (that is, assumes it is a field name). If no accessor
* is found than it assumes fieldOrPropertyName is a property name and
* converts it to its corresponding field name and looks for the accessor
* again. If still no accessor is found and this descriptor metadata is
* and an inheritance subclass, than it will then look on the root metadata
* descriptor. Null is returned otherwise.
*/
public MappingAccessor getAccessorFor(String fieldOrPropertyName) {
MappingAccessor accessor = m_accessors.get(fieldOrPropertyName);
if (accessor == null) {
// Perhaps we have a property name ...
accessor = m_accessors.get(MetadataMethod.getAttributeNameFromMethodName(fieldOrPropertyName));
// If still no accessor and we are an inheritance subclass, check
// the root descriptor now.
if (accessor == null && isInheritanceSubclass()) {
accessor = getInheritanceParentDescriptor().getAccessorFor(fieldOrPropertyName);
}
}
return accessor;
}
/**
* INTERNAL:
*/
public String getAlias() {
return m_descriptor.getAlias();
}
/**
* INTERNAL:
*/
public AssociationOverrideMetadata getAssociationOverrideFor(String attributeName) {
return m_associationOverrides.get(attributeName);
}
/**
* INTERNAL:
*/
public AttributeOverrideMetadata getAttributeOverrideFor(String attributeName) {
return m_attributeOverrides.get(attributeName);
}
/**
* INTERNAL:
*/
public List<BasicCollectionAccessor> getBasicCollectionAccessors() {
return m_basicCollectionAccessors;
}
/**
* INTERNAL:
*/
public DatabaseField getClassIndicatorField() {
if (isInheritanceSubclass()) {
return getInheritanceParentDescriptor().getClassDescriptor().getInheritancePolicy().getClassIndicatorField();
} else {
if (getClassDescriptor().hasInheritance()) {
return getClassDescriptor().getInheritancePolicy().getClassIndicatorField();
} else {
return null;
}
}
}
/**
* INTERNAL:
* The default table name is the descriptor alias, unless this descriptor
* metadata is an inheritance subclass with a SINGLE_TABLE strategy. Then
* it is the table name of the root descriptor metadata.
*/
public String getDefaultTableName() {
String defaultTableName = getAlias().toUpperCase();
if (isInheritanceSubclass()) {
if (getInheritanceParentDescriptor().usesSingleTableInheritanceStrategy()) {
defaultTableName = getInheritanceParentDescriptor().getPrimaryTableName();
}
}
return defaultTableName;
}
/**
* INTERNAL:
*/
public ClassAccessor getClassAccessor() {
return m_accessor;
}
/**
* INTERNAL:
*/
public ClassDescriptor getClassDescriptor() {
return m_descriptor;
}
/**
* INTERNAL:
*/
public String getEmbeddedIdAttributeName() {
return m_embeddedIdAttributeName;
}
/**
* INTERNAL:
* Return the primary key attribute name for this entity.
*/
public String getIdAttributeName() {
if (getIdAttributeNames().isEmpty()) {
if (isInheritanceSubclass()) {
return getInheritanceParentDescriptor().getIdAttributeName();
} else {
return "";
}
} else {
return getIdAttributeNames().get(0);
}
}
/**
* INTERNAL:
* Return the id attribute names declared on this descriptor metadata.
*/
public List<String> getIdAttributeNames() {
return m_idAttributeNames;
}
/**
* INTERNAL:
* Return the primary key attribute names for this entity. If there are no
* id attribute names set then we are either:
* 1) an inheritance subclass, get the id attribute names from the root
* of the inheritance structure.
* 2) we have an embedded id. Get the id attribute names from the embedded
* descriptor metadata, which is equal the attribute names of all the
* direct to field mappings on that descriptor metadata. Currently does
* not traverse nested embeddables.
*/
public List<String> getIdOrderByAttributeNames() {
if (m_idOrderByAttributeNames.isEmpty()) {
if (m_idAttributeNames.isEmpty()) {
if (isInheritanceSubclass()) {
// Get the id attribute names from our root parent.
m_idOrderByAttributeNames = getInheritanceParentDescriptor().getIdAttributeNames();
} else {
// We must have a composite primary key as a result of an embedded id.
m_idOrderByAttributeNames = ((MappingAccessor) getAccessorFor(getEmbeddedIdAttributeName())).getReferenceDescriptor().getOrderByAttributeNames();
}
} else {
m_idOrderByAttributeNames = m_idAttributeNames;
}
}
return m_idOrderByAttributeNames;
}
/**
* INTERNAL:
* Assumes hasBidirectionalManyToManyAccessorFor has been called before
* hand.
*/
public MetadataAccessor getBiDirectionalManyToManyAccessor(String className, String attributeName) {
return m_biDirectionalManyToManyAccessors.get(className).get(attributeName);
}
/**
* INTERNAL:
* This will return the attribute names for all the direct to field mappings
* on this descriptor metadata. This method will typically be called when an
* @Embedded or @EmbeddedId attribute has been specified in an @OrderBy.
*/
public List<String> getOrderByAttributeNames() {
if (m_orderByAttributeNames.isEmpty()) {
for (DatabaseMapping mapping : getMappings()) {
if (mapping.isDirectToFieldMapping()) {
m_orderByAttributeNames.add(mapping.getAttributeName());
}
}
}
return m_orderByAttributeNames;
}
/**
* INTERNAL:
*/
public Class getJavaClass() {
return m_javaClass;
}
/**
* INTERNAL:
*/
public String getJavaClassName() {
return m_descriptor.getJavaClassName();
}
/**
* INTERNAL:
*/
public MetadataLogger getLogger() {
return getProject().getLogger();
}
/**
* INTERNAL:
*/
public MetadataDescriptor getInheritanceParentDescriptor() {
return m_inheritanceParentDescriptor;
}
/**
* INTERNAL:
*/
public DatabaseMapping getMappingForAttributeName(String attributeName) {
return getMappingForAttributeName(attributeName, null);
}
/**
* INTERNAL:
* Non-owning mappings that need to look up the owning mapping, should call
* this method with their respective accessor to check for circular mappedBy
* references. If the referencingAccessor is null, no check will be made.
*/
public DatabaseMapping getMappingForAttributeName(String attributeName, MetadataAccessor referencingAccessor) {
MetadataAccessor accessor = getAccessorFor(attributeName);
if (accessor != null) {
// If the accessor is a relationship accessor than it may or may
// not have been processed yet. Fast track its processing if it
// needs to be. The process call will do nothing if it has already
// been processed.
if (accessor.isRelationship()) {
RelationshipAccessor relationshipAccessor = (RelationshipAccessor) accessor;
// Check that we don't have circular mappedBy values which
// will cause an infinite loop.
if (referencingAccessor != null && (relationshipAccessor.isOneToOne() || relationshipAccessor.isCollectionAccessor())) {
String mappedBy = null;
if (relationshipAccessor.isOneToOne()) {
mappedBy = ((OneToOneAccessor) relationshipAccessor).getMappedBy();
} else {
mappedBy = ((CollectionAccessor) relationshipAccessor).getMappedBy();
}
if (mappedBy != null && mappedBy.equals(referencingAccessor.getAttributeName())) {
throw ValidationException.circularMappedByReferences(referencingAccessor.getJavaClass(), referencingAccessor.getAttributeName(), getJavaClass(), attributeName);
}
}
relationshipAccessor.processRelationship();
}
return m_descriptor.getMappingForAttributeName(attributeName);
}
// We didn't find a mapping on this descriptor, check our aggregate
// descriptors now.
for (MetadataDescriptor embeddableDescriptor : m_embeddableDescriptors) {
DatabaseMapping mapping = embeddableDescriptor.getMappingForAttributeName(attributeName, referencingAccessor);
if (mapping != null) {
return mapping;
}
}
// We didn't find a mapping on the aggregate descriptors. If we are an
// inheritance subclass, check for a mapping on the inheritance root
// descriptor metadata.
if (isInheritanceSubclass()) {
return getInheritanceParentDescriptor().getMappingForAttributeName(attributeName, referencingAccessor);
}
// Found nothing ... return null.
return null;
}
/**
* INTERNAL:
*/
public List<DatabaseMapping> getMappings() {
return m_descriptor.getMappings();
}
/**
* INTERNAL:
*/
public String getPKClassName() {
String pkClassName = null;
if (m_descriptor.hasCMPPolicy()) {
pkClassName = ((CMP3Policy) m_descriptor.getCMPPolicy()).getPKClassName();
}
return pkClassName;
}
/**
* INTERNAL:
* Method to return the primary key field name for the given descriptor
* metadata. Assumes there is one.
*/
public String getPrimaryKeyFieldName() {
return (getPrimaryKeyFields().iterator().next()).getName();
}
/**
* INTERNAL:
* Method to return the primary key field names for the given descriptor
* metadata. getPrimaryKeyFieldNames() on ClassDescriptor returns qualified
* names. We don't want that.
*/
public List<String> getPrimaryKeyFieldNames() {
List<DatabaseField> primaryKeyFields = getPrimaryKeyFields();
List<String> primaryKeyFieldNames = new ArrayList<String>(primaryKeyFields.size());
for (DatabaseField primaryKeyField : primaryKeyFields) {
primaryKeyFieldNames.add(primaryKeyField.getName());
}
return primaryKeyFieldNames;
}
/**
* INTERNAL:
* Return the primary key fields for this descriptor metadata. If this is
* an inheritance subclass and it has no primary key fields, then grab the
* primary key fields from the root.
*/
public List<DatabaseField> getPrimaryKeyFields() {
List<DatabaseField> primaryKeyFields = m_descriptor.getPrimaryKeyFields();
if (primaryKeyFields.isEmpty() && isInheritanceSubclass()) {
primaryKeyFields = getInheritanceParentDescriptor().getPrimaryKeyFields();
}
return primaryKeyFields;
}
/**
* INTERNAL:
* Recursively check the potential chaining of the primary key fields from
* a inheritance subclass, all the way to the root of the inheritance
* hierarchy.
*/
public String getPrimaryKeyJoinColumnAssociation(String foreignKeyName) {
String primaryKeyName = m_pkJoinColumnAssociations.get(foreignKeyName);
if (primaryKeyName == null || ! isInheritanceSubclass()) {
return foreignKeyName;
} else {
return getInheritanceParentDescriptor().getPrimaryKeyJoinColumnAssociation(primaryKeyName);
}
}
/**
* INTERNAL:
* Assumes there is one primary key field set. This method should be called
* when qualifying any primary key field (from a join column) for this
* descriptor. This method was created because in an inheritance hierarchy
* with a joined strategy we can't use getPrimaryTableName() since it would
* return the wrong table name. From the spec, the primary key must be
* defined on the entity that is the root of the entity hierarchy or on a
* mapped superclass of the entity hierarchy. The primary key must be
* defined exactly once in an entity hierarchy.
*/
public DatabaseTable getPrimaryKeyTable() {
return ((getPrimaryKeyFields().iterator().next())).getTable();
}
/**
* INTERNAL:
*/
public DatabaseTable getPrimaryTable() {
if (m_primaryTable == null && isInheritanceSubclass()) {
return getInheritanceParentDescriptor().getPrimaryTable();
} else {
if (m_descriptor.isAggregateDescriptor()) {
// Aggregate descriptors don't have tables, just return a
// a default empty table.
return new DatabaseTable();
}
return m_primaryTable;
}
}
/**
* INTERNAL:
*/
public String getPrimaryTableName() {
return getPrimaryTable().getName();
}
/**
* INTERNAL:
*/
public MetadataProject getProject() {
return getClassAccessor().getProject();
}
/**
* INTERNAL:
*/
public List<RelationshipAccessor> getRelationshipAccessors() {
return m_relationshipAccessors;
}
/**
* INTERNAL:
*/
protected ReturningPolicy getReturningPolicy() {
if (! m_descriptor.hasReturningPolicy()) {
m_descriptor.setReturningPolicy(new ReturningPolicy());
}
return m_descriptor.getReturningPolicy();
}
/**
* INTERNAL:
*/
public DatabaseField getSequenceNumberField() {
return m_descriptor.getSequenceNumberField();
}
/**
* INTERNAL:
*/
public String getXMLAccess() {
return m_xmlAccess;
}
/**
* INTERNAL:
*/
public String getXMLCatalog() {
return m_xmlCatalog;
}
/**
* INTERNAL:
*/
public String getXMLSchema() {
return m_xmlSchema;
}
/**
* INTERNAL:
*/
public boolean hasAssociationOverrideFor(String attributeName) {
return m_associationOverrides.containsKey(attributeName);
}
/**
* INTERNAL:
*/
public boolean hasAttributeOverrideFor(String attributeName) {
return m_attributeOverrides.containsKey(attributeName);
}
/**
* INTERNAL:
*/
public boolean hasCompositePrimaryKey() {
return getPrimaryKeyFields().size() > 1 || getPKClassName() != null;
}
/**
* INTERNAL:
*/
public boolean hasEmbeddedIdAttribute() {
return m_embeddedIdAttributeName != null;
}
/**
* INTERNAL:
*/
public boolean hasExistenceChecking() {
return m_existenceChecking != null;
}
/**
* INTERNAL:
*/
public boolean hasInheritance() {
return m_descriptor.hasInheritance();
}
/**
* INTERNAL:
*/
public boolean hasBiDirectionalManyToManyAccessorFor(String className, String attributeName) {
if (m_biDirectionalManyToManyAccessors.containsKey(className)) {
return m_biDirectionalManyToManyAccessors.get(className).containsKey(attributeName);
}
return false;
}
/**
* INTERNAL:
* Indicates that a Cache annotation or cache element has already been
* processed for this descriptor.
*/
public boolean hasCache() {
return m_hasCache;
}
/**
* INTERNAL:
* Indicates that a Change tracking annotation or change tracking element
* has already been processed for this descriptor.
*/
public boolean hasChangeTracking() {
return m_hasChangeTracking;
}
/**
* INTERNAL:
* Indicates that a copy Policy annotation or copy policy element
* has already been processed for this descriptor.
*/
public boolean hasCopyPolicy() {
return m_hasCopyPolicy;
}
/**
* INTERNAL:
* Indicates that a customizer annotation or customizer element has already
* been processed for this descriptor.
*/
public boolean hasCustomizer() {
return m_hasCustomizer;
}
/**
* INTERNAL:
* Indicates that a read only annotation or read only element has already
* been processed for this descriptor.
*/
public boolean hasReadOnly() {
return m_hasReadOnly;
}
/**
* INTERNAL:
*/
protected boolean havePersistenceAnnotationsDefined(Field[] fields) {
for (Field field : fields) {
MetadataField metadataField = new MetadataField(field, getLogger());
if (metadataField.hasDeclaredAnnotations(this)) {
return true;
}
}
return false;
}
/**
* INTERNAL:
*/
protected boolean havePersistenceAnnotationsDefined(Method[] methods) {
for (Method method : methods) {
MetadataMethod metadataMethod = new MetadataMethod(method, getLogger());
if (metadataMethod.hasDeclaredAnnotations(this)) {
return true;
}
}
return false;
}
/**
* INTERNAL:
*/
public boolean hasMappingForAttributeName(String attributeName) {
return m_descriptor.getMappingForAttributeName(attributeName) != null;
}
/**
* INTERNAL:
* Return true is the descriptor has primary key fields set.
*/
public boolean hasPrimaryKeyFields() {
return m_descriptor.getPrimaryKeyFields().size() > 0;
}
/**
* INTERNAL:
* Indicates whether or not annotations should be ignored, i.e. only default
* values processed.
*/
public boolean ignoreAnnotations() {
return m_ignoreAnnotations;
}
/**
* INTERNAL:
* Indicates that cascade-persist should be applied to all relationship
* mappings for this entity.
*/
public boolean isCascadePersist() {
return m_isCascadePersist;
}
/**
* INTERNAL:
*/
public boolean isEmbeddable() {
return m_descriptor.isAggregateDescriptor();
}
/**
* INTERNAL:
*/
public boolean isEmbeddableCollection() {
return m_descriptor.isAggregateCollectionDescriptor();
}
/**
* INTERNAL:
*/
public boolean isInheritanceSubclass() {
return m_inheritanceParentDescriptor != null;
}
/**
* INTERNAL:
* Indicates that we found an XML field access type for this metadata
* descriptor.
*/
protected boolean isXmlFieldAccess() {
return isXmlFieldAccess(m_xmlAccess);
}
/**
* INTERNAL:
*/
protected boolean isXmlFieldAccess(String access) {
return access != null && access.equals(FIELD);
}
/**
* INTERNAL:
* Indicates that we found an XML property access type for this metadata
* descriptor.
*/
protected boolean isXmlPropertyAccess() {
return isXmlPropertyAccess(m_xmlAccess);
}
/**
* INTERNAL:
*/
protected boolean isXmlPropertyAccess(String access) {
return access != null && access.equals(PROPERTY);
}
/**
* INTERNAL:
*/
public boolean pkClassWasNotValidated() {
return ! m_pkClassIDs.isEmpty();
}
/**
* INTERNAL:
*/
public void setAlias(String alias) {
m_descriptor.setAlias(alias);
}
/**
* INTERNAL:
*/
public void setClassAccessor(ClassAccessor accessor) {
m_accessor = accessor;
accessor.setDescriptor(this);
}
/**
* INTERNAL:
*/
public void setClassIndicatorField(DatabaseField field) {
m_descriptor.getInheritancePolicy().setClassIndicatorField(field);
}
/**
* INTERNAL:
*/
public void setDescriptor(ClassDescriptor descriptor) {
m_descriptor = descriptor;
}
/**
* INTERNAL:
*/
public void setEmbeddedIdAttributeName(String embeddedIdAttributeName) {
m_embeddedIdAttributeName = embeddedIdAttributeName;
}
/**
* INTERNAL:
*/
public void setEntityEventListener(EntityListener listener) {
m_descriptor.getEventManager().setEntityEventListener(listener);
}
/**
* INTERNAL:
*/
public void setExcludeDefaultListeners(boolean excludeDefaultListeners) {
m_descriptor.getEventManager().setExcludeDefaultListeners(excludeDefaultListeners);
}
/**
* INTERNAL:
*/
public void setExcludeSuperclassListeners(boolean excludeSuperclassListeners) {
m_descriptor.getEventManager().setExcludeSuperclassListeners(excludeSuperclassListeners);
}
/**
* INTERNAL:
*/
public void setExistenceChecking(ExistenceType existenceChecking) {
m_existenceChecking = existenceChecking;
if (existenceChecking.equals(ExistenceType.CHECK_CACHE)) {
m_descriptor.getQueryManager().checkCacheForDoesExist();
} else if (existenceChecking.equals(ExistenceType.CHECK_DATABASE)) {
m_descriptor.getQueryManager().checkDatabaseForDoesExist();
} else if (existenceChecking.equals(ExistenceType.ASSUME_EXISTENCE)) {
m_descriptor.getQueryManager().assumeExistenceForDoesExist();
} else if (existenceChecking.equals(ExistenceType.ASSUME_NON_EXISTENCE)) {
m_descriptor.getQueryManager().assumeNonExistenceForDoesExist();
}
}
/**
* INTERNAL:
* Indicates that we have processed a cache annotation or cache xml element.
*/
public void setHasCache() {
m_hasCache = true;
}
/**
* INTERNAL:
* Indicates that we have processed a change tracking annotation or change
* tracking xml element.
*/
public void setHasChangeTracking() {
m_hasChangeTracking = true;
}
/**
* INTERNAL:
* Indicates that we have processed a copy policy annotation or copy policy xml element.
*/
public void setHasCopyPolicy() {
m_hasCopyPolicy = true;
}
/**
* INTERNAL:
* Indicates that all annotations should be ignored, and only default values
* set by the annotations processor.
*/
public void setIgnoreAnnotations(boolean ignoreAnnotations) {
m_ignoreAnnotations = ignoreAnnotations;
}
/**
* INTERNAL:
* Store the root class of an inheritance hierarchy.
*/
public void setInheritanceParentDescriptor(MetadataDescriptor inheritanceParentDescriptor) {
m_inheritanceParentDescriptor = inheritanceParentDescriptor;
}
/**
* INTERNAL:
* Indicates that cascade-persist should be added to the set of cascade
* values for all relationship mappings.
*/
public void setIsCascadePersist(boolean isCascadePersist) {
m_isCascadePersist = isCascadePersist;
}
/**
* INTERNAL:
*/
public void setIsEmbeddable() {
m_descriptor.descriptorIsAggregate();
}
/**
* INTERNAL:
* Used to set this descriptors java class.
*/
public void setJavaClass(Class javaClass) {
m_javaClass = javaClass;
m_descriptor.setJavaClassName(javaClass.getName());
// If the javaClass is an interface, add it to the java interface name
// on the relational descriptor.
if (javaClass.isInterface()) {
m_descriptor.setJavaInterfaceName(javaClass.getName());
}
}
/**
* INTERNAL:
*/
public void setOptimisticLockingPolicy(OptimisticLockingPolicy policy) {
m_descriptor.setOptimisticLockingPolicy(policy);
}
/**
* INTERNAL:
* Set the inheritance parent class for this class.
*/
public void setParentClass(Class parent) {
m_descriptor.getInheritancePolicy().setParentClassName(parent.getName());
}
/**
* INTERNAL:
*/
public void setPKClass(Class pkClass) {
setPKClass(pkClass.getName());
}
/**
* INTERNAL:
*/
public void setPKClass(String pkClassName) {
CMP3Policy policy = new CMP3Policy();
policy.setPrimaryKeyClassName(pkClassName);
m_descriptor.setCMPPolicy(policy);
}
/**
* INTERNAL:
*/
public void setPrimaryTable(DatabaseTable primaryTable) {
addTable(primaryTable);
m_primaryTable = primaryTable;
}
/**
* INTERNAL:
*/
public void setReadOnly(boolean readOnly) {
if (readOnly) {
m_descriptor.setReadOnly();
}
m_hasReadOnly = true;
}
/**
* INTERNAL:
*/
public void setSequenceNumberField(DatabaseField field) {
m_descriptor.setSequenceNumberField(field);
}
/**
* INTERNAL:
*/
public void setSequenceNumberName(String name) {
m_descriptor.setSequenceNumberName(name);
}
/**
* INTERNAL:
* Sets the strategy on the descriptor's inheritance policy to SINGLE_TABLE.
* The default is JOINED.
*/
public void setSingleTableInheritanceStrategy() {
m_descriptor.getInheritancePolicy().setSingleTableStrategy();
}
/**
* INTERNAL:
*/
public void setUsesCascadedOptimisticLocking(Boolean usesCascadedOptimisticLocking) {
m_usesCascadedOptimisticLocking = usesCascadedOptimisticLocking;
}
/**
* INTERNAL:
*
* Set the access-type while processing a class like Embeddable as it
* inherits the access-type from the referencing entity.
*/
public void setUsesPropertyAccess(Boolean usesPropertyAccess) {
m_usesPropertyAccess = usesPropertyAccess;
}
/**
* INTERNAL:
*/
public void setXMLAccess(String xmlAccess) {
m_xmlAccess = xmlAccess;
}
/**
* INTERNAL:
*/
public void setXMLCatalog(String xmlCatalog) {
m_xmlCatalog = xmlCatalog;
}
/**
* INTERNAL:
*/
public void setXMLSchema(String xmlSchema) {
m_xmlSchema = xmlSchema;
}
/**
* INTERNAL:
*/
public boolean usesCascadedOptimisticLocking() {
return m_usesCascadedOptimisticLocking != null && m_usesCascadedOptimisticLocking.booleanValue();
}
/**
* INTERNAL:
* Indicates if the strategy on the descriptor's inheritance policy is
* JOINED.
*/
public boolean usesJoinedInheritanceStrategy() {
return m_descriptor.getInheritancePolicy().isJoinedStrategy();
}
/**
* INTERNAL:
*/
public boolean usesOptimisticLocking() {
return m_descriptor.usesOptimisticLocking();
}
/**
* INTERNAL:
* Returns true if this class uses property access. In an inheritance
* hierarchy, the subclasses inherit their access type from the parent.
* The metadata helper method caches the class access types for
* efficiency.
*/
public boolean usesPropertyAccess() {
if (isInheritanceSubclass()) {
return getInheritanceParentDescriptor().usesPropertyAccess();
} else {
if (m_usesPropertyAccess == null) {
if (havePersistenceAnnotationsDefined(MetadataHelper.getFields(getJavaClass())) || isXmlFieldAccess()) {
// We have persistence annotations defined on a field from
// the entity or field access has been set via XML, set the
// access to FIELD.
m_usesPropertyAccess = Boolean.FALSE;
} else if (havePersistenceAnnotationsDefined(MetadataHelper.getDeclaredMethods(getJavaClass())) || isXmlPropertyAccess()) {
// We have persistence annotations defined on a method from
// the entity or method access has been set via XML, set the
// access to PROPERTY.
m_usesPropertyAccess = Boolean.TRUE;
} else {
for (ClassAccessor mappedSuperclass : getClassAccessor().getMappedSuperclasses()) {
if (havePersistenceAnnotationsDefined(MetadataHelper.getFields(mappedSuperclass.getJavaClass())) || isXmlFieldAccess(mappedSuperclass.getAccess())) {
// We have persistence annotations defined on a
// field from a mapped superclass, set the access
// to FIELD.
m_usesPropertyAccess = Boolean.FALSE;
break;
} else if (havePersistenceAnnotationsDefined(MetadataHelper.getDeclaredMethods(mappedSuperclass.getJavaClass())) || isXmlPropertyAccess(mappedSuperclass.getAccess())) {
// We have persistence annotations defined on a
// method from a mapped superclass, set the access
// to FIELD.
m_usesPropertyAccess = Boolean.TRUE;
break;
}
}
// We still found nothing ... we should throw an exception
// here, but for now, set the access to FIELD. The user
// will eventually get an exception saying there is no
// primary key set if field access is not actually the
// case.
if (m_usesPropertyAccess == null) {
m_usesPropertyAccess = Boolean.FALSE;
}
}
}
return m_usesPropertyAccess;
}
}
/**
* INTERNAL:
* Indicates if the strategy on the descriptor's inheritance policy is
* SINGLE_TABLE.
*/
public boolean usesSingleTableInheritanceStrategy() {
return ! usesJoinedInheritanceStrategy();
}
/**
* INTERNAL:
* Return true if this descriptors class processed OptimisticLocking
* meta data of type VERSION_COLUMN.
*/
public boolean usesVersionColumnOptimisticLocking() {
// If an optimistic locking metadata of type VERSION_COLUMN was not
// specified, then m_usesCascadedOptimisticLocking will be null, that
// is, we won't have processed the cascade value.
return m_usesCascadedOptimisticLocking != null;
}
/**
* INTERNAL:
* This method is used only to validate id fields that were found on a
* pk class were also found on the entity.
*/
public void validatePKClassId(String attributeName, Type type) {
if (m_pkClassIDs.containsKey(attributeName)) {
Type expectedType = m_pkClassIDs.get(attributeName);
if (type == expectedType) {
m_pkClassIDs.remove(attributeName);
} else {
throw ValidationException.invalidCompositePKAttribute(getJavaClass(), getPKClassName(), attributeName, expectedType, type);
}
}
}
}
|
package com.matthewtamlin.spyglass.library.default_annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface DefaultToStringResource {
int value();
}
|
package org.safehaus.kiskis.mgmt.api.monitor;
public enum Metric {
CPU_USER("%"),
CPU_SYSTEM("%"),
CPU_IDLE("%"),
CPU_WIO("%"),
MEM_FREE("KB"),
MEM_CACHED("KB"),
MEM_BUFFERS("KB"),
SWAP_FREE("KB"),
PKTS_IN("packets/sec"),
PKTS_OUT("packets/sec"),
BYTES_IN("bytes/sec"),
BYTES_OUT("bytes/sec"),
PART_MAX_USED("%");
private String unit = "";
private Metric(String unit) {
this.unit = unit;
}
public String getUnit() {
return unit;
}
}
|
package io.github.zutherb.appstash.shop.service.order.model;
import io.github.zutherb.appstash.shop.service.user.model.UserInfo;
import io.github.zutherb.appstash.shop.service.user.model.UserInfo;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* @author zutherb
*/
public class OrderInfo implements Serializable {
private Long orderId;
private UserInfo user;
private List<OrderItemInfo> orderItems;
private DeliveryAddressInfo deliveryAddress;
private Date orderDate;
private String sessionId;
private OrderInfo() {
}
public OrderInfo(UserInfo user, DeliveryAddressInfo deliveryAddress, List<OrderItemInfo> orderItems, String sessionId) {
this.user = user;
this.orderItems = orderItems;
this.deliveryAddress = deliveryAddress;
this.sessionId = sessionId;
}
public OrderInfo(Long orderId, String sessionId, OrderInfo orderInfo) {
this.orderId = orderId;
this.sessionId = sessionId;
this.user = orderInfo.getUser();
this.orderItems = orderInfo.getOrderItems();
this.deliveryAddress = orderInfo.getDeliveryAddress();
}
public OrderInfo(Long orderId, OrderInfo orderInfo, List<OrderItemInfo> orderItemInfos, String sessionId) {
this(orderId, sessionId, orderInfo);
this.orderItems = orderItemInfos;
this.sessionId = sessionId;
}
public String getSessionId() {
return sessionId;
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
public List<OrderItemInfo> getOrderItems() {
if (orderItems == null) {
orderItems = new ArrayList<>();
}
return Collections.unmodifiableList(orderItems);
}
public DeliveryAddressInfo getDeliveryAddress() {
return deliveryAddress;
}
public BigDecimal getDiscountSum() {
BigDecimal totalSum = BigDecimal.ZERO;
for (OrderItemInfo orderItemInfo : orderItems) {
totalSum = totalSum.add(orderItemInfo.getTotalSum());
}
double fraction = 25/100;
return totalSum.multiply(new BigDecimal(Double.toString(fraction)));
}
public BigDecimal getTotalSum() {
BigDecimal totalSum = BigDecimal.ZERO;
for (OrderItemInfo orderItemInfo : orderItems) {
totalSum = totalSum.add(orderItemInfo.getTotalSum());
}
// double fraction = 25/100;
// return totalSum.subtract(totalSum.multiply(new BigDecimal(fraction)));
return totalSum;
}
public Long getOrderId() {
return orderId;
}
public Date getOrderDate() {
return orderDate;
}
}
|
package org.motechproject.ivr.kookoo.repository;
import org.ektorp.CouchDbConnector;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.ivr.kookoo.domain.KookooCallDetailRecord;
import org.motechproject.server.service.ivr.CallDetailRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/ivrKookooRepositories.xml"})
public class AllKooKooCallDetailRecordsIT {
@Autowired
private AllKooKooCallDetailRecords allKooKooCallDetailRecords;
@Autowired
@Qualifier("kookooIvrDbConnector")
private CouchDbConnector ivrKookooCouchDbConnector;
@Test
public void shouldFindCallDetailRecordByCallId() {
CallDetailRecord callDetailRecord = CallDetailRecord.newIncomingCallRecord("phoneNumber");
KookooCallDetailRecord kookooCallDetailRecord = new KookooCallDetailRecord(callDetailRecord);
allKooKooCallDetailRecords.add(kookooCallDetailRecord);
KookooCallDetailRecord result = allKooKooCallDetailRecords.findByCallId(kookooCallDetailRecord.getCallId());
assertNotNull(result);
ivrKookooCouchDbConnector.delete(kookooCallDetailRecord);
}
}
|
package name.abuchen.portfolio.ui.views.dashboard;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.function.Supplier;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import name.abuchen.portfolio.model.Dashboard;
import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.money.Money;
import name.abuchen.portfolio.money.MutableMoney;
import name.abuchen.portfolio.money.Values;
import name.abuchen.portfolio.snapshot.ClientPerformanceSnapshot;
import name.abuchen.portfolio.snapshot.ClientPerformanceSnapshot.CategoryType;
import name.abuchen.portfolio.snapshot.PerformanceIndex;
import name.abuchen.portfolio.ui.Messages;
public class PerformanceCalculationWidget extends WidgetDelegate<ClientPerformanceSnapshot>
{
enum TableLayout
{
FULL(Messages.LabelLayoutFull), REDUCED(Messages.LabelLayoutReduced), RELEVANT(Messages.LabelLayoutRelevant);
private String label;
private TableLayout(String label)
{
this.label = label;
}
@Override
public String toString()
{
return label;
}
}
static class LayoutConfig extends EnumBasedConfig<TableLayout>
{
public LayoutConfig(WidgetDelegate<?> delegate)
{
super(delegate, Messages.LabelLayout, TableLayout.class, Dashboard.Config.LAYOUT, Policy.EXACTLY_ONE);
}
}
private Composite container;
private DashboardResources resources;
private Label title;
private Label[] signs;
private Label[] labels;
private Label[] values;
public PerformanceCalculationWidget(Widget widget, DashboardData dashboardData)
{
super(widget, dashboardData);
addConfig(new ReportingPeriodConfig(this));
addConfig(new DataSeriesConfig(this, false));
addConfig(new LayoutConfig(this));
}
@Override
public Composite createControl(Composite parent, DashboardResources resources)
{
this.resources = resources;
container = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().numColumns(3).margins(5, 5).spacing(3, 3).applyTo(container);
container.setBackground(parent.getBackground());
title = new Label(container, SWT.NONE);
title.setText(getWidget().getLabel());
GridDataFactory.fillDefaults().span(3, 1).hint(SWT.DEFAULT, title.getFont().getFontData()[0].getHeight() + 10)
.grab(true, false).applyTo(title);
TableLayout layout = get(LayoutConfig.class).getValue();
createControls(layout);
return container;
}
private void createControls(TableLayout layout)
{
// used to detect if we need to re-create the full table
title.setData(layout);
switch (layout)
{
case FULL:
createTable(ClientPerformanceSnapshot.CategoryType.values().length);
break;
case REDUCED:
createTable(5);
break;
case RELEVANT:
createTable(7);
break;
default:
throw new IllegalArgumentException();
}
}
private void createTable(int size)
{
Font boldFont = resources.getResourceManager()
.createFont(FontDescriptor.createFrom(container.getFont()).setStyle(SWT.BOLD));
labels = new Label[size];
signs = new Label[size];
values = new Label[size];
for (int ii = 0; ii < size; ii++)
{
signs[ii] = new Label(container, SWT.NONE);
labels[ii] = new Label(container, SWT.NONE);
values[ii] = new Label(container, SWT.RIGHT);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).applyTo(values[ii]);
if (ii == 0 || ii == size - 1) // first and last line
{
signs[ii].setFont(boldFont);
labels[ii].setFont(boldFont);
values[ii].setFont(boldFont);
}
if (ii == 0 || ii == size - 2) // after first and before last line
{
Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
GridDataFactory.fillDefaults().span(3, 1).grab(true, false).align(SWT.FILL, SWT.BEGINNING)
.applyTo(separator);
}
}
}
@Override
public Control getTitleControl()
{
return title;
}
@Override
public Supplier<ClientPerformanceSnapshot> getUpdateTask()
{
return () -> {
PerformanceIndex index = getDashboardData().calculate(get(DataSeriesConfig.class).getDataSeries(),
get(ReportingPeriodConfig.class).getReportingPeriod());
return index.getClientPerformanceSnapshot();
};
}
@Override
public void update(ClientPerformanceSnapshot snapshot)
{
TableLayout layout = get(LayoutConfig.class).getValue();
if (!layout.equals(title.getData()))
{
for (Control child : container.getChildren())
if (!title.equals(child))
child.dispose();
createControls(layout);
container.getParent().layout(true);
container.getParent().getParent().layout(true);
}
title.setText(getWidget().getLabel());
switch (layout)
{
case FULL:
filInValues(0, snapshot.getCategories());
break;
case REDUCED:
fillInReducedValues(snapshot);
break;
case RELEVANT:
fillInOnlyRelevantValues(snapshot);
break;
default:
throw new IllegalArgumentException();
}
container.layout();
}
private void fillInOnlyRelevantValues(final ClientPerformanceSnapshot snapshot)
{
List<ClientPerformanceSnapshot.Category> categories = snapshot.getCategories();
// header
LocalDate startDate = snapshot.getStartClientSnapshot().getTime();
String header = MessageFormat.format(Messages.PerformanceRelevantTransactionsHeader,
Values.Date.format(startDate));
labels[0].setText(header);
for (int i = 1; i < 6; i++)
{
ClientPerformanceSnapshot.Category category = categories.get(i);
signs[i].setText(category.getSign());
labels[i].setText(category.getLabel());
values[i].setText(Values.Money.format(category.getValuation(), getClient().getBaseCurrency()));
}
// footer
signs[6].setText("="); //$NON-NLS-1$
LocalDate endDate = snapshot.getEndClientSnapshot().getTime();
String footer = MessageFormat.format(Messages.PerformanceRelevantTransactionsFooter,
Values.Date.format(endDate));
labels[6].setText(footer);
Money totalRelevantTransactions = sumCategoryValuations(
snapshot.getValue(CategoryType.INITIAL_VALUE).getCurrencyCode(), categories.subList(1, 6));
values[6].setText(Values.Money.format(totalRelevantTransactions, getClient().getBaseCurrency()));
}
/**
* @brief Sums up the total currency for the supplied categories
* @param currencyCode
* The currency code of the currency that is summed up
* @param categories
* The categories for which the total value is computed
* @return
*/
private Money sumCategoryValuations(String currencyCode, List<ClientPerformanceSnapshot.Category> categories)
{
MutableMoney totalMoney = MutableMoney.of(currencyCode);
for (ClientPerformanceSnapshot.Category category : categories)
{
switch (category.getSign())
{
case "+": //$NON-NLS-1$
totalMoney.add(category.getValuation());
break;
case "-": //$NON-NLS-1$
totalMoney.subtract(category.getValuation());
break;
default:
throw new IllegalArgumentException();
}
}
return totalMoney.toMoney();
}
private void filInValues(int startIndex, List<ClientPerformanceSnapshot.Category> categories)
{
int ii = startIndex;
for (ClientPerformanceSnapshot.Category category : categories)
{
signs[ii].setText(category.getSign());
labels[ii].setText(category.getLabel());
values[ii].setText(Values.Money.format(category.getValuation(), getClient().getBaseCurrency()));
if (++ii >= labels.length)
break;
}
}
private void fillInReducedValues(ClientPerformanceSnapshot snapshot)
{
List<ClientPerformanceSnapshot.Category> categories = snapshot.getCategories();
Money misc = sumCategoryValuations(snapshot.getValue(CategoryType.INITIAL_VALUE).getCurrencyCode(),
categories.subList(2, 6));
filInValues(0, categories.subList(0, 2));
signs[2].setText("+"); //$NON-NLS-1$
labels[2].setText(Messages.LabelCategoryOtherMovements);
values[2].setText(Values.Money.format(misc, getClient().getBaseCurrency()));
filInValues(3, categories.subList(categories.size() - 2, categories.size()));
}
}
|
package net.trajano.openidconnect.jaspic.internal;
import static net.trajano.openidconnect.jaspic.internal.Utils.isNullOrEmpty;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.json.JsonObject;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import net.trajano.openidconnect.core.OpenIdConnectKey;
import net.trajano.openidconnect.core.OpenIdProviderConfiguration;
import net.trajano.openidconnect.crypto.Encoding;
import net.trajano.openidconnect.crypto.JsonWebTokenProcessor;
import net.trajano.openidconnect.internal.CharSets;
import net.trajano.openidconnect.jaspic.OpenIdConnectAuthModule;
public class ValidateContext {
private static final String[] AUTH_COOKIE_NAMES = { OpenIdConnectAuthModule.NET_TRAJANO_AUTH_ID, OpenIdConnectAuthModule.NET_TRAJANO_AUTH_AGE, OpenIdConnectAuthModule.NET_TRAJANO_AUTH_NONCE };
private final Client client;
private final Subject clientSubject;
private final String cookieContext;
private final CallbackHandler handler;
private final boolean mandatory;
private OpenIdProviderConfiguration oidConfig;
private final Map<String, String> options;
private final HttpServletRequest req;
private final HttpServletResponse resp;
private SecretKey secret;
private final TokenCookie tokenCookie;
public ValidateContext(final Client client, final Subject clientSubject, final boolean mandatory, final Map<String, String> options, final HttpServletRequest req, final HttpServletResponse resp, final TokenCookie tokenCookie, final String cookieContext, final CallbackHandler handler) {
this.client = client;
this.clientSubject = clientSubject;
this.mandatory = mandatory;
this.options = options;
this.req = req;
this.resp = resp;
this.tokenCookie = tokenCookie;
this.handler = handler;
if (isNullOrEmpty(cookieContext)) {
this.cookieContext = req.getContextPath();
} else {
this.cookieContext = cookieContext;
}
}
/**
* Deletes the authentication cookies.
*/
public void deleteAuthCookies() {
for (final String cookieName : AUTH_COOKIE_NAMES) {
final Cookie deleteCookie = new Cookie(cookieName, "");
deleteCookie.setMaxAge(0);
deleteCookie.setSecure(true);
deleteCookie.setPath(cookieContext);
resp.addCookie(deleteCookie);
}
}
public void deleteCookie(final String cookieName) {
final Cookie deleteNonceCookie = new Cookie(cookieName, "");
deleteNonceCookie.setMaxAge(0);
deleteNonceCookie.setSecure(true);
deleteNonceCookie.setPath(cookieContext);
resp.addCookie(deleteNonceCookie);
}
public Client getClient() {
return client;
}
public Subject getClientSubject() {
return clientSubject;
}
public String getCookie(final String cookieName) {
final Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
for (final Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
public CallbackHandler getHandler() {
return handler;
}
/**
* Gets the id_token from the cookie. It will perform the JWT processing
* needed.
*
* @throws GeneralSecurityException
* @throws IOException
*/
public JsonObject getIdToken() throws IOException,
GeneralSecurityException {
return new JsonWebTokenProcessor(tokenCookie.getIdTokenJwt()).signatureCheck(false)
.getJsonPayload();
}
public synchronized OpenIdProviderConfiguration getOpenIDProviderConfig() {
if (oidConfig == null) {
final String issuerUri = options.get(OpenIdConnectAuthModule.ISSUER_URI_KEY);
if (issuerUri == null) {
// LOG.log(Level.SEVERE, "missingOption", ISSUER_URI_KEY);
// throw new
// AuthException(MessageFormat.format(R.getString("missingOption"),
// ISSUER_URI_KEY));
}
oidConfig = client.target(URI.create(issuerUri)
.resolve("/.well-known/openid-configuration"))
.request(MediaType.APPLICATION_JSON_TYPE)
.get(OpenIdProviderConfiguration.class);
}
return oidConfig;
}
public String getOption(final String key) {
return options.get(key);
}
public Map<String, String> getOptions() {
return options;
}
public HttpServletRequest getReq() {
return req;
}
public HttpServletResponse getResp() {
return resp;
}
public synchronized SecretKey getSecret() throws GeneralSecurityException {
if (secret == null) {
secret = CipherUtil.buildSecretKey(options.get(OpenIdConnectKey.CLIENT_ID), options.get(OpenIdConnectKey.CLIENT_SECRET));
}
return secret;
}
public TokenCookie getTokenCookie() {
return tokenCookie;
}
public URI getUri(final String key) {
return URI.create(req.getRequestURL()
.toString())
.resolve(options.get(key));
}
public boolean hasOption(final String key) {
return options.get(key) != null;
}
public boolean hasTokenCookie() {
return tokenCookie != null;
}
/**
* Checks if the request uses the GET method.
*
* @param req
* request
* @return <code>true</code> if the request uses the GET method.
*/
public boolean isGetRequest() {
return "GET".equals(req.getMethod());
}
public boolean isMandatory() {
return mandatory;
}
/**
* Checks if the request URI matches the option value for the key provided.
*
* @param key
* option key
* @return
*/
public boolean isRequestUri(final String key) {
return req.getRequestURI()
.equals(options.get(key));
}
public boolean isSecure() {
return req.isSecure();
}
/**
* Redirects to the last state. However, if state is equivalent to the
* logout URI it will redirect to the root.
*
* @throws IOException
*/
public void redirectToState() throws IOException {
final String stateEncoded = req.getParameter(OpenIdConnectKey.STATE);
final String contextRedirectUri = Encoding.base64urlDecodeToString(stateEncoded);
final String targetUri = req.getContextPath() + contextRedirectUri;
if (targetUri.equals(options.get(OpenIdConnectAuthModule.LOGOUT_URI_KEY))) {
Log.fine("state was the Logout URI, redirecting to context root");
resp.sendRedirect(resp.encodeRedirectURL(req.getContextPath()));
} else {
resp.sendRedirect(resp.encodeRedirectURL(targetUri));
}
}
public void saveAgeCookie() throws GeneralSecurityException,
IOException {
final Cookie ageCookie = new Cookie(OpenIdConnectAuthModule.NET_TRAJANO_AUTH_AGE, Encoding.base64urlEncode(CipherUtil.encrypt(req.getRemoteAddr()
.getBytes(CharSets.US_ASCII), secret)));
if (isNullOrEmpty(req.getParameter("expires_in"))) {
ageCookie.setMaxAge(3600);
} else {
ageCookie.setMaxAge(Integer.parseInt(req.getParameter("expires_in")));
}
ageCookie.setPath(cookieContext);
ageCookie.setSecure(true);
ageCookie.setHttpOnly(true);
resp.addCookie(ageCookie);
}
/**
* Saves the ID Token cookie.
*
* @param tokenCookie
* @throws GeneralSecurityException
*/
public void saveIdTokenCookie(final TokenCookie tokenCookie) throws GeneralSecurityException {
final Cookie idTokenCookie = new Cookie(OpenIdConnectAuthModule.NET_TRAJANO_AUTH_ID, tokenCookie.toCookieValue(getSecret()));
idTokenCookie.setMaxAge(-1);
idTokenCookie.setSecure(true);
idTokenCookie.setHttpOnly(true);
idTokenCookie.setPath(cookieContext);
resp.addCookie(idTokenCookie);
}
public void setContentType(final String contentType) {
resp.setContentType(contentType);
}
public WebTarget target(final URI uri) {
return client.target(uri);
}
}
|
package org.opennms.web.svclayer.catstatus.support;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.opennms.netmgt.config.categories.Category;
import org.opennms.netmgt.config.viewsdisplay.Section;
import org.opennms.netmgt.config.viewsdisplay.View;
import org.opennms.netmgt.dao.OutageDao;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.netmgt.model.OnmsOutage;
import org.opennms.netmgt.model.OnmsServiceType;
import org.opennms.netmgt.model.ServiceSelector;
import org.opennms.web.svclayer.catstatus.CategoryStatusService;
import org.opennms.web.svclayer.catstatus.model.StatusCategory;
import org.opennms.web.svclayer.catstatus.model.StatusNode;
import org.opennms.web.svclayer.catstatus.model.StatusSection;
import org.opennms.web.svclayer.dao.CategoryConfigDao;
import org.opennms.web.svclayer.dao.ViewDisplayDao;
public class DefaultCategoryStatusService implements CategoryStatusService {
private ViewDisplayDao m_viewDisplayDao;
private CategoryConfigDao m_categoryConfigDao;
private OutageDao m_outagedao;
public Collection<StatusSection> getCategoriesStatus() {
Collection <StatusSection> statusSections = new ArrayList<StatusSection>();
View view = m_viewDisplayDao.getView();
Collection sections = view.getSectionCollection();
for (Iterator iter = sections.iterator(); iter.hasNext();) {
Section section = (Section) iter.next();
StatusSection statusSection = createSection(section);
statusSections.add(statusSection);
}
return statusSections;
}
private StatusSection createSection(Section section) {
StatusSection statusSection = new StatusSection();
statusSection.setName(section.getSectionName());
Collection categories = section.getCategoryCollection();
for (Iterator iter = categories.iterator(); iter.hasNext();){
String category = (String) iter.next();
StatusCategory statusCategory = createCategory(category);
statusSection.addCategory(statusCategory);
}
return statusSection;
}
private StatusCategory createCategory(String category) {
Collection <OnmsOutage>outages;
CategoryBuilder categoryBuilder = new CategoryBuilder();
StatusCategory statusCategory = new StatusCategory();
Category categoryDetail = m_categoryConfigDao.getCategoryByLabel(category);
//statusCategory.setComment(categoryDetail.getCategoryComment());
statusCategory.setLabel(category);
ServiceSelector selector = new ServiceSelector(categoryDetail.getRule(),categoryDetail.getServiceCollection());
outages = m_outagedao.matchingCurrentOutages(selector);
for (OnmsOutage outage : outages) {
OnmsMonitoredService monitoredService = outage.getMonitoredService();
OnmsServiceType serviceType = monitoredService.getServiceType();
OnmsIpInterface ipInterface = monitoredService.getIpInterface();
categoryBuilder.addOutageService(
monitoredService.getNodeId(),
ipInterface.getIpAddress(),
ipInterface.getIpAddress(),
ipInterface.getNode().getLabel(),
serviceType.getName());
}
for (StatusNode node : categoryBuilder.getNodes()) {
statusCategory.addNode(node);
}
return statusCategory;
}
public void setViewDisplayDao(ViewDisplayDao viewDisplayDao){
m_viewDisplayDao = viewDisplayDao;
}
public void setCategoryConfigDao(CategoryConfigDao categoryDao){
m_categoryConfigDao = categoryDao;
}
public void setOutageDao(OutageDao outageDao) {
m_outagedao = outageDao;
}
}
|
package org.csstudio.display.builder.model.widgets;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.behaviorPVName;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.displayText;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.widgetMacros;
import java.util.Arrays;
import java.util.List;
import org.csstudio.display.builder.model.BaseWidget;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetCategory;
import org.csstudio.display.builder.model.WidgetDescriptor;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.macros.Macros;
/** Widget that provides button for invoking actions
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ActionButtonWidget extends BaseWidget
{
/** Widget descriptor */
public static final WidgetDescriptor WIDGET_DESCRIPTOR =
new WidgetDescriptor("action_button", WidgetCategory.CONTROL,
"Action Button",
"platform:/plugin/org.csstudio.display.builder.model/icons/action_button.png",
"Button that can open related displays or write PVs",
Arrays.asList("org.csstudio.opibuilder.widgets.ActionButton"))
{
@Override
public Widget createWidget()
{
return new ActionButtonWidget();
}
};
private WidgetProperty<Macros> macros;
private WidgetProperty<String> text;
public ActionButtonWidget()
{
super(WIDGET_DESCRIPTOR.getType());
}
@Override
protected void defineProperties(final List<WidgetProperty<?>> properties)
{
super.defineProperties(properties);
properties.add(behaviorPVName.createProperty(this, ""));
properties.add(macros = widgetMacros.createProperty(this, new Macros()));
properties.add(text = displayText.createProperty(this, "$(actions)"));
}
/** @return Widget 'macros' */
public WidgetProperty<Macros> widgetMacros()
{
return macros;
}
/** @return Display 'text' */
public WidgetProperty<String> displayText()
{
return text;
}
/** Action button widget extends parent macros
* @return {@link Macros}
*/
@Override
public Macros getEffectiveMacros()
{
final Macros base = super.getEffectiveMacros();
final Macros my_macros = widgetMacros().getValue();
return Macros.merge(base, my_macros);
}
}
|
package org.javarosa.formmanager.view.chatterbox.widget;
import org.javarosa.core.model.QuestionDef;
import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.Item;
public abstract class SelectEntryWidget extends ExpandedWidget {
private int style;
protected QuestionDef question;
public SelectEntryWidget (int style) {
this.style = style;
}
protected Item getEntryWidget (QuestionDef question) {
this.question = question;
//This is a slight UI hack that is in place to make the choicegroup properly
//intercept 'up' and 'down' inputs. Essentially Polish is very broken when it comes
//to scrolling nested containers, and this function properly takes the parent (Widget) position
//into account as well as the choicegroup's
ChoiceGroup cg = new ChoiceGroup("", style) {
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
//This line here (The + this.parent.relativeY part) is the fix.
return ((Container)this.parent).getScrollYOffset() + this.relativeY + this.parent.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
};
for (int i = 0; i < question.getSelectItems().size(); i++)
cg.append("", null);
return cg;
}
protected ChoiceGroup choiceGroup () {
return (ChoiceGroup)entryWidget;
}
protected void updateWidget (QuestionDef question) {
for (int i = 0; i < choiceGroup().size(); i++) {
choiceGroup().getItem(i).setText((String)question.getSelectItems().keyAt(i));
}
}
}
|
package ua.com.fielden.platform.sample.domain;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.cond;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetch;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.orderBy;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import java.util.Map;
import ua.com.fielden.platform.dao.CommonEntityDao;
import ua.com.fielden.platform.dao.QueryExecutionModel;
import ua.com.fielden.platform.dao.annotations.SessionRequired;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.query.EntityAggregates;
import ua.com.fielden.platform.entity.query.IFilter;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.entity.query.model.AggregatedResultQueryModel;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.OrderingModel;
import ua.com.fielden.platform.sample.domain.mixin.TgPersistentEntityWithPropertiesMixin;
import ua.com.fielden.platform.sample.domain.observables.TgPersistentEntityWithPropertiesChangeSubject;
import ua.com.fielden.platform.swing.review.annotations.EntityType;
import ua.com.fielden.platform.utils.EntityUtils;
import com.google.inject.Inject;
/**
* DAO implementation for companion object {@link ITgPersistentEntityWithProperties}.
* It demos the use of {@link TgPersistentEntityWithPropertiesChangeSubject} for publishing change events to be propagated to the subscribed clients.
*
* @author Developers
*
*/
@EntityType(TgPersistentEntityWithProperties.class)
public class TgPersistentEntityWithPropertiesDao extends CommonEntityDao<TgPersistentEntityWithProperties> implements ITgPersistentEntityWithProperties {
private final TgPersistentEntityWithPropertiesChangeSubject changeSubject;
@Inject
public TgPersistentEntityWithPropertiesDao(final TgPersistentEntityWithPropertiesChangeSubject changeSubject, final IFilter filter) {
super(filter);
this.changeSubject = changeSubject;
}
/**
* Overridden to publish entity change events to an application wide observable.
*/
@Override
@SessionRequired
public TgPersistentEntityWithProperties save(final TgPersistentEntityWithProperties entity) {
final TgPersistentEntityWithProperties saved = super.save(entity);
changeSubject.publish(saved);
return saved;
}
@Override
@SessionRequired
public void delete(final TgPersistentEntityWithProperties entity) {
defaultDelete(entity);
}
@Override
@SessionRequired
public void delete(final EntityResultQueryModel<TgPersistentEntityWithProperties> model, final Map<String, Object> paramValues) {
defaultDelete(model, paramValues);
}
@Override
public IFetchProvider<TgPersistentEntityWithProperties> createFetchProvider() {
return super.createFetchProvider()
.with("key") // this property is "required" (necessary during saving) -- should be declared as fetching property
.with("desc")
.with("integerProp", "moneyProp", "bigDecimalProp", "stringProp", "booleanProp", "dateProp", "requiredValidatedProp")
.with("domainInitProp", "nonConflictingProp", "conflictingProp")
// .with("entityProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key"))
.with("userParam", "userParam.basedOnUser")
.with("entityProp", "entityProp.entityProp", "entityProp.compositeProp", "entityProp.compositeProp.desc")
// .with("status")
.with("critOnlyEntityProp")
.with("compositeProp", "compositeProp.desc")
// .with("producerInitProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key")
.with("producerInitProp", "status.key", "status.desc");
}
}
|
package org.eclipse.xtext.resource;
import static com.google.common.collect.Lists.*;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.resource.impl.DefaultResourceDescription;
import org.eclipse.xtext.resource.impl.DefaultResourceDescriptionManager;
import org.eclipse.xtext.resource.impl.EObjectDescriptionLookUp;
import org.eclipse.xtext.util.IResourceScopeCache;
import com.google.inject.Inject;
/**
*
* Installs the derived state in non-linking mode and discards it right after {@link EObjectDescription} creation.
*
* @author Sven Efftinge - Initial contribution and API
* @since 2.1
*/
public class DerivedStateAwareResourceDescriptionManager extends DefaultResourceDescriptionManager {
@Inject
private IResourceScopeCache cache = IResourceScopeCache.NullImpl.INSTANCE;
@Override
protected IResourceDescription internalGetResourceDescription(final Resource resource,
IDefaultResourceDescriptionStrategy strategy) {
DerivedStateAwareResource res = (DerivedStateAwareResource) resource;
boolean isInitialized = res.fullyInitialized || res.isInitializing;
try {
if (!isInitialized) {
res.eSetDeliver(false);
res.installDerivedState(true);
}
IResourceDescription description = createResourceDescription(resource, strategy);
if (!isInitialized) {
// make sure the eobject descriptions are being built.
newArrayList(description.getExportedObjects());
}
return description;
} finally {
if (!isInitialized) {
res.discardDerivedState();
res.eSetDeliver(true);
}
}
}
protected IResourceDescription createResourceDescription(Resource resource, IDefaultResourceDescriptionStrategy strategy) {
return new DefaultResourceDescription(resource, strategy, cache) {
@Override
protected EObjectDescriptionLookUp getLookUp() {
if (lookup == null)
lookup = new EObjectDescriptionLookUp(computeExportedObjects());
return lookup;
}
};
}
}
|
package org.yakindu.sct.generator.core;
import java.io.File;
import org.yakindu.sct.generator.core.impl.AbstractSExecModelGenerator;
import org.yakindu.sct.model.sgen.GeneratorEntry;
/**
* Base class for generators that are executed inside the workspace
*
* @author holger willebrandt - Initial contribution and API
*/
//FIXME !!! used in generator runtime samples (Xtend2 & Java, see e.g. org.yakindu.sct.generator.genmodel.ui.wizard.GeneratorProjectTemplate)
public abstract class AbstractWorkspaceGenerator extends AbstractSExecModelGenerator {
public final void refreshTargetProject(GeneratorEntry entry) {
throw new UnsupportedOperationException("implement me!");
}
public final File getTargetProject(GeneratorEntry entry) {
throw new UnsupportedOperationException("implement me!");
}
public final File getTargetFolder(GeneratorEntry entry) {
throw new UnsupportedOperationException("implement me!");
}
public final File getLibraryTargetFolder(GeneratorEntry entry) {
throw new UnsupportedOperationException("implement me!");
}
}
|
package com.opengamma.engine.view.calcnode;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.tuple.Pair;
/**
* Base class for objects that manage a set of AbstractCalculationNodes with the intention of
* invoking job executions on them.
*/
public abstract class AbstractCalculationNodeInvocationContainer {
/**
* After how many failed jobs should a cleanup be attempted.
*/
private static final int FAILURE_CLEANUP_PERIOD = 100; // clean up after every 100 failed jobs
/**
* Retention period for failed jobs needs to be long enough for any tail jobs to have arrived.
*/
private static final long FAILURE_RETENTION = 5L * 60L * 100000000L;
private static final Logger s_logger = LoggerFactory.getLogger(AbstractCalculationNodeInvocationContainer.class);
protected static interface ExecutionReceiver {
void executionFailed(AbstractCalculationNode node, Exception exception);
void executionComplete(CalculationJobResult result);
}
private static class JobEntry {
private final CalculationJob _job;
private final JobExecution _execution;
private ExecutionReceiver _receiver;
private AtomicInteger _blockCount;
public JobEntry(final CalculationJob job, final JobExecution execution, final ExecutionReceiver receiver) {
_job = job;
_execution = execution;
_receiver = receiver;
}
public CalculationJob getJob() {
return _job;
}
public JobExecution getExecution() {
return _execution;
}
public ExecutionReceiver getReceiver() {
return _receiver;
}
/**
* This is only called from a single thread - doing the addJob operation - once it has been called once,
* another thread will manipulate the block count (e.g. if a job is finishing) and possibly spawn the job.
* Note that we initialize the count to two so that the job does not get spawned prematurely until the
* addJob thread has processed the required job list and performs a decrement to clear the additional value.
*/
public void incrementBlockCount() {
if (_blockCount == null) {
_blockCount = new AtomicInteger(2);
} else {
_blockCount.incrementAndGet();
}
}
/**
* Decrements the block count, returns {@code true} when the count reaches zero.
*/
public boolean releaseBlockCount() {
return _blockCount.decrementAndGet() == 0;
}
public void invalidate() {
_receiver = null;
}
@Override
public int hashCode() {
return getJob().hashCode();
}
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof JobEntry)) {
return false;
}
return getJob().equals(((JobEntry) o).getJob());
}
}
private static class JobExecution {
private enum Status {
RUNNING, COMPLETED, FAILED;
}
private final long _jobId;
private final long _timestamp;
private Status _status;
private Set<JobEntry> _blocked;
private Pair<Thread, CalculationJob> _executor;
public JobExecution(final long jobId) {
_jobId = jobId;
_timestamp = System.nanoTime();
_status = Status.RUNNING;
}
public long getJobId() {
return _jobId;
}
public long getAge() {
return System.nanoTime() - _timestamp;
}
public Status getStatus() {
return _status;
}
public void setStatus(final Status status) {
_status = status;
}
public synchronized Pair<Thread, CalculationJob> getAndSetExecutor(final Pair<Thread, CalculationJob> executor) {
final Pair<Thread, CalculationJob> previous = _executor;
_executor = executor;
return previous;
}
public synchronized boolean threadBusy(final CalculationJob job) {
assert _executor == null;
if (_status == Status.FAILED) {
return false;
}
_executor = Pair.of(Thread.currentThread(), job);
return true;
}
// Caller must own the monitor
public Set<JobEntry> getBlocked() {
Set<JobEntry> blocked = _blocked;
_blocked = null;
return blocked;
}
// Caller must own the monitor
public void blockJob(final JobEntry job) {
if (_blocked == null) {
_blocked = new HashSet<JobEntry>();
}
_blocked.add(job);
}
}
private final Queue<AbstractCalculationNode> _nodes = new ConcurrentLinkedQueue<AbstractCalculationNode>();
/**
* The set of jobs that are either running, in the runnable queue or blocked by other jobs.
*/
private final ConcurrentMap<Long, JobExecution> _executions = new ConcurrentHashMap<Long, JobExecution>();
/**
* The set of failed jobs. Anything not in this set or {@link #_executions} has completed successfully.
*/
private final ConcurrentMap<Long, JobExecution> _failures = new ConcurrentSkipListMap<Long, JobExecution>();
private final AtomicInteger _failureCount = new AtomicInteger();
private final Queue<JobEntry> _runnableJobs = new ConcurrentLinkedQueue<JobEntry>();
private final ExecutorService _executorService = Executors.newCachedThreadPool();
protected Queue<AbstractCalculationNode> getNodes() {
return _nodes;
}
public void addNode(final AbstractCalculationNode node) {
ArgumentChecker.notNull(node, "node");
getNodes().add(node);
onNodeChange();
}
public void addNodes(final Collection<AbstractCalculationNode> nodes) {
ArgumentChecker.notNull(nodes, "nodes");
getNodes().addAll(nodes);
onNodeChange();
}
public void setNode(final AbstractCalculationNode node) {
ArgumentChecker.notNull(node, "node");
getNodes().clear();
getNodes().add(node);
onNodeChange();
}
public void setNodes(final Collection<AbstractCalculationNode> nodes) {
ArgumentChecker.notNull(nodes, "nodes");
getNodes().clear();
getNodes().addAll(nodes);
onNodeChange();
}
protected abstract void onNodeChange();
protected void onJobStart(final CalculationJob job) {
}
protected void onJobExecutionComplete() {
}
protected ExecutorService getExecutorService() {
return _executorService;
}
private JobExecution createExecution(final Long jobId) {
final JobExecution jobexec = new JobExecution(jobId);
_executions.put(jobId, jobexec);
return jobexec;
}
private JobExecution getExecution(final Long jobId) {
return _executions.get(jobId);
}
private JobExecution getFailure(final Long jobId) {
return _failures.get(jobId);
}
/**
* Adds a job to the runnable queue, spawning a worker thread if a node is supplied or one is
* available.
*/
private void spawnOrQueueJob(final JobEntry jobexec, AbstractCalculationNode node) {
if (node == null) {
node = getNodes().poll();
if (node == null) {
synchronized (this) {
node = getNodes().poll();
if (node == null) {
s_logger.debug("Adding job {} to runnable queue", jobexec.getJob().getSpecification().getJobId());
_runnableJobs.add(jobexec);
return;
}
}
}
}
s_logger.debug("Spawning execution of job {}", jobexec.getJob().getSpecification().getJobId());
final AbstractCalculationNode parallelNode = node;
getExecutorService().execute(new Runnable() {
@Override
public void run() {
executeJobs(parallelNode, jobexec);
}
});
}
private void failExecution(final JobExecution execution) {
final Set<JobEntry> blocked;
synchronized (execution) {
execution.setStatus(JobExecution.Status.FAILED);
blocked = execution.getBlocked();
// Add to failure set first, so the job is never missing from both
_failures.put(execution.getJobId(), execution);
_executions.remove(execution.getJobId());
_failureCount.incrementAndGet();
}
if (blocked != null) {
for (JobEntry tail : blocked) {
tail.invalidate();
failExecution(tail.getExecution());
}
}
}
/**
* Adds jobs to the runnable queue, spawning a worker thread if a node is supplied or one is available. Jobs must be
* added in dependency order - i.e. a job must be submitted before any that require it. This is to simplify
* retention of job status as we only need to track jobs that are still running or have failed which saves a lot
* of housekeeping overhead.
*
* @param job job to run, not {@code null}
* @param receiver execution status receiver, not {@code null}
* @param node optional node to start a worker thread with
*/
protected void addJob(final CalculationJob job, final ExecutionReceiver receiver, final AbstractCalculationNode node) {
final JobExecution jobExecution = createExecution(job.getSpecification().getJobId());
final Collection<Long> requiredJobIds = job.getRequiredJobIds();
final JobEntry jobEntry = new JobEntry(job, jobExecution, receiver);
if (requiredJobIds != null) {
// Shouldn't be passing a node in with a job that might not be runnable
assert node == null;
boolean failed = false;
boolean blocked = false;
for (Long requiredId : requiredJobIds) {
JobExecution required = getExecution(requiredId);
s_logger.debug("Job {} requires {}", jobExecution.getJobId(), requiredId);
if (required != null) {
synchronized (required) {
switch (required.getStatus()) {
case COMPLETED:
// No action needed - we can continue
s_logger.debug("Required job {} completed (from execution cache)", requiredId);
break;
case FAILED:
// We can't run
failed = true;
s_logger.debug("Required job {} failed (from execution cache)", requiredId);
break;
case RUNNING:
// We're blocked
blocked = true;
// Will increment or initialize to 2
jobEntry.incrementBlockCount();
required.blockJob(jobEntry);
s_logger.debug("Required job {} blocking {}", requiredId, jobExecution.getJobId());
break;
}
}
} else {
required = getFailure(requiredId);
if (required != null) {
failed = true;
s_logger.debug("Required job {} failed (from failure cache)", requiredId);
} else {
s_logger.debug("Required job {} completion inferred", requiredId);
}
}
}
if (failed) {
s_logger.debug("Failing execution of {}", jobExecution.getJobId());
failExecution(jobExecution);
return;
}
if (blocked) {
// Decrement the additional count from the initialization
if (!jobEntry.releaseBlockCount()) {
s_logger.debug("Blocked execution of {}", jobExecution.getJobId());
return;
}
}
}
spawnOrQueueJob(jobEntry, node);
}
private void threadFree(final JobExecution exec) {
// The executor should only go null transiently while the cancel action happens and should then
// be restored. If, for probably erroneous reasons, the job has been launched twice we can see
// a continuous null here from the second running thread so have a spin count here to give up
// after 1s regardless (which may cause further errors, but is better than deadlock).
int spin = 0;
do {
final Pair<Thread, CalculationJob> previous = exec.getAndSetExecutor(null);
if (previous != null) {
assert previous.getFirst() == Thread.currentThread();
return;
}
// Executor reference is null while the job is being canceled. An interrupt may be done as part of
// this so we need to make sure we swallow it rather than leave ourselves in an interrupted state.
if (Thread.interrupted()) {
s_logger.debug("Interrupt status cleared");
return;
}
switch (spin) {
case 0:
s_logger.debug("Waiting for interrupt");
break;
case 1:
s_logger.info("Waiting for interrupt");
break;
case 2:
s_logger.warn("Waiting for interrupt");
break;
default:
s_logger.error("Waiting for interrupt");
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
s_logger.debug("Interrupt received");
return;
}
} while (++spin < 1000);
}
/**
* Executes jobs from the runnable queue until it is empty.
*
* @param node Node to run on, not {@code null}
* @param jobexec The first job to run, not {@code null}
*/
private void executeJobs(final AbstractCalculationNode node, JobEntry jobexec) {
do {
s_logger.info("Executing job {} on {}", jobexec.getExecution().getJobId(), node.getNodeId());
onJobStart(jobexec.getJob());
CalculationJobResult result = null;
if (jobexec.getExecution().threadBusy(jobexec.getJob())) {
try {
result = node.executeJob(jobexec.getJob());
threadFree(jobexec.getExecution());
} catch (Exception e) {
// Any tail jobs will be abandoned
threadFree(jobexec.getExecution());
s_logger.warn("Job {} failed", jobexec.getExecution().getJobId());
failExecution(jobexec.getExecution());
jobexec.getReceiver().executionFailed(node, e);
}
} else {
s_logger.debug("Job {} cancelled", jobexec.getExecution().getJobId());
}
if (result != null) {
final Set<JobEntry> blocked;
synchronized (jobexec.getExecution()) {
jobexec.getExecution().setStatus(JobExecution.Status.COMPLETED);
blocked = jobexec.getExecution().getBlocked();
_executions.remove(jobexec.getExecution().getJobId());
}
if (blocked != null) {
s_logger.info("Job {} completed - releasing blocked jobs", jobexec.getExecution().getJobId());
for (JobEntry tail : blocked) {
if (tail.getReceiver() != null) {
if (tail.releaseBlockCount()) {
spawnOrQueueJob(tail, null);
}
}
}
} else {
s_logger.info("Job {} completed - no tail jobs", jobexec.getExecution().getJobId());
}
}
if (result != null) {
jobexec.getReceiver().executionComplete(result);
}
jobexec = _runnableJobs.poll();
if (jobexec == null) {
synchronized (this) {
jobexec = _runnableJobs.poll();
if (jobexec == null) {
getNodes().add(node);
break;
}
}
}
} while (true);
s_logger.debug("Finished job execution on {}", node.getNodeId());
onJobExecutionComplete();
// Housekeeping
if (_failureCount.get() > FAILURE_CLEANUP_PERIOD) {
_failureCount.set(0);
int count = 0;
final Iterator<Map.Entry<Long, JobExecution>> entryIterator = _failures.entrySet().iterator();
while (entryIterator.hasNext()) {
final Map.Entry<Long, JobExecution> entry = entryIterator.next();
if (entry.getValue().getAge() > FAILURE_RETENTION) {
s_logger.debug("Removed job {} from failure set", entry.getKey());
entryIterator.remove();
count++;
} else {
break;
}
}
s_logger.info("Removed {} dead entries from failure map, {} remaining", count, _failures.size());
}
s_logger.debug("Failure map size = {}, execution map size = {}", _failures.size(), _executions.size());
}
protected void cancelJob(final CalculationJobSpecification jobSpec) {
final JobExecution jobExec = getExecution(jobSpec.getJobId());
if (jobExec == null) {
s_logger.warn("Request to cancel job {} but already failed or completed", jobSpec.getJobId());
return;
}
s_logger.info("Cancelling job {}", jobSpec.getJobId());
failExecution(jobExec);
Pair<Thread, CalculationJob> executor = jobExec.getAndSetExecutor(null);
if (executor != null) {
s_logger.debug("Marking job {} cancelled", executor.getSecond().getSpecification().getJobId());
executor.getSecond().cancel();
s_logger.info("Interrupting thread {}", executor.getFirst().getName());
executor.getFirst().interrupt();
// Need to wait for the execution thread to acknowledge the interrupt, or it may be canceled by us swapping the executor
// reference back in and the interrupt will affect a subsequent wait causing erroneous behavior
while (executor.getFirst().isInterrupted()) {
s_logger.debug("Waiting for thread {} to accept the interrupt", executor.getFirst().getName());
Thread.yield();
}
s_logger.debug("Thread {} interrupted", executor.getFirst().getName());
executor = jobExec.getAndSetExecutor(executor);
assert executor == null;
}
}
protected boolean isJobAlive(final CalculationJobSpecification jobSpec) {
final JobExecution jobExec = getExecution(jobSpec.getJobId());
if (jobExec == null) {
// Completed or failed, not alive at any rate!
return false;
}
return true;
}
}
|
package org.ncomet.fibonaccispringaop.resource;
import org.ncomet.fibonaccispringaop.service.FibonacciService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.MessageFormat;
@RestController
@RequestMapping("/fibonacci/{n}")
public class FibonacciResource {
private final FibonacciService fibonacciService;
@Autowired
public FibonacciResource(FibonacciService fibonacciService) {
this.fibonacciService = fibonacciService;
}
@GetMapping
public ResponseEntity<String> fibo(@PathVariable int n) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long result = fibonacciService.compute(n);
stopWatch.stop();
long duration = stopWatch.getLastTaskTimeMillis();
return ResponseEntity.ok(MessageFormat.format(
"fibonacci({0}) = {1}<br/> It took <font color=\"red\">{2}</font>ms <br/><br/>",
n,
result,
duration)
+ commentary(duration));
}
private String commentary(long duration) {
return duration > 1L ? "A bit <i>long</i> don't you think?" : "Woaw that was <i>fast</i> !";
}
}
|
package uk.ac.ebi.quickgo.client.service.loader.presets.ff;
import uk.ac.ebi.quickgo.client.service.loader.presets.RestValuesRetriever;
import java.util.*;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.validator.ValidationException;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsValidationHelper.checkIsNullOrEmpty;
/**
* Provide ItemProcessor instances to be used in the creation of preset list information.
*/
public class ItemProcessorFactory {
/**
* An item processor to ensure there are no duplicates in a presets list
* @return item processor
*/
public static ItemProcessor<RawNamedPreset, RawNamedPreset> duplicateCheckingItemProcessor() {
return new ItemProcessor<RawNamedPreset, RawNamedPreset>() {
private final Set<String> duplicatePrevent = new HashSet<>();
@Override
public RawNamedPreset process(RawNamedPreset rawNamedPreset) {
return duplicatePrevent.add(rawNamedPreset.name.toLowerCase()) ? rawNamedPreset : null;
}
};
}
/**
* An item processor to ensure validation conditions are met.
* @return item processor
*/
public static ItemProcessor<RawNamedPreset, RawNamedPreset> validatingItemProcessor() {
return new ItemProcessor<RawNamedPreset, RawNamedPreset>() {
@Override
public RawNamedPreset process(RawNamedPreset rawNamedPreset) throws Exception {
if (rawNamedPreset == null) {
throw new ValidationException("RawDBPreset cannot be null or empty");
}
checkIsNullOrEmpty(rawNamedPreset.name);
return rawNamedPreset;
}
};
}
/**
* An item processor to ensure preset values are actually in use.
* @param restValuesRetriever the source of the 'in-use data' to check.
* @param retrieveKey the key used to retrieve the 'in-use data' from it's source.
* @return item processor
*/
public static ItemProcessor<RawNamedPreset, RawNamedPreset> checkPresetIsUsedItemProcessor(RestValuesRetriever
restValuesRetriever,
String retrieveKey) {
final Optional<List<String>> returnedValues = restValuesRetriever.retrieveValues(retrieveKey);
List<String> usableList = returnedValues.orElse(Collections.emptyList());
Set<String> usedValues = new HashSet<>(usableList);
return rawNamedPreset -> {
if (usedValues.isEmpty()) {
//Wasn't possible to load from values used from source and check usage, so OK preset value so we have
// something to show.
return rawNamedPreset;
}
return usedValues.contains(rawNamedPreset.name) ? rawNamedPreset : null;
};
}
}
|
package uk.ac.ebi.quickgo.client.service.loader.presets.ff;
/**
* Factory for creating {@link RawNamedPresetColumns} instances based on a specified {@link Source}.
* The supplied {@link Source} indicates the source which is being read.
*
* Created 13/09/16
* @author Edd
*/
public class SourceColumnsFactory {
public static RawNamedPresetColumns createFor(Source source) {
switch (source) {
case DB_COLUMNS:
return RawNamedPresetColumnsBuilder.createWithNamePosition(0)
.withDescriptionPosition(1)
.build();
case REF_COLUMNS:
return RawNamedPresetColumnsBuilder.createWithNamePosition(0)
.withDescriptionPosition(1)
.withRelevancyPosition(2)
.build();
case GENE_PRODUCT_COLUMNS:
return RawNamedPresetColumnsBuilder.createWithNamePosition(0)
.withDescriptionPosition(1)
.withURLPosition(3)
.build();
case GO_SLIM_SET_COLUMNS:
return RawNamedPresetColumnsBuilder.createWithNamePosition(0)
.withIdPosition(1)
.withDescriptionPosition(2)
.withAssociationPosition(3)
.build();
case EXT_RELATION_COLUMNS:
return RawNamedPresetColumnsBuilder
.createWithNamePosition(1)
.withIdPosition(0)
.build();
case TAXON_COLUMNS:
return RawNamedPresetColumnsBuilder.createWithNamePosition(1)
.withIdPosition(0)
.build();
case EXT_DATABASE_COLUMNS:
return RawNamedPresetColumnsBuilder
.createWithNamePosition(0)
.build();
default:
throw new IllegalStateException("Source type: " + source + " is not handled.");
}
}
public enum Source {
DB_COLUMNS,
GENE_PRODUCT_COLUMNS,
GO_SLIM_SET_COLUMNS,
REF_COLUMNS,
EXT_RELATION_COLUMNS,
TAXON_COLUMNS,
EXT_DATABASE_COLUMNS
}
}
|
package bdv.export;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import mpicbg.spim.data.XmlHelpers;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import mpicbg.spim.data.generic.sequence.BasicImgLoader;
import mpicbg.spim.data.generic.sequence.BasicSetupImgLoader;
import mpicbg.spim.data.generic.sequence.BasicViewSetup;
import mpicbg.spim.data.sequence.TimePoint;
import mpicbg.spim.data.sequence.TimePoints;
import mpicbg.spim.data.sequence.ViewId;
import net.imglib2.Cursor;
import net.imglib2.Dimensions;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.img.basictypeaccess.array.ShortArray;
import net.imglib2.img.cell.CellImg;
import net.imglib2.iterator.LocalizingIntervalIterator;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.view.Views;
import bdv.img.hdf5.Hdf5ImageLoader;
import bdv.img.hdf5.Partition;
import bdv.img.hdf5.Util;
import bdv.spimdata.SequenceDescriptionMinimal;
import ch.systemsx.cisd.hdf5.HDF5Factory;
import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures;
import ch.systemsx.cisd.hdf5.IHDF5Reader;
import ch.systemsx.cisd.hdf5.IHDF5Writer;
/**
* Create a hdf5 files containing image data from all views and all timepoints
* in a chunked, mipmaped representation.
*
* <p>
* Every image is stored in multiple resolutions. The resolutions are described
* as int[] arrays defining multiple of original pixel size in every dimension.
* For example {1,1,1} is the original resolution, {4,4,2} is downsampled by
* factor 4 in X and Y and factor 2 in Z. Each resolution of the image is stored
* as a chunked three-dimensional array (each chunk corresponds to one cell of a
* {@link CellImg} when the data is loaded). The chunk sizes are defined by the
* subdivisions parameter which is an array of int[], one per resolution. Each
* int[] array describes the X,Y,Z chunk size for one resolution. For instance
* {32,32,8} says that the (downsampled) image is divided into 32x32x8 pixel
* blocks.
*
* <p>
* For every mipmap level we have a (3D) int[] resolution array, so the full
* mipmap pyramid is specified by a nested int[][] array. Likewise, we have a
* (3D) int[] subdivions array for every mipmap level, so the full chunking of
* the full pyramid is specfied by a nested int[][] array.
*
* <p>
* A data-set can be stored in a single hdf5 file or split across several hdf5
* "partitions" with one master hdf5 linking into the partitions.
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public class WriteSequenceToHdf5
{
/**
* Create a hdf5 file containing image data from all views and all
* timepoints in a chunked, mipmaped representation.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param hdf5File
* hdf5 file to which the image data is written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final HashMap< Integer, Integer > timepointIdSequenceToPartition = new HashMap< Integer, Integer >();
for ( final TimePoint timepoint : seq.getTimePoints().getTimePointsOrdered() )
timepointIdSequenceToPartition.put( timepoint.getId(), timepoint.getId() );
final HashMap< Integer, Integer > setupIdSequenceToPartition = new HashMap< Integer, Integer >();
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
setupIdSequenceToPartition.put( setup.getId(), setup.getId() );
final Partition partition = new Partition( hdf5File.getPath(), timepointIdSequenceToPartition, setupIdSequenceToPartition );
writeHdf5PartitionFile( seq, perSetupMipmapInfo, deflate, partition, loopbackHeuristic, afterEachPlane, numCellCreatorThreads, progressWriter );
}
/**
* Create a hdf5 file containing image data from all views and all
* timepoints in a chunked, mipmaped representation. This is the same as
* {@link WriteSequenceToHdf5#writeHdf5File(AbstractSequenceDescription, Map, boolean, File, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* except that only one set of supsampling factors and and subdivision
* blocksizes is given, which is used for all {@link BasicViewSetup views}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param resolutions
* this nested arrays contains per mipmap level, the subsampling
* factors.
* @param subdivisions
* this nested arrays contains per mipmap level, the subdivision
* block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param hdf5File
* hdf5 file to which the image data is written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final int[][] resolutions,
final int[][] subdivisions,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final HashMap< Integer, ExportMipmapInfo > perSetupMipmapInfo = new HashMap< Integer, ExportMipmapInfo >();
final ExportMipmapInfo mipmapInfo = new ExportMipmapInfo( resolutions, subdivisions );
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
perSetupMipmapInfo.put( setup.getId(), mipmapInfo );
writeHdf5File( seq, perSetupMipmapInfo, deflate, hdf5File, loopbackHeuristic, afterEachPlane, numCellCreatorThreads, progressWriter );
}
/**
* Create a hdf5 master file linking to image data from all views and all
* timepoints. This is the same as
* {@link #writeHdf5PartitionLinkFile(AbstractSequenceDescription, Map, ArrayList, File)},
* except that the information about the partition files as well as the
* path of the master file to be written is obtained from the
* {@link BasicImgLoader} of the sequence, which must be a
* {@link Hdf5ImageLoader}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
*/
public static void writeHdf5PartitionLinkFile( final AbstractSequenceDescription< ?, ?, ? > seq, final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo )
{
if ( !( seq.getImgLoader() instanceof Hdf5ImageLoader ) )
throw new IllegalArgumentException( "sequence has " + seq.getImgLoader().getClass() + " imgloader. Hdf5ImageLoader required." );
final Hdf5ImageLoader loader = ( Hdf5ImageLoader ) seq.getImgLoader();
writeHdf5PartitionLinkFile( seq, perSetupMipmapInfo, loader.getPartitions(), loader.getHdf5File() );
}
/**
* Create a hdf5 master file linking to image data from all views and all
* timepoints. Which hdf5 files contain which part of the image data is
* specified in the {@code portitions} parameter.
*
* Note that this method only writes the master file containing links. The
* individual partitions need to be written with
* {@link #writeHdf5PartitionFile(AbstractSequenceDescription, Map, boolean, Partition, LoopbackHeuristic, AfterEachPlane, ProgressWriter)}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param partitions
* which parts of the dataset are stored in which files.
* @param hdf5File
* hdf5 master file to which the image data from the partition
* files is linked.
*/
public static void writeHdf5PartitionLinkFile( final AbstractSequenceDescription< ?, ?, ? > seq, final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo, final ArrayList< Partition > partitions, final File hdf5File )
{
// open HDF5 output file
if ( hdf5File.exists() )
hdf5File.delete();
final IHDF5Writer hdf5Writer = HDF5Factory.open( hdf5File );
// write Mipmap descriptions
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
{
final int setupId = setup.getId();
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupId );
hdf5Writer.writeDoubleMatrix( Util.getResolutionsPath( setupId ), mipmapInfo.getResolutions() );
hdf5Writer.writeIntMatrix( Util.getSubdivisionsPath( setupId ), mipmapInfo.getSubdivisions() );
}
// link Cells for all views in the partition
final File basePath = hdf5File.getParentFile();
for ( final Partition partition : partitions )
{
final Map< Integer, Integer > timepointIdSequenceToPartition = partition.getTimepointIdSequenceToPartition();
final Map< Integer, Integer > setupIdSequenceToPartition = partition.getSetupIdSequenceToPartition();
for ( final Entry< Integer, Integer > tEntry : timepointIdSequenceToPartition.entrySet() )
{
final int tSequence = tEntry.getKey();
final int tPartition = tEntry.getValue();
for ( final Entry< Integer, Integer > sEntry : setupIdSequenceToPartition.entrySet() )
{
final int sSequence = sEntry.getKey();
final int sPartition = sEntry.getValue();
final ViewId idSequence = new ViewId( tSequence, sSequence );
final ViewId idPartition = new ViewId( tPartition, sPartition );
final int numLevels = perSetupMipmapInfo.get( sSequence ).getNumLevels();
for ( int level = 0; level < numLevels; ++level )
{
final String relativePath = XmlHelpers.getRelativePath( new File( partition.getPath() ), basePath ).getPath();
hdf5Writer.object().createOrUpdateExternalLink( relativePath, Util.getCellsPath( idPartition, level ), Util.getCellsPath( idSequence, level ) );
}
}
}
}
hdf5Writer.close();
}
/**
* Create a hdf5 partition file containing image data for a subset of views
* and timepoints in a chunked, mipmaped representation.
*
* Please note that the description of the <em>full</em> dataset must be
* given in the <code>seq</code>, <code>perSetupResolutions</code>, and
* <code>perSetupSubdivisions</code> parameters. Then only the part
* described by <code>partition</code> will be written.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param partition
* which part of the dataset to write, and to which file.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5PartitionFile(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final Partition partition,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
ProgressWriter progressWriter )
{
final int blockWriterQueueLength = 100;
if ( progressWriter == null )
progressWriter = new ProgressWriterConsole();
progressWriter.setProgress( 0 );
// get sequence timepointIds for the timepoints contained in this partition
final ArrayList< Integer > timepointIdsSequence = new ArrayList< Integer >( partition.getTimepointIdSequenceToPartition().keySet() );
Collections.sort( timepointIdsSequence );
final int numTimepoints = timepointIdsSequence.size();
final ArrayList< Integer > setupIdsSequence = new ArrayList< Integer >( partition.getSetupIdSequenceToPartition().keySet() );
Collections.sort( setupIdsSequence );
// get the BasicImgLoader that supplies the images
final BasicImgLoader imgLoader = seq.getImgLoader();
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() ) {
final Object type = imgLoader.getSetupImgLoader( setup.getId() ).getImageType();
if ( !( type instanceof UnsignedShortType ) )
throw new IllegalArgumentException( "Expected BasicImgLoader<UnsignedShortTyp> but your dataset has BasicImgLoader<"
+ type.getClass().getSimpleName() + ">.\nCurrently writing to HDF5 is only supported for UnsignedShortType." );
}
// open HDF5 partition output file
final File hdf5File = new File( partition.getPath() );
if ( hdf5File.exists() )
hdf5File.delete();
final Hdf5BlockWriterThread writerQueue = new Hdf5BlockWriterThread( hdf5File, blockWriterQueueLength );
writerQueue.start();
// start CellCreatorThreads
final CellCreatorThread[] cellCreatorThreads = createAndStartCellCreatorThreads( numCellCreatorThreads );
// calculate number of tasks for progressWriter
int numTasks = 1; // first task is for writing mipmap descriptions etc...
for ( final int timepointIdSequence : timepointIdsSequence )
for ( final int setupIdSequence : setupIdsSequence )
if ( seq.getViewDescriptions().get( new ViewId( timepointIdSequence, setupIdSequence ) ).isPresent() )
numTasks++;
int numCompletedTasks = 0;
// write Mipmap descriptions
for ( final Entry< Integer, Integer > entry : partition.getSetupIdSequenceToPartition().entrySet() )
{
final int setupIdSequence = entry.getKey();
final int setupIdPartition = entry.getValue();
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupIdSequence );
writerQueue.writeMipmapDescription( setupIdPartition, mipmapInfo );
}
progressWriter.setProgress( ( double ) ++numCompletedTasks / numTasks );
// write image data for all views to the HDF5 file
int timepointIndex = 0;
for ( final int timepointIdSequence : timepointIdsSequence )
{
final int timepointIdPartition = partition.getTimepointIdSequenceToPartition().get( timepointIdSequence );
progressWriter.out().printf( "proccessing timepoint %d / %d\n", ++timepointIndex, numTimepoints );
// assemble the viewsetups that are present in this timepoint
final ArrayList< Integer > setupsTimePoint = new ArrayList< Integer >();
for ( final int setupIdSequence : setupIdsSequence )
if ( seq.getViewDescriptions().get( new ViewId( timepointIdSequence, setupIdSequence ) ).isPresent() )
setupsTimePoint.add( setupIdSequence );
final int numSetups = setupsTimePoint.size();
int setupIndex = 0;
for ( final int setupIdSequence : setupsTimePoint )
{
final int setupIdPartition = partition.getSetupIdSequenceToPartition().get( setupIdSequence );
progressWriter.out().printf( "proccessing setup %d / %d\n", ++setupIndex, numSetups );
@SuppressWarnings( "unchecked" )
final RandomAccessibleInterval< UnsignedShortType > img = ( ( BasicSetupImgLoader< UnsignedShortType > ) imgLoader.getSetupImgLoader( setupIdSequence ) ).getImage( timepointIdSequence );
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupIdSequence );
final double startCompletionRatio = ( double ) numCompletedTasks++ / numTasks;
final double endCompletionRatio = ( double ) numCompletedTasks / numTasks;
final ProgressWriter subProgressWriter = new SubTaskProgressWriter( progressWriter, startCompletionRatio, endCompletionRatio );
writeViewToHdf5PartitionFile(
img, timepointIdPartition, setupIdPartition, mipmapInfo, false,
deflate, writerQueue, cellCreatorThreads, loopbackHeuristic, afterEachPlane, subProgressWriter );
}
}
// shutdown and close file
stopCellCreatorThreads( cellCreatorThreads );
writerQueue.close();
progressWriter.setProgress( 1.0 );
}
/**
* Write a single view to a hdf5 partition file, in a chunked, mipmaped
* representation. Note that the specified view must not already exist in
* the partition file!
*
* @param img
* the view to be written.
* @param partition
* describes which part of the full sequence is contained in this
* partition, and to which file this partition is written.
* @param timepointIdPartition
* the timepoint id wrt the partition of the view to be written.
* The information in {@code partition} relates this to timepoint
* id in the full sequence.
* @param setupIdPartition
* the setup id wrt the partition of the view to be written. The
* information in {@code partition} relates this to setup id in
* the full sequence.
* @param mipmapInfo
* contains for each mipmap level of the setup, the subsampling
* factors and subdivision block sizes.
* @param writeMipmapInfo
* whether to write mipmap description for the setup. must be
* done (at least) once for each setup in the partition.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here. may
* be null.
*/
public static void writeViewToHdf5PartitionFile(
final RandomAccessibleInterval< UnsignedShortType > img,
final Partition partition,
final int timepointIdPartition,
final int setupIdPartition,
final ExportMipmapInfo mipmapInfo,
final boolean writeMipmapInfo,
final boolean deflate,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final int blockWriterQueueLength = 100;
// create and start Hdf5BlockWriterThread
final Hdf5BlockWriterThread writerQueue = new Hdf5BlockWriterThread( partition.getPath(), blockWriterQueueLength );
writerQueue.start();
final CellCreatorThread[] cellCreatorThreads = createAndStartCellCreatorThreads( numCellCreatorThreads );
// write the image
writeViewToHdf5PartitionFile( img, timepointIdPartition, setupIdPartition, mipmapInfo, writeMipmapInfo, deflate, writerQueue, cellCreatorThreads, loopbackHeuristic, afterEachPlane, progressWriter );
stopCellCreatorThreads( cellCreatorThreads );
writerQueue.close();
}
static class LoopBackImageLoader extends Hdf5ImageLoader
{
private LoopBackImageLoader( final IHDF5Reader existingHdf5Reader, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription )
{
super( null, existingHdf5Reader, null, sequenceDescription, false );
}
static LoopBackImageLoader create( final IHDF5Reader existingHdf5Reader, final int timepointIdPartition, final int setupIdPartition, final Dimensions imageDimensions )
{
final HashMap< Integer, TimePoint > timepoints = new HashMap< Integer, TimePoint >();
timepoints.put( timepointIdPartition, new TimePoint( timepointIdPartition ) );
final HashMap< Integer, BasicViewSetup > setups = new HashMap< Integer, BasicViewSetup >();
setups.put( setupIdPartition, new BasicViewSetup( setupIdPartition, null, imageDimensions, null ) );
final SequenceDescriptionMinimal seq = new SequenceDescriptionMinimal( new TimePoints( timepoints ), setups, null, null );
return new LoopBackImageLoader( existingHdf5Reader, seq );
}
}
/**
* Write a single view to a hdf5 partition file, in a chunked, mipmaped
* representation. Note that the specified view must not already exist in
* the partition file!
*
* @param img
* the view to be written.
* @param timepointIdPartition
* the timepoint id wrt the partition of the view to be written.
* The information in {@code partition} relates this to timepoint
* id in the full sequence.
* @param setupIdPartition
* the setup id wrt the partition of the view to be written. The
* information in {@code partition} relates this to setup id in
* the full sequence.
* @param mipmapInfo
* contains for each mipmap level of the setup, the subsampling
* factors and subdivision block sizes.
* @param writeMipmapInfo
* whether to write mipmap description for the setup. must be
* done (at least) once for each setup in the partition.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param writerQueue
* block writing tasks are enqueued here.
* @param cellCreatorThreads
* threads used for creating (possibly down-sampled) blocks of
* the view to be written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param progressWriter
* completion ratio and status output will be directed here. may
* be null.
*/
public static void writeViewToHdf5PartitionFile(
final RandomAccessibleInterval< UnsignedShortType > img,
final int timepointIdPartition,
final int setupIdPartition,
final ExportMipmapInfo mipmapInfo,
final boolean writeMipmapInfo,
final boolean deflate,
final Hdf5BlockWriterThread writerQueue,
final CellCreatorThread[] cellCreatorThreads,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
ProgressWriter progressWriter )
{
final HDF5IntStorageFeatures storage = deflate ? HDF5IntStorageFeatures.INT_AUTO_SCALING_DEFLATE : HDF5IntStorageFeatures.INT_AUTO_SCALING;
if ( progressWriter == null )
progressWriter = new ProgressWriterConsole();
// for progressWriter
final int numTasks = mipmapInfo.getNumLevels();
int numCompletedTasks = 0;
progressWriter.setProgress( ( double ) numCompletedTasks++ / numTasks );
// write Mipmap descriptions
if ( writeMipmapInfo )
writerQueue.writeMipmapDescription( setupIdPartition, mipmapInfo );
// create loopback image-loader to read already written chunks from the
// h5 for generating low-resolution versions.
final LoopBackImageLoader loopback = ( loopbackHeuristic == null ) ? null : LoopBackImageLoader.create( writerQueue.getIHDF5Writer(), timepointIdPartition, setupIdPartition, img );
// write image data for all views to the HDF5 file
final int n = 3;
final long[] dimensions = new long[ n ];
final int[][] resolutions = mipmapInfo.getExportResolutions();
final int[][] subdivisions = mipmapInfo.getSubdivisions();
final int numLevels = mipmapInfo.getNumLevels();
for ( int level = 0; level < numLevels; ++level )
{
progressWriter.out().println( "writing level " + level );
final long t0 = System.currentTimeMillis();
final RandomAccessibleInterval< UnsignedShortType > sourceImg;
final int[] factor;
final boolean useLoopBack;
if ( loopbackHeuristic == null )
{
sourceImg = img;
factor = resolutions[ level ];
useLoopBack = false;
}
else
{
// Are downsampling factors a multiple of a level that we have
// already written?
int[] factorsToPreviousLevel = null;
int previousLevel = -1;
A: for ( int l = level - 1; l >= 0; --l )
{
final int[] f = new int[ n ];
for ( int d = 0; d < n; ++d )
{
f[ d ] = resolutions[ level ][ d ] / resolutions[ l ][ d ];
if ( f[ d ] * resolutions[ l ][ d ] != resolutions[ level ][ d ] )
continue A;
}
factorsToPreviousLevel = f;
previousLevel = l;
break;
}
// Now, if previousLevel >= 0 we can use loopback ImgLoader on
// previousLevel and downsample with factorsToPreviousLevel.
// whether it makes sense to actually do so is determined by a
// heuristic based on the following considerations:
// * if downsampling a lot over original image, the cost of
// reading images back from hdf5 outweighs the cost of
// accessing and averaging original pixels.
// * original image may already be cached (for example when
// exporting an ImageJ virtual stack. To compute blocks
// that downsample a lot in Z, many planes of the virtual
// stack need to be accessed leading to cache thrashing if
// individual planes are very large.
useLoopBack = loopbackHeuristic.decide( img, resolutions[ level ], previousLevel, factorsToPreviousLevel, subdivisions[ level ] );
if ( useLoopBack )
{
sourceImg = loopback.getSetupImgLoader( setupIdPartition ).getImage( timepointIdPartition, previousLevel );
factor = factorsToPreviousLevel;
}
else
{
sourceImg = img;
factor = resolutions[ level ];
}
}
sourceImg.dimensions( dimensions );
final boolean fullResolution = ( factor[ 0 ] == 1 && factor[ 1 ] == 1 && factor[ 2 ] == 1 );
long size = 1;
if ( !fullResolution )
{
for ( int d = 0; d < n; ++d )
{
dimensions[ d ] = Math.max( dimensions[ d ] / factor[ d ], 1 );
size *= factor[ d ];
}
}
final double scale = 1.0 / size;
final long[] minRequiredInput = new long[ n ];
final long[] maxRequiredInput = new long[ n ];
sourceImg.min( minRequiredInput );
for ( int d = 0; d < n; ++d )
maxRequiredInput[ d ] = minRequiredInput[ d ] + dimensions[ d ] * factor[ d ] - 1;
final RandomAccessibleInterval< UnsignedShortType > extendedImg = Views.interval( Views.extendBorder( sourceImg ), new FinalInterval( minRequiredInput, maxRequiredInput ) );
final int[] cellDimensions = subdivisions[ level ];
final ViewId viewIdPartition = new ViewId( timepointIdPartition, setupIdPartition );
final String path = Util.getCellsPath( viewIdPartition, level );
writerQueue.createAndOpenDataset( path, dimensions.clone(), cellDimensions.clone(), storage );
final long[] numCells = new long[ n ];
final int[] borderSize = new int[ n ];
final long[] minCell = new long[ n ];
final long[] maxCell = new long[ n ];
for ( int d = 0; d < n; ++d )
{
numCells[ d ] = ( dimensions[ d ] - 1 ) / cellDimensions[ d ] + 1;
maxCell[ d ] = numCells[ d ] - 1;
borderSize[ d ] = ( int ) ( dimensions[ d ] - ( numCells[ d ] - 1 ) * cellDimensions[ d ] );
}
// generate one "plane" of cells after the other to avoid cache thrashing when exporting from virtual stacks
for ( int lastDimCell = 0; lastDimCell < numCells[ n - 1 ]; ++lastDimCell )
{
minCell[ n - 1 ] = lastDimCell;
maxCell[ n - 1 ] = lastDimCell;
final LocalizingIntervalIterator i = new LocalizingIntervalIterator( minCell, maxCell );
final int numThreads = cellCreatorThreads.length;
final CountDownLatch doneSignal = new CountDownLatch( numThreads );
for ( int threadNum = 0; threadNum < numThreads; ++threadNum )
{
cellCreatorThreads[ threadNum ].run( new Runnable()
{
@Override
public void run()
{
final double[] accumulator = fullResolution ? null : new double[ cellDimensions[ 0 ] * cellDimensions[ 1 ] * cellDimensions[ 2 ] ];
final long[] currentCellMin = new long[ n ];
final long[] currentCellMax = new long[ n ];
final long[] currentCellDim = new long[ n ];
final long[] currentCellPos = new long[ n ];
final long[] blockMin = new long[ n ];
final RandomAccess< UnsignedShortType > in = extendedImg.randomAccess();
while ( true )
{
synchronized ( i )
{
if ( !i.hasNext() )
break;
i.fwd();
i.localize( currentCellPos );
}
for ( int d = 0; d < n; ++d )
{
currentCellMin[ d ] = currentCellPos[ d ] * cellDimensions[ d ];
blockMin[ d ] = currentCellMin[ d ] * factor[ d ];
final boolean isBorderCellInThisDim = ( currentCellPos[ d ] + 1 == numCells[ d ] );
currentCellDim[ d ] = isBorderCellInThisDim ? borderSize[ d ] : cellDimensions[ d ];
currentCellMax[ d ] = currentCellMin[ d ] + currentCellDim[ d ] - 1;
}
final ArrayImg< UnsignedShortType, ? > cell = ArrayImgs.unsignedShorts( currentCellDim );
if ( fullResolution )
copyBlock( cell.randomAccess(), currentCellDim, in, blockMin );
else
downsampleBlock( cell.cursor(), accumulator, currentCellDim, in, blockMin, factor, scale );
writerQueue.writeBlockWithOffset( ( ( ShortArray ) cell.update( null ) ).getCurrentStorageArray(), currentCellDim.clone(), currentCellMin.clone() );
}
doneSignal.countDown();
}
} );
}
try
{
doneSignal.await();
}
catch ( final InterruptedException e )
{
e.printStackTrace();
}
if ( afterEachPlane != null )
afterEachPlane.afterEachPlane( useLoopBack );
}
writerQueue.closeDataset();
progressWriter.setProgress( ( double ) numCompletedTasks++ / numTasks );
}
if ( loopback != null )
loopback.close();
}
/**
* A heuristic to decide for a given resolution level whether the source
* pixels should be taken from the original image or read from a previously
* written resolution level in the hdf5 file.
*/
public interface LoopbackHeuristic
{
public boolean decide(
final RandomAccessibleInterval< ? > originalImg,
final int[] factorsToOriginalImg,
final int previousLevel,
final int[] factorsToPreviousLevel,
final int[] chunkSize );
}
public interface AfterEachPlane
{
public void afterEachPlane( final boolean usedLoopBack );
}
/**
* Simple heuristic: use loopback image loader if saving 8 times or more on
* number of pixel access with respect to the original image.
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public static class DefaultLoopbackHeuristic implements LoopbackHeuristic
{
@Override
public boolean decide( final RandomAccessibleInterval< ? > originalImg, final int[] factorsToOriginalImg, final int previousLevel, final int[] factorsToPreviousLevel, final int[] chunkSize )
{
if ( previousLevel < 0 )
return false;
if ( numElements( factorsToOriginalImg ) / numElements( factorsToPreviousLevel ) >= 8 )
return true;
return false;
}
}
public static int numElements( final int[] size )
{
int numElements = size[ 0 ];
for ( int d = 1; d < size.length; ++d )
numElements *= size[ d ];
return numElements;
}
public static CellCreatorThread[] createAndStartCellCreatorThreads( final int numThreads )
{
final CellCreatorThread[] cellCreatorThreads = new CellCreatorThread[ numThreads ];
for ( int threadNum = 0; threadNum < numThreads; ++threadNum )
{
cellCreatorThreads[ threadNum ] = new CellCreatorThread();
cellCreatorThreads[ threadNum ].setName( "CellCreatorThread " + threadNum );
cellCreatorThreads[ threadNum ].start();
}
return cellCreatorThreads;
}
public static void stopCellCreatorThreads( final CellCreatorThread[] cellCreatorThreads )
{
for ( final CellCreatorThread thread : cellCreatorThreads )
thread.interrupt();
}
public static class CellCreatorThread extends Thread
{
private Runnable currentTask = null;
public synchronized void run( final Runnable task )
{
currentTask = task;
notify();
}
@Override
public void run()
{
while ( !isInterrupted() )
{
synchronized ( this )
{
try
{
if ( currentTask == null )
wait();
else
{
currentTask.run();
currentTask = null;
}
}
catch ( final InterruptedException e )
{
break;
}
}
}
}
}
private static < T extends RealType< T > > void copyBlock( final RandomAccess< T > out, final long[] outDim, final RandomAccess< T > in, final long[] blockMin )
{
in.setPosition( blockMin );
for ( out.setPosition( 0, 2 ); out.getLongPosition( 2 ) < outDim[ 2 ]; out.fwd( 2 ) )
{
for ( out.setPosition( 0, 1 ); out.getLongPosition( 1 ) < outDim[ 1 ]; out.fwd( 1 ) )
{
for ( out.setPosition( 0, 0 ); out.getLongPosition( 0 ) < outDim[ 0 ]; out.fwd( 0 ), in.fwd( 0 ) )
{
out.get().set( in.get() );
}
in.setPosition( blockMin[ 0 ], 0 );
in.fwd( 1 );
}
in.setPosition( blockMin[ 1 ], 1 );
in.fwd( 2 );
}
}
private static < T extends RealType< T > > void downsampleBlock( final Cursor< T > out, final double[] accumulator, final long[] outDim, final RandomAccess< UnsignedShortType > randomAccess, final long[] blockMin, final int[] blockSize, final double scale )
{
final int numBlockPixels = ( int ) ( outDim[ 0 ] * outDim[ 1 ] * outDim[ 2 ] );
Arrays.fill( accumulator, 0, numBlockPixels, 0 );
randomAccess.setPosition( blockMin );
final int ox = ( int ) outDim[ 0 ];
final int oy = ( int ) outDim[ 1 ];
final int oz = ( int ) outDim[ 2 ];
final int sx = ox * blockSize[ 0 ];
final int sy = oy * blockSize[ 1 ];
final int sz = oz * blockSize[ 2 ];
int i = 0;
for ( int z = 0, bz = 0; z < sz; ++z )
{
for ( int y = 0, by = 0; y < sy; ++y )
{
for ( int x = 0, bx = 0; x < sx; ++x )
{
accumulator[ i ] += randomAccess.get().getRealDouble();
randomAccess.fwd( 0 );
if ( ++bx == blockSize[ 0 ] )
{
bx = 0;
++i;
}
}
randomAccess.move( -sx, 0 );
randomAccess.fwd( 1 );
if ( ++by == blockSize[ 1 ] )
by = 0;
else
i -= ox;
}
randomAccess.move( -sy, 1 );
randomAccess.fwd( 2 );
if ( ++bz == blockSize[ 2 ] )
bz = 0;
else
i -= ox * oy;
}
for ( int j = 0; j < numBlockPixels; ++j )
out.next().setReal( accumulator[ j ] * scale );
}
/**
* DEPRECATED. Use
* {@link #writeHdf5File(AbstractSequenceDescription, Map, boolean, File, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* instead.
*/
@Deprecated
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final ProgressWriter progressWriter )
{
final int numThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() - 2 );
writeHdf5File( seq, perSetupMipmapInfo, deflate, hdf5File, loopbackHeuristic, afterEachPlane, numThreads, progressWriter );
}
/**
* DEPRECATED. Use
* {@link #writeHdf5File(AbstractSequenceDescription, int[][], int[][], boolean, File, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* instead.
*/
@Deprecated
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final int[][] resolutions,
final int[][] subdivisions,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final ProgressWriter progressWriter )
{
final int numThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() - 2 );
writeHdf5File( seq, resolutions, subdivisions, deflate, hdf5File, loopbackHeuristic, afterEachPlane, numThreads, progressWriter );
}
/**
* DEPRECATED. Use
* {@link #writeHdf5PartitionFile(AbstractSequenceDescription, Map, boolean, Partition, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* instead.
*/
@Deprecated
public static void writeHdf5PartitionFile(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final Partition partition,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final ProgressWriter progressWriter )
{
final int numThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() - 2 );
writeHdf5PartitionFile( seq, perSetupMipmapInfo, deflate, partition, loopbackHeuristic, afterEachPlane, numThreads, progressWriter );
}
/**
* DEPRECATED. Use
* {@link #writeViewToHdf5PartitionFile(RandomAccessibleInterval, Partition, int, int, ExportMipmapInfo, boolean, boolean, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* instead.
*/
@Deprecated
public static void writeViewToHdf5PartitionFile(
final RandomAccessibleInterval< UnsignedShortType > img,
final Partition partition,
final int timepointIdPartition,
final int setupIdPartition,
final ExportMipmapInfo mipmapInfo,
final boolean writeMipmapInfo,
final boolean deflate,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final ProgressWriter progressWriter )
{
final int numThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() - 2 );
writeViewToHdf5PartitionFile( img, partition, timepointIdPartition, setupIdPartition, mipmapInfo, writeMipmapInfo, deflate, loopbackHeuristic, afterEachPlane, numThreads, progressWriter );
}
}
|
package bg.car_wash;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CarWashApplication {
public static void main(String[] args) {
SpringApplication.run(CarWashApplication.class, args);
}
}
|
package br.eti.rslemos.bitsmagic;
import java.util.Arrays;
/**
* This class consists exclusively of static methods that read or write bits
* over arrays of integral primitive type.
*
* <p>The number of bits available per array element (element width) varies
* according to the storage class used:
* </p>
* <ul>
* <li>{@code byte}: 8 bits ({@code Byte.SIZE});</li>
* <li>{@code char}: 16 bits ({@code Character.SIZE});</li>
* <li>{@code short}: 16 bits ({@code Short.SIZE});</li>
* <li>{@code int}: 32 bits ({@code Integer.SIZE});</li>
* <li>{@code long}: 64 bits ({@code Long.SIZE}).</li>
* </ul>
* <p>The total number of bits available (non-offlimits bits) is the product of
* {@code arraysize} by {@code element width}.
* </p>
* <p>For every method available in this class, the arguments that represent
* offsets should always be given in bits, and are 0-based. The bit mapping
* goes as follows ({@code S} is the element width in bits):
* </p>
* <ul>
* <li>bits < 0: always offlimits;</li>
* <li>bit 0: the least significant bit of first element;</li>
* <li>bit 1: the second least significant bit of first element;</li>
* <li>bit S-1: the most significant bit of first element (this happens to be
* the sign bit on signed types: {@code short}, {@code int} and
* {@code long});</li>
* <li>bit S: the least significant bit of second element;</li>
* <li>bit S+1: the second least significant bit of second element;</li>
* <li>bit 2S-1: the most significant bit of second element;</li>
* <li>bits >= available bits (as previously defined): always offlimits.
* </li>
* </ul>
* <p>Offlimits bits are hardwired to 0: they always read as 0, and any value
* written to them is discarded. Except where otherwise noted, methods in this
* class should never throw {@code ArrayIndexOutOfBoundsException}.
* </p>
* <p>{@code NullPointerException} is thrown if the given array is {@code null}.
* </p>
* <p>All methods are inherently thread unsafe: in case of more than one thread
* acting upon the same storage the results are undefined. Also neither they
* acquire nor block on any monitor. Any necessary synchronization should be
* done externally.
* </p>
*
* @author Rodrigo Lemos
* @since 1.0.0
*/
public class Store {
private Store() { /* non-instantiable */ }
static final int BYTE_ADDRESS_LINES = 3;
static final int BYTE_DATA_LINES = 1 << BYTE_ADDRESS_LINES;
static final int BYTE_ADDRESS_MASK = ~(-1 << BYTE_ADDRESS_LINES);
static final int BYTE_DATA_MASK = ~(-1 << BYTE_DATA_LINES);
// we expect this function to be heavily inlined
private static int read(byte[] data, int index) {
return index < data.length && index >=0 ? data[index] & BYTE_DATA_MASK : 0;
}
/**
* Reads the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static boolean readBit(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length || index < 0)
return false;
int offset = i & BYTE_ADDRESS_MASK;
return readBit0(data, index, offset);
}
private static boolean readBit0(byte[] data, int index, int offset) {
return (data[index] << ~offset) < 0;
}
/**
* Writes the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeBit(byte[] data, int i, boolean v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index < data.length && index >= 0)
writeBit0(data, index, i & BYTE_ADDRESS_MASK, v);
}
private static void writeBit0(byte[] data, int index, int offset, boolean v) {
if (v)
data[index] |= 1 << offset;
else
data[index] &= ~(1 << offset);
}
/**
* Assigns the specified bit value to each bit of the specified range of
* the given storage. The range to be filled extends from offset
* {@code from}, inclusive, to offset {@code to}, exclusive. If
* {@code to <= from} this method does nothing.
*
* <p>This method behaves as the following code:
* <pre>
* for(int i = from; i < to; i++)
* Store.writeBit(data, i, v);
* </pre>
* </p>
*
* @param data storage array.
* @param from offset, in bits, 0-based, of the first bit (inclusive) to be
* filled with the specified value.
* @param to offset, in bits, 0-based, of the last bit (exclusive) to be
* filled with the specified value.
* @param v value whose contents will be used to fill the specified region
* into {@code data}.
*
* @since 1.0.0
*/
public static void fill(byte[] data, int from, int to, boolean v) {
if (from == to)
return;
if (to < from)
throw new IllegalArgumentException();
// clamp
if (from < 0)
from = 0;
if (to > data.length << BYTE_ADDRESS_LINES)
to = data.length << BYTE_ADDRESS_LINES;
if (!(to > from))
return;
int[] index = {from >> BYTE_ADDRESS_LINES, to >> BYTE_ADDRESS_LINES};
int[] offset = {from & BYTE_ADDRESS_MASK, to & BYTE_ADDRESS_MASK };
if (index[1] == index[0]) {
// special case: subword count
final long LOWEST_BITS_FROM = ~(BYTE_DATA_MASK << offset[0]);
final long HIGHEST_BITS_TO = BYTE_DATA_MASK << offset[1];
if (v)
data[index[0]] |= ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO);
else
data[index[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO;
return;
}
if (offset[0] != 0) {
// handle "from" end specially
final long HIGHEST_BITS = BYTE_DATA_MASK << offset[0];
if (v)
data[index[0]] |= HIGHEST_BITS;
else
data[index[0]] &= ~HIGHEST_BITS;
// first index already taken care of
index[0]++;
}
if (index[1] > index[0])
Arrays.fill(data, index[0], index[1], (byte) (v ? -1 : 0));
if (offset[1] != 0) {
final long LOWEST_BITS = ~(BYTE_DATA_MASK << offset[1]);
if (v)
data[index[1]] |= LOWEST_BITS;
else
data[index[1]] &= ~LOWEST_BITS;
}
}
/**
* Reads as {@code byte} the 8 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static byte readByte(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0)
return (byte) d0;
d0 >>>= offset;
int d1 = read(data, ++index);
d1 <<= BYTE_DATA_LINES - offset;
return (byte) (d1 | d0);
}
/**
* Writes 8 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeByte(byte[] data, int i, byte v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & BYTE_ADDRESS_MASK;
int mask = ~(BYTE_DATA_MASK << Byte.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (offset == 0)
return;
if (++index >= data.length) return;
mask = ~(BYTE_DATA_MASK << Byte.SIZE) >>> BYTE_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >> (BYTE_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code char} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static char readChar(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0)
return (char) (d1 << BYTE_DATA_LINES | d0);
int d2 = read(data, ++index);
d0 >>>= offset;
d1 <<= BYTE_DATA_LINES - offset;
d2 <<= 2*BYTE_DATA_LINES - offset;
return (char) (d2 | d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeChar(byte[] data, int i, char v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -2) return;
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (byte)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES);
return;
}
int mask = BYTE_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (byte)(v >> 2*BYTE_DATA_LINES - offset) & ~mask;
}
/**
* Reads as {@code short} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static short readShort(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0)
return (short) (d1 << BYTE_DATA_LINES | d0);
int d2 = read(data, ++index);
d0 >>>= offset;
d1 <<= BYTE_DATA_LINES - offset;
d2 <<= 2*BYTE_DATA_LINES - offset;
return (short) (d2 | d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeShort(byte[] data, int i, short v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -2) return;
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (byte)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES);
return;
}
int mask = BYTE_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (byte)(v >> 2*BYTE_DATA_LINES - offset) & ~mask;
}
/**
* Reads as {@code int} the 32 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static int readInt(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int d2 = read(data, ++index);
int d3 = read(data, ++index);
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0)
return (int) (d3 << 3*BYTE_DATA_LINES | d2 << 2*BYTE_DATA_LINES | d1 << BYTE_DATA_LINES | d0);
long d4 = read(data, ++index);
d0 >>>= offset;
d1 <<= BYTE_DATA_LINES - offset;
d2 <<= 2*BYTE_DATA_LINES - offset;
d3 <<= 3*BYTE_DATA_LINES - offset;
d4 <<= 4*BYTE_DATA_LINES - offset;
return (int) (d4 | d3 | d2 | d1 | d0);
}
/**
* Writes 32 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeInt(byte[] data, int i, int v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -4) return;
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (byte)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 2*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 3*BYTE_DATA_LINES);
return;
}
int mask = BYTE_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 2*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 3*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (byte)(v >> 4*BYTE_DATA_LINES - offset) & ~mask;
}
/**
* Reads as {@code long} the 64 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static long readLong(byte[] data, int i) {
int index = i >> BYTE_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int d2 = read(data, ++index);
long d3 = read(data, ++index);
long d4 = read(data, ++index);
long d5 = read(data, ++index);
long d6 = read(data, ++index);
long d7 = read(data, ++index);
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0)
return d7 << 7*BYTE_DATA_LINES | d6 << 6*BYTE_DATA_LINES | d5 << 5*BYTE_DATA_LINES | d4 << 4*BYTE_DATA_LINES
| d3 << 3*BYTE_DATA_LINES | d2 << 2*BYTE_DATA_LINES | d1 << BYTE_DATA_LINES | d0;
long d8 = read(data, ++index);
d0 >>>= offset;
d1 <<= BYTE_DATA_LINES - offset;
d2 <<= 2*BYTE_DATA_LINES - offset;
d3 <<= 3*BYTE_DATA_LINES - offset;
d4 <<= 4*BYTE_DATA_LINES - offset;
d5 <<= 5*BYTE_DATA_LINES - offset;
d6 <<= 6*BYTE_DATA_LINES - offset;
d7 <<= 7*BYTE_DATA_LINES - offset;
d8 <<= 8*BYTE_DATA_LINES - offset;
return d8 | d7 | d6 | d5 | d4 | d3 | d2 | d1 | d0;
}
/**
* Writes 64 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeLong(byte[] data, int i, long v) {
int index = i >> BYTE_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -8) return;
int offset = i & BYTE_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (byte)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 2*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 3*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 4*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 5*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 6*BYTE_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 7*BYTE_DATA_LINES);
return;
}
int mask = BYTE_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 2*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 3*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 4*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 5*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 6*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (byte)(v >> 7*BYTE_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (byte)(v >> 8*BYTE_DATA_LINES - offset) & ~mask;
}
/**
* Returns a string representation of the contents of the given storage.
* The string representation consists of digits '0' and '1' for all
* non-offlimits bits. The first character of the returned string
* represents the 0<sup>th</sup> bit.
*
* @param data storage array.
*
* @since 1.0.0
*/
public static String readBitString(byte[] data) {
return readBitString(data, 0, data.length * BYTE_DATA_LINES - 0);
}
/**
* Returns a string representation of a range of the contents of the given
* storage. The string representation consists of digits '0' and '1' for
* bits ranging from {@code offset}, inclusive, to {@code offset + length},
* exclusive. If any offlimits bit is touched, this method will throw
* {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param length number of digits returned.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static String readBitString(byte[] data, int offset, int length) {
char[] dest = new char[length];
return new String(readBitString(data, offset, dest, 0, length));
}
private static char[] readBitString(byte[] src, int srcPos, char[] dest, int destPos, int length) {
Arrays.fill(dest, destPos, length, '0');
for (int i = destPos + length - 1, index = 0; i >= destPos; i--, srcPos++) {
index += srcPos >> BYTE_ADDRESS_LINES;
srcPos &= BYTE_ADDRESS_MASK;
if (readBit0(src, index, srcPos))
dest[i] = '1';
}
return dest;
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code 0}, inclusive, to
* {@code string's length}, exclusive.
*
* @param data storage array.
* @param v string whose contents are stored into given storage.
*
* @since 1.0.0
*/
public static void writeBitString(byte[] data, String v) {
writeBitString(data, 0, v);
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code offset}, inclusive, to
* {@code offset + length}, exclusive. If any offlimits bit is touched,
* this method will throw {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param v string whose contents are stored into given storage.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static void writeBitString(byte[] data, int offset, String v) {
writeBitString(data, offset, v.length(), v);
}
private static void writeBitString(byte[] data, int offset, int length, String v) {
writeBitString(data, offset, v.toCharArray(), 0, length);
}
private static void writeBitString(byte[] dest, int destPos, char[] src, int srcPos, int length) {
for (int i = srcPos + length - 1, index = 0; i >= srcPos; i--, destPos++) {
index += destPos >> BYTE_ADDRESS_LINES;
destPos &= BYTE_ADDRESS_MASK;
writeBit0(dest, index, destPos, src[i] == '1');
}
}
static final int CHAR_ADDRESS_LINES = 4;
static final int CHAR_DATA_LINES = 1 << CHAR_ADDRESS_LINES;
static final int CHAR_ADDRESS_MASK = ~(-1 << CHAR_ADDRESS_LINES);
static final int CHAR_DATA_MASK = ~(-1 << CHAR_DATA_LINES);
// we expect this function to be heavily inlined
private static int read(char[] data, int index) {
return index < data.length && index >=0 ? data[index] & CHAR_DATA_MASK : 0;
}
/**
* Reads the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static boolean readBit(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length || index < 0)
return false;
int offset = i & CHAR_ADDRESS_MASK;
return readBit0(data, index, offset);
}
private static boolean readBit0(char[] data, int index, int offset) {
return (data[index] << ~offset) < 0;
}
/**
* Writes the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeBit(char[] data, int i, boolean v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index < data.length && index >= 0)
writeBit0(data, index, i & CHAR_ADDRESS_MASK, v);
}
private static void writeBit0(char[] data, int index, int offset, boolean v) {
if (v)
data[index] |= 1 << offset;
else
data[index] &= ~(1 << offset);
}
/**
* Assigns the specified bit value to each bit of the specified range of
* the given storage. The range to be filled extends from offset
* {@code from}, inclusive, to offset {@code to}, exclusive. If
* {@code to <= from} this method does nothing.
*
* <p>This method behaves as the following code:
* </p>
* <pre>
* for(int i = from; i < to; i++)
* Store.writeBit(data, i, v);
* </pre>
*
* @param data storage array.
* @param from offset, in bits, 0-based, of the first bit (inclusive) to be
* filled with the specified value.
* @param to offset, in bits, 0-based, of the last bit (exclusive) to be
* filled with the specified value.
* @param v value whose contents will be used to fill the specified region
* into {@code data}.
*
* @since 1.0.0
*/
public static void fill(char[] data, int from, int to, boolean v) {
if (from == to)
return;
if (to < from)
throw new IllegalArgumentException();
// clamp
if (from < 0)
from = 0;
if (to > data.length << CHAR_ADDRESS_LINES)
to = data.length << CHAR_ADDRESS_LINES;
if (!(to > from))
return;
int[] index = {from >> CHAR_ADDRESS_LINES, to >> CHAR_ADDRESS_LINES};
int[] offset = {from & CHAR_ADDRESS_MASK, to & CHAR_ADDRESS_MASK };
if (index[1] == index[0]) {
// special case: subword count
final long LOWEST_BITS_FROM = ~(CHAR_DATA_MASK << offset[0]);
final long HIGHEST_BITS_TO = CHAR_DATA_MASK << offset[1];
if (v)
data[index[0]] |= ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO);
else
data[index[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO;
return;
}
if (offset[0] != 0) {
// handle "from" end specially
final long HIGHEST_BITS = CHAR_DATA_MASK << offset[0];
if (v)
data[index[0]] |= HIGHEST_BITS;
else
data[index[0]] &= ~HIGHEST_BITS;
// first index already taken care of
index[0]++;
}
if (index[1] > index[0])
Arrays.fill(data, index[0], index[1], (char) (v ? -1 : 0));
if (offset[1] != 0) {
final long LOWEST_BITS = ~(CHAR_DATA_MASK << offset[1]);
if (v)
data[index[1]] |= LOWEST_BITS;
else
data[index[1]] &= ~LOWEST_BITS;
}
}
/**
* Reads as {@code byte} the 8 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static byte readByte(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0)
return (byte) d0;
d0 >>>= offset;
if (offset + Byte.SIZE <= CHAR_DATA_LINES)
return (byte)d0;
int d1 = read(data, ++index);
d1 <<= CHAR_DATA_LINES - offset;
return (byte) (d1 | d0);
}
/**
* Writes 8 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeByte(char[] data, int i, byte v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & CHAR_ADDRESS_MASK;
int mask = ~(CHAR_DATA_MASK << Byte.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (offset + Byte.SIZE <= CHAR_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(CHAR_DATA_MASK << Byte.SIZE) >>> CHAR_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >> (CHAR_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code char} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static char readChar(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0)
return (char) d0;
d0 >>>= offset;
int d1 = read(data, ++index);
d1 <<= CHAR_DATA_LINES - offset;
return (char) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeChar(char[] data, int i, char v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & CHAR_ADDRESS_MASK;
int mask = ~(CHAR_DATA_MASK << Character.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Character.SIZE <= CHAR_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(CHAR_DATA_MASK << Character.SIZE) >> CHAR_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> CHAR_DATA_LINES - offset & mask;
}
/**
* Reads as {@code short} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static short readShort(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0)
return (short) d0;
d0 >>>= offset;
int d1 = read(data, ++index);
d1 <<= CHAR_DATA_LINES - offset;
return (short) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeShort(char[] data, int i, short v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & CHAR_ADDRESS_MASK;
int mask = ~(CHAR_DATA_MASK << Short.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Short.SIZE <= CHAR_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(CHAR_DATA_MASK << Short.SIZE) >> CHAR_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> CHAR_DATA_LINES - offset & mask;
}
/**
* Reads as {@code int} the 32 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static int readInt(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0)
return d1 << CHAR_DATA_LINES | d0;
int d2 = read(data, ++index);
d0 >>>= offset;
d1 <<= CHAR_DATA_LINES - offset;
d2 <<= 2*CHAR_DATA_LINES - offset;
return d2 | d1 | d0;
}
/**
* Writes 32 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeInt(char[] data, int i, int v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -2) return;
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (char)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> CHAR_DATA_LINES);
return;
}
int mask = CHAR_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> CHAR_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (char)(v >> 2*CHAR_DATA_LINES - offset) & ~mask;
}
/**
* Reads as {@code long} the 64 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static long readLong(char[] data, int i) {
int index = i >> CHAR_ADDRESS_LINES;
long d0 = read(data, index);
long d1 = read(data, ++index);
long d2 = read(data, ++index);
long d3 = read(data, ++index);
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0)
return d3 << 3*CHAR_DATA_LINES | d2 << 2*CHAR_DATA_LINES | d1 << CHAR_DATA_LINES | d0;
long d4 = read(data, ++index);
d0 >>>= offset;
d1 <<= CHAR_DATA_LINES - offset;
d2 <<= 2*CHAR_DATA_LINES - offset;
d3 <<= 3*CHAR_DATA_LINES - offset;
d4 <<= 4*CHAR_DATA_LINES - offset;
return d4 | d3 | d2 | d1 | d0;
}
/**
* Writes 64 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeLong(char[] data, int i, long v) {
int index = i >> CHAR_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -4) return;
int offset = i & CHAR_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (char)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> CHAR_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> 2*CHAR_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> 3*CHAR_DATA_LINES);
return;
}
int mask = CHAR_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> CHAR_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> 2*CHAR_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (char)(v >> 3*CHAR_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (char)(v >> 4*CHAR_DATA_LINES - offset) & ~mask;
}
/**
* Returns a string representation of the contents of the given storage.
* The string representation consists of digits '0' and '1' for all
* non-offlimits bits. The first character of the returned string
* represents the 0<sup>th</sup> bit.
*
* @param data storage array.
*
* @since 1.0.0
*/
public static String readBitString(char[] data) {
return readBitString(data, 0, data.length * CHAR_DATA_LINES - 0);
}
/**
* Returns a string representation of a range of the contents of the given
* storage. The string representation consists of digits '0' and '1' for
* bits ranging from {@code offset}, inclusive, to {@code offset + length},
* exclusive. If any offlimits bit is touched, this method will throw
* {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param length number of digits returned.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static String readBitString(char[] data, int offset, int length) {
char[] dest = new char[length];
return new String(readBitString(data, offset, dest, 0, length));
}
private static char[] readBitString(char[] src, int srcPos, char[] dest, int destPos, int length) {
Arrays.fill(dest, destPos, length, '0');
for (int i = destPos + length - 1, index = 0; i >= destPos; i--, srcPos++) {
index += srcPos >> CHAR_ADDRESS_LINES;
srcPos &= CHAR_ADDRESS_MASK;
if (readBit0(src, index, srcPos))
dest[i] = '1';
}
return dest;
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code 0}, inclusive, to
* {@code string's length}, exclusive.
*
* @param data storage array.
* @param v string whose contents are stored into given storage.
*
* @since 1.0.0
*/
public static void writeBitString(char[] data, String v) {
writeBitString(data, 0, v);
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code offset}, inclusive, to
* {@code offset + length}, exclusive. If any offlimits bit is touched,
* this method will throw {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param v string whose contents are stored into given storage.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static void writeBitString(char[] data, int offset, String v) {
writeBitString(data, offset, v.length(), v);
}
private static void writeBitString(char[] data, int offset, int length, String v) {
writeBitString(data, offset, v.toCharArray(), 0, length);
}
private static void writeBitString(char[] dest, int destPos, char[] src, int srcPos, int length) {
for (int i = srcPos + length - 1, index = 0; i >= srcPos; i--, destPos++) {
index += destPos >> CHAR_ADDRESS_LINES;
destPos &= CHAR_ADDRESS_MASK;
writeBit0(dest, index, destPos, src[i] == '1');
}
}
static final int SHORT_ADDRESS_LINES = 4;
static final int SHORT_DATA_LINES = 1 << SHORT_ADDRESS_LINES;
static final int SHORT_ADDRESS_MASK = ~(-1 << SHORT_ADDRESS_LINES);
static final int SHORT_DATA_MASK = ~(-1 << SHORT_DATA_LINES);
// we expect this function to be heavily inlined
private static int read(short[] data, int index) {
return index < data.length && index >=0 ? data[index] & SHORT_DATA_MASK : 0;
}
/**
* Reads the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static boolean readBit(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length || index < 0)
return false;
int offset = i & SHORT_ADDRESS_MASK;
return readBit0(data, index, offset);
}
private static boolean readBit0(short[] data, int index, int offset) {
return (data[index] << ~offset) < 0;
}
/**
* Writes the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeBit(short[] data, int i, boolean v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index < data.length && index >= 0)
writeBit0(data, index, i & SHORT_ADDRESS_MASK, v);
}
private static void writeBit0(short[] data, int index, int offset, boolean v) {
if (v)
data[index] |= 1 << offset;
else
data[index] &= ~(1 << offset);
}
/**
* Assigns the specified bit value to each bit of the specified range of
* the given storage. The range to be filled extends from offset
* {@code from}, inclusive, to offset {@code to}, exclusive. If
* {@code to <= from} this method does nothing.
*
* <p>This method behaves as the following code:
* </p>
* <pre>
* for(int i = from; i < to; i++)
* Store.writeBit(data, i, v);
* </pre>
*
* @param data storage array.
* @param from offset, in bits, 0-based, of the first bit (inclusive) to be
* filled with the specified value.
* @param to offset, in bits, 0-based, of the last bit (exclusive) to be
* filled with the specified value.
* @param v value whose contents will be used to fill the specified region
* into {@code data}.
*
* @since 1.0.0
*/
public static void fill(short[] data, int from, int to, boolean v) {
if (from == to)
return;
if (to < from)
throw new IllegalArgumentException();
// clamp
if (from < 0)
from = 0;
if (to > data.length << SHORT_ADDRESS_LINES)
to = data.length << SHORT_ADDRESS_LINES;
if (!(to > from))
return;
int[] index = {from >> SHORT_ADDRESS_LINES, to >> SHORT_ADDRESS_LINES};
int[] offset = {from & SHORT_ADDRESS_MASK, to & SHORT_ADDRESS_MASK };
if (index[1] == index[0]) {
// special case: subword count
final long LOWEST_BITS_FROM = ~(SHORT_DATA_MASK << offset[0]);
final long HIGHEST_BITS_TO = SHORT_DATA_MASK << offset[1];
if (v)
data[index[0]] |= ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO);
else
data[index[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO;
return;
}
if (offset[0] != 0) {
// handle "from" end specially
final long HIGHEST_BITS = SHORT_DATA_MASK << offset[0];
if (v)
data[index[0]] |= HIGHEST_BITS;
else
data[index[0]] &= ~HIGHEST_BITS;
// first index already taken care of
index[0]++;
}
if (index[1] > index[0])
Arrays.fill(data, index[0], index[1], (short) (v ? -1 : 0));
if (offset[1] != 0) {
final long LOWEST_BITS = ~(SHORT_DATA_MASK << offset[1]);
if (v)
data[index[1]] |= LOWEST_BITS;
else
data[index[1]] &= ~LOWEST_BITS;
}
}
/**
* Reads as {@code byte} the 8 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static byte readByte(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0)
return (byte) d0;
d0 >>>= offset;
if (offset + Byte.SIZE <= SHORT_DATA_LINES)
return (byte)d0;
int d1 = read(data, ++index);
d1 <<= SHORT_DATA_LINES - offset;
return (byte) (d1 | d0);
}
/**
* Writes 8 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeByte(short[] data, int i, byte v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & SHORT_ADDRESS_MASK;
int mask = ~(SHORT_DATA_MASK << Byte.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (offset + Byte.SIZE <= SHORT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(SHORT_DATA_MASK << Byte.SIZE) >>> SHORT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >> (SHORT_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code char} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static char readChar(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0)
return (char) d0;
int d1 = read(data, ++index);
d0 >>>= offset;
d1 <<= SHORT_DATA_LINES - offset;
return (char) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeChar(short[] data, int i, char v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & SHORT_ADDRESS_MASK;
int mask = ~(SHORT_DATA_MASK << Character.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Character.SIZE <= SHORT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(SHORT_DATA_MASK << Character.SIZE) >> SHORT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> SHORT_DATA_LINES - offset & mask;
}
/**
* Reads as {@code short} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static short readShort(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0)
return (short) d0;
int d1 = read(data, ++index);
d0 >>>= offset;
d1 <<= SHORT_DATA_LINES - offset;
return (short) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeShort(short[] data, int i, short v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & SHORT_ADDRESS_MASK;
int mask = ~(SHORT_DATA_MASK << Short.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Short.SIZE <= SHORT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(SHORT_DATA_MASK << Short.SIZE) >> SHORT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> SHORT_DATA_LINES - offset & mask;
}
/**
* Reads as {@code int} the 32 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static int readInt(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
int d0 = read(data, index);
int d1 = read(data, ++index);
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0)
return d1 << SHORT_DATA_LINES | d0;
int d2 = read(data, ++index);
d0 >>>= offset;
d1 <<= SHORT_DATA_LINES - offset;
d2 <<= 2*SHORT_DATA_LINES - offset;
return d2 | d1 | d0;
}
/**
* Writes 32 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeInt(short[] data, int i, int v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -2) return;
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (short)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> SHORT_DATA_LINES);
return;
}
int mask = SHORT_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> SHORT_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (short)(v >> 2*SHORT_DATA_LINES - offset) & ~mask;
}
/**
* Reads as {@code long} the 64 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static long readLong(short[] data, int i) {
int index = i >> SHORT_ADDRESS_LINES;
long d0 = read(data, index);
long d1 = read(data, ++index);
long d2 = read(data, ++index);
long d3 = read(data, ++index);
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0)
return d3 << 3*SHORT_DATA_LINES | d2 << 2*SHORT_DATA_LINES | d1 << SHORT_DATA_LINES | d0;
long d4 = read(data, ++index);
d0 >>>= offset;
d1 <<= SHORT_DATA_LINES - offset;
d2 <<= 2*SHORT_DATA_LINES - offset;
d3 <<= 3*SHORT_DATA_LINES - offset;
d4 <<= 4*SHORT_DATA_LINES - offset;
return d4 | d3 | d2 | d1 | d0;
}
/**
* Writes 64 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeLong(short[] data, int i, long v) {
int index = i >> SHORT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -4) return;
int offset = i & SHORT_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (short)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> SHORT_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> 2*SHORT_DATA_LINES);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> 3*SHORT_DATA_LINES);
return;
}
int mask = SHORT_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> SHORT_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> 2*SHORT_DATA_LINES - offset);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (short)(v >> 3*SHORT_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (short)(v >> 4*SHORT_DATA_LINES - offset) & ~mask;
}
/**
* Returns a string representation of the contents of the given storage.
* The string representation consists of digits '0' and '1' for all
* non-offlimits bits. The first character of the returned string
* represents the 0<sup>th</sup> bit.
*
* @param data storage array.
*
* @since 1.0.0
*/
public static String readBitString(short[] data) {
return readBitString(data, 0, data.length * SHORT_DATA_LINES - 0);
}
/**
* Returns a string representation of a range of the contents of the given
* storage. The string representation consists of digits '0' and '1' for
* bits ranging from {@code offset}, inclusive, to {@code offset + length},
* exclusive. If any offlimits bit is touched, this method will throw
* {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param length number of digits returned.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static String readBitString(short[] data, int offset, int length) {
char[] dest = new char[length];
return new String(readBitString(data, offset, dest, 0, length));
}
private static char[] readBitString(short[] src, int srcPos, char[] dest, int destPos, int length) {
Arrays.fill(dest, destPos, length, '0');
for (int i = destPos + length - 1, index = 0; i >= destPos; i--, srcPos++) {
index += srcPos >> SHORT_ADDRESS_LINES;
srcPos &= SHORT_ADDRESS_MASK;
if (readBit0(src, index, srcPos))
dest[i] = '1';
}
return dest;
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code 0}, inclusive, to
* {@code string's length}, exclusive.
*
* @param data storage array.
* @param v string whose contents are stored into given storage.
*
* @since 1.0.0
*/
public static void writeBitString(short[] data, String v) {
writeBitString(data, 0, v);
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code offset}, inclusive, to
* {@code offset + length}, exclusive. If any offlimits bit is touched,
* this method will throw {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param v string whose contents are stored into given storage.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static void writeBitString(short[] data, int offset, String v) {
writeBitString(data, offset, v.length(), v);
}
private static void writeBitString(short[] data, int offset, int length, String v) {
writeBitString(data, offset, v.toCharArray(), 0, length);
}
private static void writeBitString(short[] dest, int destPos, char[] src, int srcPos, int length) {
for (int i = srcPos + length - 1, index = 0; i >= srcPos; i--, destPos++) {
index += destPos >> SHORT_ADDRESS_LINES;
destPos &= SHORT_ADDRESS_MASK;
writeBit0(dest, index, destPos, src[i] == '1');
}
}
static final int INT_ADDRESS_LINES = 5;
static final int INT_DATA_LINES = 1 << INT_ADDRESS_LINES;
static final int INT_ADDRESS_MASK = ~(-1 << INT_ADDRESS_LINES);
static final int INT_DATA_MASK = ~0;
static final long INT_DATA_MASKL = ~(-1L << INT_DATA_LINES);
// we expect this function to be heavily inlined
private static int read(int[] data, int index) {
return index < data.length && index >=0 ? data[index] : 0;
}
private static long readl(int[] data, int index) {
return index < data.length && index >=0 ? (long)data[index] & INT_DATA_MASKL : 0;
}
/**
* Reads the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static boolean readBit(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length || index < 0)
return false;
int offset = i & INT_ADDRESS_MASK;
return readBit0(data, index, offset);
}
private static boolean readBit0(int[] data, int index, int offset) {
return (data[index] << ~offset) < 0;
}
/**
* Writes the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeBit(int[] data, int i, boolean v) {
int index = i >> INT_ADDRESS_LINES;
if (index < data.length && index >= 0)
writeBit0(data, index, i & INT_ADDRESS_MASK, v);
}
private static void writeBit0(int[] data, int index, int offset, boolean v) {
if (v)
data[index] |= 1 << offset;
else
data[index] &= ~(1 << offset);
}
/**
* Assigns the specified bit value to each bit of the specified range of
* the given storage. The range to be filled extends from offset
* {@code from}, inclusive, to offset {@code to}, exclusive. If
* {@code to <= from} this method does nothing.
*
* <p>This method behaves as the following code:
* </p>
* <pre>
* for(int i = from; i < to; i++)
* Store.writeBit(data, i, v);
* </pre>
*
* @param data storage array.
* @param from offset, in bits, 0-based, of the first bit (inclusive) to be
* filled with the specified value.
* @param to offset, in bits, 0-based, of the last bit (exclusive) to be
* filled with the specified value.
* @param v value whose contents will be used to fill the specified region
* into {@code data}.
*
* @since 1.0.0
*/
public static void fill(int[] data, int from, int to, boolean v) {
if (from == to)
return;
if (to < from)
throw new IllegalArgumentException();
// clamp
if (from < 0)
from = 0;
if (to > data.length << INT_ADDRESS_LINES)
to = data.length << INT_ADDRESS_LINES;
if (!(to > from))
return;
int[] index = {from >> INT_ADDRESS_LINES, to >> INT_ADDRESS_LINES};
int[] offset = {from & INT_ADDRESS_MASK, to & INT_ADDRESS_MASK };
if (index[1] == index[0]) {
// special case: subword count
final long LOWEST_BITS_FROM = ~(INT_DATA_MASK << offset[0]);
final long HIGHEST_BITS_TO = INT_DATA_MASK << offset[1];
if (v)
data[index[0]] |= ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO);
else
data[index[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO;
return;
}
if (offset[0] != 0) {
// handle "from" end specially
final long HIGHEST_BITS = INT_DATA_MASK << offset[0];
if (v)
data[index[0]] |= HIGHEST_BITS;
else
data[index[0]] &= ~HIGHEST_BITS;
// first index already taken care of
index[0]++;
}
if (index[1] > index[0])
Arrays.fill(data, index[0], index[1], v ? -1 : 0);
if (offset[1] != 0) {
final long LOWEST_BITS = ~(INT_DATA_MASK << offset[1]);
if (v)
data[index[1]] |= LOWEST_BITS;
else
data[index[1]] &= ~LOWEST_BITS;
}
}
/**
* Reads as {@code byte} the 8 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static byte readByte(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & INT_ADDRESS_MASK;
if (offset == 0)
return (byte) d0;
d0 >>>= offset;
if (offset + Byte.SIZE <= INT_DATA_LINES)
return (byte)d0;
int d1 = read(data, ++index);
d1 <<= INT_DATA_LINES - offset;
return (byte) (d1 | d0);
}
/**
* Writes 8 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeByte(int[] data, int i, byte v) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & INT_ADDRESS_MASK;
int mask = ~(INT_DATA_MASK << Byte.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (offset + Byte.SIZE <= INT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(INT_DATA_MASK << Byte.SIZE) >>> INT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >> (INT_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code char} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static char readChar(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & INT_ADDRESS_MASK;
if (offset == 0)
return (char) d0;
d0 >>>= offset;
if (offset + Character.SIZE <= INT_DATA_LINES)
return (char)d0;
int d1 = read(data, ++index);
d1 <<= INT_DATA_LINES - offset;
return (char) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeChar(int[] data, int i, char v) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & INT_ADDRESS_MASK;
int mask = ~(INT_DATA_MASK << Character.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Character.SIZE <= INT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(INT_DATA_MASK << Character.SIZE) >> INT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> INT_DATA_LINES - offset & mask;
}
/**
* Reads as {@code short} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static short readShort(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & INT_ADDRESS_MASK;
if (offset == 0)
return (short) d0;
d0 >>>= offset;
if (offset + Short.SIZE <= INT_DATA_LINES)
return (short)d0;
int d1 = read(data, ++index);
d1 <<= INT_DATA_LINES - offset;
return (short) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeShort(int[] data, int i, short v) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & INT_ADDRESS_MASK;
int mask = ~(INT_DATA_MASK << Short.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (offset + Short.SIZE <= INT_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(INT_DATA_MASK << Short.SIZE) >> INT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >> INT_DATA_LINES - offset & mask;
}
/**
* Reads as {@code int} the 32 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static int readInt(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
int d0 = read(data, index);
int offset = i & INT_ADDRESS_MASK;
if (offset == 0)
return d0;
int d1 = read(data, ++index);
d0 >>>= offset;
d1 <<= INT_DATA_LINES - offset;
return d1 | d0;
}
/**
* Writes 32 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeInt(int[] data, int i, int v) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & INT_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = v;
return;
}
int mask = INT_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= v << offset & mask;
}
if (++index >= data.length) return;
mask = INT_DATA_MASK >>> INT_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >> (INT_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code long} the 64 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static long readLong(int[] data, int i) {
int index = i >> INT_ADDRESS_LINES;
long d0 = readl(data, index);
long d1 = readl(data, ++index);
int offset = i & INT_ADDRESS_MASK;
if (offset == 0)
return d1 << INT_DATA_LINES | d0;
long d2 = readl(data, ++index);
d0 >>>= offset;
d1 <<= INT_DATA_LINES - offset;
d2 <<= 2*INT_DATA_LINES - offset;
return d2 | d1 | d0;
}
/**
* Writes 64 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeLong(int[] data, int i, long v) {
int index = i >> INT_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -2) return;
int offset = i & INT_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (int)(v >> 0);
if (++index >= data.length) return;
if (index >= 0)
data[index] = (int)(v >> INT_DATA_LINES);
return;
}
int mask = INT_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
if (index >= 0)
data[index] = (int)(v >> INT_DATA_LINES - offset);
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (int)(v >> 2*INT_DATA_LINES - offset) & ~mask;
}
/**
* Returns a string representation of the contents of the given storage.
* The string representation consists of digits '0' and '1' for all
* non-offlimits bits. The first character of the returned string
* represents the 0<sup>th</sup> bit.
*
* @param data storage array.
*
* @since 1.0.0
*/
public static String readBitString(int[] data) {
return readBitString(data, 0, data.length * INT_DATA_LINES - 0);
}
/**
* Returns a string representation of a range of the contents of the given
* storage. The string representation consists of digits '0' and '1' for
* bits ranging from {@code offset}, inclusive, to {@code offset + length},
* exclusive. If any offlimits bit is touched, this method will throw
* {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param length number of digits returned.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static String readBitString(int[] data, int offset, int length) {
char[] dest = new char[length];
return new String(readBitString(data, offset, dest, 0, length));
}
private static char[] readBitString(int[] src, int srcPos, char[] dest, int destPos, int length) {
Arrays.fill(dest, destPos, length, '0');
for (int i = destPos + length - 1, index = 0; i >= destPos; i--, srcPos++) {
index += srcPos >> INT_ADDRESS_LINES;
srcPos &= INT_ADDRESS_MASK;
if (readBit0(src, index, srcPos))
dest[i] = '1';
}
return dest;
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code 0}, inclusive, to
* {@code string's length}, exclusive.
*
* @param data storage array.
* @param v string whose contents are stored into given storage.
*
* @since 1.0.0
*/
public static void writeBitString(int[] data, String v) {
writeBitString(data, 0, v);
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code offset}, inclusive, to
* {@code offset + length}, exclusive. If any offlimits bit is touched,
* this method will throw {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param v string whose contents are stored into given storage.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static void writeBitString(int[] data, int offset, String v) {
writeBitString(data, offset, v.length(), v);
}
private static void writeBitString(int[] data, int offset, int length, String v) {
writeBitString(data, offset, v.toCharArray(), 0, length);
}
private static void writeBitString(int[] dest, int destPos, char[] src, int srcPos, int length) {
for (int i = srcPos + length - 1, index = 0; i >= srcPos; i--, destPos++) {
index += destPos >> INT_ADDRESS_LINES;
destPos &= INT_ADDRESS_MASK;
writeBit0(dest, index, destPos, src[i] == '1');
}
}
static final int LONG_ADDRESS_LINES = 6;
static final int LONG_DATA_LINES = 1 << LONG_ADDRESS_LINES;
static final int LONG_ADDRESS_MASK = ~(-1 << LONG_ADDRESS_LINES);
static final long LONG_DATA_MASK = ~0L;
// we expect this function to be heavily inlined
private static long read(long[] data, int index) {
return index < data.length && index >=0 ? data[index] : 0;
}
/**
* Reads the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static boolean readBit(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length || index < 0)
return false;
int offset = i & LONG_ADDRESS_MASK;
return readBit0(data, index, offset);
}
private static boolean readBit0(long[] data, int index, int offset) {
return (data[index] << ~offset) < 0;
}
/**
* Writes the {@code i}<sup>th</sup> bit of the given storage.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeBit(long[] data, int i, boolean v) {
int index = i >> LONG_ADDRESS_LINES;
if (index < data.length && index >= 0)
writeBit0(data, index, i & LONG_ADDRESS_MASK, v);
}
private static void writeBit0(long[] data, int index, int offset, boolean v) {
if (v)
data[index] |= 1L << offset;
else
data[index] &= ~(1L << offset);
}
/**
* Assigns the specified bit value to each bit of the specified range of
* the given storage. The range to be filled extends from offset
* {@code from}, inclusive, to offset {@code to}, exclusive. If
* {@code to <= from} this method does nothing.
*
* <p>This method behaves as the following code:
* </p>
* <pre>
* for(int i = from; i < to; i++)
* Store.writeBit(data, i, v);
* </pre>
*
* @param data storage array.
* @param from offset, in bits, 0-based, of the first bit (inclusive) to be
* filled with the specified value.
* @param to offset, in bits, 0-based, of the last bit (exclusive) to be
* filled with the specified value.
* @param v value whose contents will be used to fill the specified region
* into {@code data}.
*
* @since 1.0.0
*/
public static void fill(long[] data, int from, int to, boolean v) {
if (from == to)
return;
if (to < from)
throw new IllegalArgumentException();
// clamp
if (from < 0)
from = 0;
if (to > data.length << LONG_ADDRESS_LINES)
to = data.length << LONG_ADDRESS_LINES;
if (!(to > from))
return;
int[] index = {from >> LONG_ADDRESS_LINES, to >> LONG_ADDRESS_LINES};
int[] offset = {from & LONG_ADDRESS_MASK, to & LONG_ADDRESS_MASK };
if (index[1] == index[0]) {
// special case: subword count
final long LOWEST_BITS_FROM = ~(LONG_DATA_MASK << offset[0]);
final long HIGHEST_BITS_TO = LONG_DATA_MASK << offset[1];
if (v)
data[index[0]] |= ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO);
else
data[index[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO;
return;
}
if (offset[0] != 0) {
// handle "from" end specially
final long HIGHEST_BITS = LONG_DATA_MASK << offset[0];
if (v)
data[index[0]] |= HIGHEST_BITS;
else
data[index[0]] &= ~HIGHEST_BITS;
// first index already taken care of
index[0]++;
}
if (index[1] > index[0])
Arrays.fill(data, index[0], index[1], v ? -1L : 0L);
if (offset[1] != 0) {
final long LOWEST_BITS = ~(LONG_DATA_MASK << offset[1]);
if (v)
data[index[1]] |= LOWEST_BITS;
else
data[index[1]] &= ~LOWEST_BITS;
}
}
/**
* Reads as {@code byte} the 8 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static byte readByte(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
long d0 = read(data, index);
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0)
return (byte) d0;
d0 >>>= offset;
if (offset + Byte.SIZE <= LONG_DATA_LINES)
return (byte)d0;
long d1 = read(data, ++index);
d1 <<= LONG_DATA_LINES - offset;
return (byte) (d1 | d0);
}
/**
* Writes 8 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+8}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeByte(long[] data, int i, byte v) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & LONG_ADDRESS_MASK;
long mask = ~(LONG_DATA_MASK << Byte.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (long)v << offset & mask;
}
if (offset + Byte.SIZE <= LONG_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(LONG_DATA_MASK << Byte.SIZE) >>> LONG_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= (v >>> (LONG_DATA_LINES-offset)) & mask;
}
/**
* Reads as {@code char} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static char readChar(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
long d0 = read(data, index);
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0)
return (char) d0;
d0 >>>= offset;
if (offset + Character.SIZE <= LONG_DATA_LINES)
return (char)d0;
long d1 = read(data, ++index);
d1 <<= LONG_DATA_LINES - offset;
return (char) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeChar(long[] data, int i, char v) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & LONG_ADDRESS_MASK;
long mask = ~(LONG_DATA_MASK << Character.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (long)v << offset & mask;
}
if (offset + Character.SIZE <= LONG_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(LONG_DATA_MASK << Character.SIZE) >>> LONG_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >>> LONG_DATA_LINES - offset & mask;
}
/**
* Reads as {@code short} the 16 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static short readShort(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
long d0 = read(data, index);
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0)
return (short) d0;
d0 >>>= offset;
if (offset + Short.SIZE <= LONG_DATA_LINES)
return (short)d0;
long d1 = read(data, ++index);
d1 <<= LONG_DATA_LINES - offset;
return (short) (d1 | d0);
}
/**
* Writes 16 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+16}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeShort(long[] data, int i, short v) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & LONG_ADDRESS_MASK;
long mask = ~(LONG_DATA_MASK << Short.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (long)v << offset & mask;
}
if (offset + Short.SIZE <= LONG_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(LONG_DATA_MASK << Short.SIZE) >>> LONG_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >>> LONG_DATA_LINES - offset & mask;
}
/**
* Reads as {@code int} the 32 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static int readInt(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
long d0 = read(data, index);
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0)
return (int) d0;
d0 >>>= offset;
if (offset + Integer.SIZE <= LONG_DATA_LINES)
return (int)d0;
long d1 = read(data, ++index);
d1 <<= LONG_DATA_LINES - offset;
return (int) (d1 | d0);
}
/**
* Writes 32 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+32}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeInt(long[] data, int i, int v) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & LONG_ADDRESS_MASK;
long mask = ~(LONG_DATA_MASK << Integer.SIZE) << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (long)v << offset & mask;
}
if (offset + Integer.SIZE <= LONG_DATA_LINES)
return;
if (++index >= data.length) return;
mask = ~(LONG_DATA_MASK << Integer.SIZE) >>> LONG_DATA_LINES - offset;
data[index] &= ~mask;
data[index] |= v >>> LONG_DATA_LINES - offset & mask;
}
/**
* Reads as {@code long} the 64 bits of the given storage starting from the
* {@code i}<sup>th</sup> bit. The range of bits read extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
*
* @since 1.0.0
*/
public static long readLong(long[] data, int i) {
int index = i >> LONG_ADDRESS_LINES;
long d0 = read(data, index);
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0)
return d0;
long d1 = read(data, ++index);
d0 >>>= offset;
d1 <<= LONG_DATA_LINES - offset;
return d1 | d0;
}
/**
* Writes 64 bits of the given storage, starting from the
* {@code i}<sup>th</sup> bit. The range of bits written extends from
* {@code i}, inclusive, to offset {@code i+64}, exclusive.
*
* @param data storage array.
* @param i offset, in bits, 0-based.
* @param v value whose contents will be written to {@code data}.
*
* @since 1.0.0
*/
public static void writeLong(long[] data, int i, long v) {
int index = i >> LONG_ADDRESS_LINES;
if (index >= data.length) return;
if (index < -1) return;
int offset = i & LONG_ADDRESS_MASK;
if (offset == 0) {
if (index >= 0)
data[index] = (v >> 0);
return;
}
long mask = LONG_DATA_MASK << offset;
if (index >= 0) {
data[index] &= ~mask;
data[index] |= (v << offset) & mask;
}
if (++index >= data.length) return;
data[index] &= mask;
data[index] |= (v >>> LONG_DATA_LINES - offset) & ~mask;
}
/**
* Returns a string representation of the contents of the given storage.
* The string representation consists of digits '0' and '1' for all
* non-offlimits bits. The first character of the returned string
* represents the 0<sup>th</sup> bit.
*
* @param data storage array.
*
* @since 1.0.0
*/
public static String readBitString(long[] data) {
return readBitString(data, 0, data.length * LONG_DATA_LINES - 0);
}
/**
* Returns a string representation of a range of the contents of the given
* storage. The string representation consists of digits '0' and '1' for
* bits ranging from {@code offset}, inclusive, to {@code offset + length},
* exclusive. If any offlimits bit is touched, this method will throw
* {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param length number of digits returned.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static String readBitString(long[] data, int offset, int length) {
char[] dest = new char[length];
return new String(readBitString(data, offset, dest, 0, length));
}
private static char[] readBitString(long[] src, int srcPos, char[] dest, int destPos, int length) {
Arrays.fill(dest, destPos, length, '0');
for (int i = destPos + length - 1, index = 0; i >= destPos; i--, srcPos++) {
index += srcPos >> LONG_ADDRESS_LINES;
srcPos &= LONG_ADDRESS_MASK;
if (readBit0(src, index, srcPos))
dest[i] = '1';
}
return dest;
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code 0}, inclusive, to
* {@code string's length}, exclusive.
*
* @param data storage array.
* @param v string whose contents are stored into given storage.
*
* @since 1.0.0
*/
public static void writeBitString(long[] data, String v) {
writeBitString(data, 0, v);
}
/**
* Stores a string representation into a range of the contents of the given
* storage. The string representation consists of digits '0' and '1'. The
* range of bits to be stored extends from {@code offset}, inclusive, to
* {@code offset + length}, exclusive. If any offlimits bit is touched,
* this method will throw {@code ArrayIndexOutOfBoundsException}.
*
* @param data storage array.
* @param offset start of range, in bits, 0-based, inclusive.
* @param v string whose contents are stored into given storage.
* @throws ArrayIndexOutOfBoundsException if offset is negative or if
* {@code offset + length} is greater than the number of bits available.
*
* @since 1.0.0
*/
public static void writeBitString(long[] data, int offset, String v) {
writeBitString(data, offset, v.length(), v);
}
private static void writeBitString(long[] data, int offset, int length, String v) {
writeBitString(data, offset, v.toCharArray(), 0, length);
}
private static void writeBitString(long[] dest, int destPos, char[] src, int srcPos, int length) {
for (int i = srcPos + length - 1, index = 0; i >= srcPos; i--, destPos++) {
index += destPos >> LONG_ADDRESS_LINES;
destPos &= LONG_ADDRESS_MASK;
writeBit0(dest, index, destPos, src[i] == '1');
}
}
}
|
package fi.nls.oskari.statistics.eurostat;
import fi.nls.oskari.cache.JedisManager;
import fi.nls.oskari.control.statistics.plugins.StatisticalIndicatorSelector;
import fi.nls.oskari.control.statistics.plugins.StatisticalIndicatorSelectors;
import fi.nls.oskari.control.statistics.plugins.db.DatasourceLayer;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.util.IOHelper;
import fi.nls.oskari.util.XmlHelper;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.jaxen.SimpleNamespaceContext;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class EurostatIndicatorsParser {
private final static Logger LOG = LogFactory.getLogger(EurostatIndicatorsParser.class);
SimpleNamespaceContext NAMESPACE_CTX = new SimpleNamespaceContext();
private EurostatConfig config;
public EurostatIndicatorsParser(EurostatConfig config) throws java.io.IOException {
this.config = config;
NAMESPACE_CTX.addNamespace(XMLConstants.DEFAULT_NS_PREFIX, "http:
NAMESPACE_CTX.addNamespace("xml", "http:
NAMESPACE_CTX.addNamespace("mes", "http:
NAMESPACE_CTX.addNamespace("str", "http:
NAMESPACE_CTX.addNamespace("com", "http:
}
public boolean setMetadata(EurostatIndicator indicator, String dataStructureID) throws Exception {
// here should return boolean
XMLStreamReader reader = null;
boolean hasGEO = false;
try (InputStreamReader inputReader =
new InputStreamReader(
getMetadata(this.getURL("/SDMX/diss-web/rest/datastructure/ESTAT/"), dataStructureID))) {
reader = XMLInputFactory.newInstance().createXMLStreamReader(inputReader);
StAXOMBuilder builder = new StAXOMBuilder(reader);
OMElement eleMeta = builder.getDocumentElement();
AXIOMXPath xpath_Codelist = XmlHelper.buildXPath("/mes:Structure/mes:Structures/str:Codelists/str:Codelist", NAMESPACE_CTX);
AXIOMXPath xpath_codeID = XmlHelper.buildXPath("str:Code", this.NAMESPACE_CTX);
AXIOMXPath xpath_codeName = XmlHelper.buildXPath("com:Name", this.NAMESPACE_CTX);
AXIOMXPath dimensionPath = XmlHelper.buildXPath("/mes:Structure/mes:Structures/str:DataStructures/str:DataStructure/str:DataStructureComponents/str:DimensionList/str:Dimension", NAMESPACE_CTX);
List<OMElement> codelists = xpath_Codelist.selectNodes(eleMeta);// here we have all the codelist indicators
List<OMElement> dimension = dimensionPath.selectNodes(eleMeta);
final StatisticalIndicatorSelectors selectors = new StatisticalIndicatorSelectors();
indicator.setSelectors(selectors);
for (OMElement dimension1 : dimension) {
String idDimension = dimension1.getAttributeValue(QName.valueOf("id"));// idDimension is { FREQ, UNIT, GEO}
if (idDimension.equals("GEO")) {
// we need to know that this indicator has a region dimension ("GEO")
hasGEO = true;
// but we don't pass it as a parameter for the frontend -> skip to next one
continue;
}
StatisticalIndicatorSelector selector = new StatisticalIndicatorSelector(idDimension);
selector.setName(idDimension);
OMElement localRepresentationOme = XmlHelper.getChild(dimension1, "LocalRepresentation");
OMElement enumerationOme = XmlHelper.getChild(localRepresentationOme, "Enumeration");
OMElement refOme = XmlHelper.getChild(enumerationOme, "Ref");
String refId = refOme.getAttributeValue(QName.valueOf("id")); // { refId is CL_FREQ, CL_UNIT}
for (OMElement codelistElem : codelists) {
String id = codelistElem.getAttributeValue(QName.valueOf("id"));// Codelist ID = CL_FREQ
if (!id.equals(refId)) {
continue;
}
List<OMElement> codeID = xpath_codeID.selectNodes(codelistElem);
for (OMElement codeID1 : codeID) {
String nameID = codeID1.getAttributeValue(QName.valueOf("id"));
List<OMElement> codeName = xpath_codeName.selectNodes(codeID1); // Code ID = "D" or "W"
for (OMElement selectValue : codeName) {
String selectValues = selectValue.getText(); // selectedValues = codeName "Daily, weekly "
selector.addAllowedValue(nameID, selectValues);
}
}
selectors.addSelector(selector);
}
}
populateTimeDimension(selectors);
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception ignore) {
}
}
}
return hasGEO;
}
private void populateTimeDimension(StatisticalIndicatorSelectors selectors) {
StatisticalIndicatorSelector selector = new StatisticalIndicatorSelector("time");
selector.setName("time");
// fixme: hardcoded
selector.addAllowedValue("2014");
selector.addAllowedValue("2015");
selector.addAllowedValue("2013");
selector.addAllowedValue("2012");
selectors.addSelector(selector);
}
public String getURL(final String pUrl) throws IOException {
return config.getUrl() + pUrl;
}
public List<EurostatIndicator> parse(List<DatasourceLayer> layers) {
List<EurostatIndicator> list = new ArrayList<>();
XMLStreamReader reader = null;
InputStream is = null;
try {
//is = IOHelper.getConnection(config.getUrl() + "/SDMX/diss-web/rest/dataflow/ESTAT/all/latest").getInputStream();
is = IOHelper.getConnection("http://ec.europa.eu/eurostat/SDMX/diss-web/rest/dataflow/ESTAT/all/latest").getInputStream();
is = IOHelper.debugResponse(is);
} catch (IOException e) {
// do this later
}
try (InputStreamReader inputReader = new InputStreamReader(is)) {
reader = XMLInputFactory.newInstance().createXMLStreamReader(inputReader);
System.out.println(config.getUrl());
StAXOMBuilder builder = new StAXOMBuilder(reader);
OMElement ele = builder.getDocumentElement();
//System.out.println(ele.getText());
AXIOMXPath xpath_indicator = XmlHelper.buildXPath("/mes:Structure/mes:Structures/str:Dataflows/str:Dataflow", NAMESPACE_CTX);
AXIOMXPath xpath_names = XmlHelper.buildXPath("com:Name", NAMESPACE_CTX);
List<OMElement> indicatorsElement = xpath_indicator.selectNodes(ele);
int count= 0;
for (OMElement indicator : indicatorsElement) {
// str:Dataflow
count++;
if (count < 550 || count>600) {
// at this range there should be indicators with NUTS areas as regions
continue;
}
if (list.size() > 10) {
// have 10 indicators with geo:
// break so we don't need to wait all day for the rest to load
break;
}
EurostatIndicator item = new EurostatIndicator();
String id = indicator.getAttributeValue(QName.valueOf("id"));
item.setId(id);// itemId = nama_gdp_c
List<OMElement> names = xpath_names.selectNodes(indicator);
for (OMElement name : names) { // com:Name item (language)="en", item(indicatorName)= "sold production..."
String language = XmlHelper.getAttributeValue(name, "lang");
String indicatorName = name.getText();
item.addLocalizedName(language, indicatorName);
}
OMElement struct = XmlHelper.getChild(indicator, "Structure");
OMElement ref = XmlHelper.getChild(struct, "Ref");
String DSDid = ref.getAttributeValue(QName.valueOf("id"));
boolean indicatorHasRegion = setMetadata(item, DSDid);
if (indicatorHasRegion) {
list.add(item);
}
for (DatasourceLayer layer : layers) {
item.addLayer(new EurostatStatisticalIndicatorLayer(layer.getMaplayerId(), item.getId(), config.getUrl()));
}
}
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception ignore) {
}
}
}
return list;
}
private InputStream getMetadata(String pUrl, String dataStructureID) {
final String url = pUrl + dataStructureID;
final String cacheKey = "stats:" + config.getId() + ":metadata:" + url;
try {
String metadata = JedisManager.get(cacheKey);
if(metadata == null) {
metadata = IOHelper.getURL(url);
JedisManager.setex(cacheKey, JedisManager.EXPIRY_TIME_DAY, metadata);
}
return new ByteArrayInputStream(metadata.getBytes(StandardCharsets.UTF_8));
} catch (IOException ex) {
LOG.error(ex, "Error getting indicator metadata from Pxweb datasource:", url);
}
return null;
}
}
|
package bschecker.bluesheets;
import java.util.ArrayList;
import bschecker.util.ErrorList;
import bschecker.util.LogHelper;
import bschecker.util.PerformanceMonitor;
import bschecker.util.Tools;
import bschecker.util.UtilityMethods;
import opennlp.tools.parser.Parse;
/**
* Defines abstract class for types of grammatical errors
* @author tedpyne
* @author JeremiahDeGreeff
*/
public abstract class Bluesheet {
/**
* Finds errors of a specific type in a paragraph.
* @param line the paragraph in which to find errors
* @param parses a Parse array of each sentence of the line
* @return an ErrorList which for each Error references start token, end token, and, optionally, a note
*/
protected abstract ErrorList findErrors(String line, Parse[] parses);
/**
* Finds all errors within the given text.
* All types included in {@code ERROR_LIST} which have a {@code CheckedWhenAnalyzed} value of {@code true} will be checked.
* Expects text to end with a new line character.
* @param text the text to search
* @return a ErrorList which contains all the errors in the passage, referenced by character indices
*/
public static ErrorList findAllErrors(String text) {
PerformanceMonitor.start("analyze");
if(!text.endsWith("\n"))
text += "\n";
ErrorList errors = new ErrorList(text, false);
int lineNum = 1, charOffset = 0;
String line;
while (charOffset < text.length()) {
PerformanceMonitor.start("line");
line = text.substring(charOffset, charOffset + text.substring(charOffset).indexOf('\n'));
System.out.println();
LogHelper.getLogger(17).info("Analyzing line " + lineNum + " (characters " + charOffset + "-" + (charOffset + line.length()) + "):");
ArrayList<Integer> removedChars = new ArrayList<Integer>();
line = UtilityMethods.removeExtraPunctuation(line, charOffset, removedChars);
LogHelper.getLogger(17).info("Ignoring characters: " + removedChars);
PerformanceMonitor.start("parse");
LogHelper.getLogger(18).info("Parsing line " + lineNum + "...");
String[] sentences = Tools.getSentenceDetector().sentDetect(line);
Parse[] parses = new Parse[sentences.length];
for(int i = 0; i < sentences.length; i++)
parses[i] = UtilityMethods.parse(sentences[i]);
LogHelper.getLogger(18).info("Complete (" + PerformanceMonitor.stop("parse") + ")");
ErrorList lineErrors = new ErrorList(line, true);
for(Bluesheets b : Bluesheets.values())
if(Bluesheets.isSetToAnalyze(b.getNumber())) {
PerformanceMonitor.start("bluesheet");
LogHelper.getLogger(17).info("Looking for: " + b.getName() + "...");
ErrorList temp = b.getObject().findErrors(line, parses);
temp.setBluesheetNumber(b.getNumber());
lineErrors.addAll(temp);
LogHelper.getLogger(17).info(temp.size() + " Error" + (temp.size() == 1 ? "" : "s") + " Found (" + PerformanceMonitor.stop("bluesheet") + ")");
}
LogHelper.getLogger(17).info(lineErrors.size() + " Error" + (lineErrors.size() == 1 ? "" : "s") + " Found in line " + lineNum + " (" + PerformanceMonitor.stop("line") + ")");
errors.addAll(lineErrors.tokensToChars(charOffset, removedChars));
lineNum++;
charOffset += line.length() + removedChars.size() + 1;
}
System.out.println();
LogHelper.getLogger(17).info("Passage analyzed in " + PerformanceMonitor.stop("analyze") + "\n\n" + errors);
return errors;
}
}
|
package codemining.util;
import java.util.Set;
import java.util.SortedSet;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Multisets;
import com.google.common.collect.Sets;
/**
* A utility class containing collection-related utilities.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class CollectionUtil {
/**
* Return the elements that have been seen at least nSeen times.
*
* @param nSeen
* @param baseMultiset
* @return
*/
public static <T> Set<T> getElementsUpToCount(final int nSeen,
final Multiset<T> baseMultiset) {
final Set<T> toKeep = Sets.newHashSet();
for (final Entry<T> entry : Multisets.copyHighestCountFirst(
baseMultiset).entrySet()) {
if (entry.getCount() < nSeen) {
break;
}
toKeep.add(entry.getElement());
}
return toKeep;
}
/**
* Return the top elements of a sorted set.
*
* @param originalSet
* @param nTopElements
* @return
*/
public static <T extends Comparable<T>> SortedSet<T> getTopElements(
final SortedSet<T> originalSet, final int nTopElements) {
final SortedSet<T> filteredElements = Sets.newTreeSet();
int i = 0;
for (final T element : originalSet) {
if (i > nTopElements) {
break;
}
filteredElements.add(element);
i++;
}
return filteredElements;
}
}
|
package com.airbnb.chancery;
import com.airbnb.chancery.model.CallbackPayload;
import com.amazonaws.services.s3.AmazonS3Client;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/* TODO: some metrics */
@Slf4j
public class S3Archiver {
@NonNull
private final RefFilter refFilter;
@NonNull
private final AmazonS3Client s3Client;
@NonNull
private final String bucketName;
@NonNull
private final GithubClient ghClient;
@NonNull
private final PayloadExpressionEvaluator keyTemplate;
public S3Archiver(@NotNull S3ArchiverConfig config,
@NotNull AmazonS3Client s3Client,
@NotNull GithubClient ghClient) {
this.s3Client = s3Client;
this.ghClient = ghClient;
bucketName = config.getBucketName();
refFilter = new RefFilter(config.getRefFilter());
keyTemplate = new PayloadExpressionEvaluator(config.getKeyTemplate());
}
@Subscribe
@AllowConcurrentEvents
public void receiveCallback(@NotNull CallbackPayload payload)
throws IOException, GithubFailure.forDownload {
if (!refFilter.matches(payload))
return;
final String key = keyTemplate.evaluateForPayload(payload);
if (payload.isDeleted())
delete(key);
else {
final java.nio.file.Path path;
final String hash = payload.getAfter();
final String owner = payload.getRepository().getOwner().getName();
final String repoName = payload.getRepository().getName();
path = ghClient.download(owner, repoName, hash);
upload(path.toFile(), key);
try {
Files.delete(path);
} catch (IOException e) {
log.warn("Couldn't delete {}", path, e);
}
}
}
private void delete(@NotNull String key) {
log.info("Removing key {} from {}", key, bucketName);
try {
s3Client.deleteObject(bucketName, key);
} catch (Exception e) {
log.error("Couldn't delete {} from {}", key, bucketName, e);
throw e;
}
log.info("Deleted {} from {}", key, bucketName);
}
private void upload(@NotNull File src, @NotNull String key) {
log.info("Uploading {} to {} in {}", src, key, bucketName);
try {
s3Client.putObject(this.bucketName, key, src);
} catch (Exception e) {
log.error("Couldn't upload to {} in {}", key, bucketName, e);
throw e;
}
log.info("Uploaded to {} in {}", key, bucketName);
}
}
|
package com.github.digital_wonderland.sling_metrics.service;
import com.codahale.metrics.*;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Component(label = "Sling Metrics :: Metric Service", metatype = true)
@Service(value = MetricService.class)
public class MetricService {
private static final Logger LOG = LoggerFactory.getLogger(MetricService.class);
@Property(label = "Enabled", boolValue = true, description = "Should the metrics service be enabled")
private static final String METRIC_SERVICE_ENABLED = "metricService.enabled";
@Property(label = "Global Metric Prefix", description = "Leave empty to use 'sling.metrics.$hostname|$ip'")
private static final String METRIC_PREFIX = "metricService.metricPrefix";
private MetricRegistry registry;
private boolean isEnabled;
private String metricPrefix;
@Activate
protected void activate(final ComponentContext context) {
isEnabled = (Boolean) context.getProperties().get(METRIC_SERVICE_ENABLED);
metricPrefix = (String) context.getProperties().get(METRIC_PREFIX);
metricPrefix = metricPrefix == null ? "" : metricPrefix.trim();
if(metricPrefix.isEmpty()) {
final String tmpl = "sling.metrics.%s";
try {
metricPrefix = String.format(tmpl, InetAddress.getLocalHost().getHostName());
// shorten foo.bar.example.com to foo
metricPrefix = metricPrefix.split("\\.")[0];
} catch (UnknownHostException e) {
LOG.warn("Unable to determine hostname", e);
try {
metricPrefix = String.format(tmpl, InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e1) {
LOG.warn("Unable to determine ip", e1);
metricPrefix = "sling.metrics";
}
}
}
if(isEnabled) {
registry = new MetricRegistry();
LOG.debug("New MetricRegistry created");
}
}
public MetricRegistry getRegistry() {
return registry;
}
public boolean isEnabled() {
return isEnabled;
}
public String getMetricPrefix() { return metricPrefix; }
/**
* Concatenates elements to form a dotted name, eliding any null values or empty strings.
*
* @param name the first element of the name
* @param names the remaining elements of the name
* @return {@code name} and {@code names} concatenated by periods
* @see com.codahale.metrics.MetricRegistry#name
*/
public String name(String name, String... names) {
return com.codahale.metrics.MetricRegistry.name(String.format("%s.%s", metricPrefix, name), names);
}
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
return registry.register(name(name), metric);
}
/**
* Removes the metric with the given name.
*
* @param name the name of the metric
* @return whether or not the metric was removed
* @see com.codahale.metrics.MetricRegistry#remove
*/
public boolean remove(String name) { return registry.remove(name(name)); }
/**
* Creates a new {@link Meter} and registers it under the given name.
*
* @param name the name of the metric
* @return a new {@link Meter}
* @see com.codahale.metrics.MetricRegistry#meter
*/
public Meter meter(String name) { return registry.meter(name(name)); }
/**
* Creates a new {@link Histogram} and registers it under the given name.
*
* @param name the name of the metric
* @return a new {@link Histogram}
* @see com.codahale.metrics.MetricRegistry#histogram
*/
public Histogram histogram(String name) { return registry.histogram(name(name)); }
/**
* Creates a new {@link Counter} and registers it under the given name.
*
* @param name the name of the metric
* @return a new {@link Counter}
* @see com.codahale.metrics.MetricRegistry#counter
*/
public Counter counter(String name) { return registry.counter(name(name)); }
/**
* Creates a new {@link Timer} and registers it under the given name.
*
* @param name the name of the metric
* @return a new {@link Timer}
* @see com.codahale.metrics.MetricRegistry#timer
*/
public Timer timer(String name) { return registry.timer(name(name)); }
}
|
package com.amadornes.jtraits;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import com.google.common.collect.Maps;
public class ASMUtils {
private static Map<Integer, String> opcodes = new HashMap<Integer, String>();
static {
for (Field f : Opcodes.class.getFields()) {
f.setAccessible(true);
try {
opcodes.put(f.getInt(null), f.getName());
} catch (Exception e) {
}
}
}
public static String getOpcode(int opcode) {
return opcodes.get(opcode);
}
public static int addInstructionsWithSuperRedirections(AbstractInsnNode node, List<AbstractInsnNode> added, boolean supercall,
Mixin<?> mixin) {
if (node instanceof FieldInsnNode) {
FieldInsnNode f = (FieldInsnNode) node;
if (matches(f.owner, mixin.getTraitType())) {
if (f.name.equals("_super")) {
added.add(new TypeInsnNode(Opcodes.CHECKCAST, mixin.getNewType()));
return 1;
} else {
added.add(new FieldInsnNode(f.getOpcode(), mixin.getNewType(), f.name, f.desc));
}
} else {
added.add(new FieldInsnNode(f.getOpcode(), f.owner, f.name, f.desc));
}
} else if (node instanceof MethodInsnNode) {
MethodInsnNode m = (MethodInsnNode) node;
if (supercall && !(m.name.equals("<init>") || m.name.equals("<clinit>")) && matches(m.owner, mixin.getParents())) {
added.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, trackClosestImplementation(m.name, m.desc, mixin.getParentClass()),
m.name, m.desc, false));
return 2;
}
if (matches(m.owner, mixin.getParents())) {
added.add(new MethodInsnNode(m.getOpcode(), mixin.getNewType(), m.name, m.desc, m.itf));
} else {
added.add(new MethodInsnNode(m.getOpcode(), m.owner, m.name, m.desc, m.itf));
}
} else if (node instanceof TypeInsnNode) {
TypeInsnNode t = (TypeInsnNode) node;
if (matches(t.desc, mixin.getParents())) {
added.add(new TypeInsnNode(t.getOpcode(), mixin.getNewType()));
} else {
added.add(new TypeInsnNode(t.getOpcode(), t.desc));
}
} else if (node instanceof VarInsnNode) {
VarInsnNode v = (VarInsnNode) node;
if (v.var == 0) {
added.add(new VarInsnNode(v.getOpcode(), v.var));
added.add(new TypeInsnNode(Opcodes.CHECKCAST, mixin.getNewType()));
}
}
return 0;
}
public static String nodeToString(AbstractInsnNode node) {
String str = "[" + getOpcode(node.getOpcode()) + "] ";
if (node instanceof FieldInsnNode) {
FieldInsnNode n = (FieldInsnNode) node;
str += "VARIABLE: owner=\"" + n.owner + "\" name=\"" + n.name + "\" desc=\"" + n.desc + "\"";
} else if (node instanceof MethodInsnNode) {
MethodInsnNode n = (MethodInsnNode) node;
str += "METHOD: owner=\"" + n.owner + "\" name=\"" + n.name + "\" desc=\"" + n.desc + "\"";
} else if (node instanceof TypeInsnNode) {
TypeInsnNode n = (TypeInsnNode) node;
str += "TYPE: desc=\"" + n.desc + "\"";
} else if (node instanceof VarInsnNode) {
VarInsnNode n = (VarInsnNode) node;
str += "VAR: " + n.var;
} else if (node instanceof LdcInsnNode) {
LdcInsnNode n = (LdcInsnNode) node;
str += "CONSTANT: \"" + n.cst + "\"";
} else if (node instanceof LabelNode) {
LabelNode n = (LabelNode) node;
str += "LABEL: " + n.getLabel() + " - " + n.getLabel().hashCode();
} else if (node instanceof JumpInsnNode) {
JumpInsnNode n = (JumpInsnNode) node;
str += "JUMP: " + n.label.getLabel() + " - " + n.label.getLabel().hashCode();
} else if (node instanceof LineNumberNode) {
LineNumberNode n = (LineNumberNode) node;
str += "LINE: " + n.line;
} else if (node instanceof FrameNode) {
FrameNode n = (FrameNode) node;
str += "FRAME: " + n.type;
} else if (node instanceof InsnNode) {
str = getOpcode(node.getOpcode());
} else {
str += node;
}
return str;
}
public static boolean matches(String str, String... others) {
for (String s : others)
if (str.equals(s))
return true;
return false;
}
public static ClassNode getClassNode(Class<?> clazz) {
try {
ClassNode cnode = new ClassNode();
ClassReader reader = new ClassReader(ClassLoadingHelper.instance.getResourceAsStream(clazz.getName().replace(".", "/")
+ ".class"));
reader.accept(cnode, 0);
return cnode;
} catch (IOException ignore) {
ignore.printStackTrace();
return null;
}
}
public static int getReturnCode(String type) {
if (type.equals("V"))
return Opcodes.RETURN;
if (type.equals("B") || type.equals("Z") || type.equals("S") || type.equals("I"))
return Opcodes.IRETURN;
else if (type.equals("L"))
return Opcodes.LRETURN;
else if (type.equals("F"))
return Opcodes.FRETURN;
else if (type.equals("D"))
return Opcodes.DRETURN;
return Opcodes.ARETURN;
}
public static String[] recursivelyFindClasses(Mixin<?> mixin) {
Set<String> set = new HashSet<String>();
recursivelyFindClasses(mixin, set);
return set.toArray(new String[set.size()]);
}
private static void recursivelyFindClasses(Mixin<?> mixin, Set<String> set) {
set.add(mixin.getParentType());
set.add(mixin.getTraitType());
recursivelyFindClasses(set);
Mixin<?> next = ClassLoadingHelper.instance.findMixin(mixin.getParentType().replace("/", "."));
if (next != null)
recursivelyFindClasses(next, set);
}
private static void recursivelyFindClasses(Set<String> set) {
int oldAmt = set.size();
for (String s : new ArrayList<String>(set)) {
try {
Class<?> c = Class.forName(s.replace('/', '.'));
Class<?> sc = c.getSuperclass();
if (sc != null)
set.add(sc.getName().replace('.', '/'));
for (Class<?> i : c.getInterfaces())
set.add(i.getName().replace('.', '/'));
} catch (Exception ex) {
}
}
if (oldAmt != set.size())
recursivelyFindClasses(set);
}
public static MethodNode getMethod(String name, String desc, ClassNode clazz) {
for (MethodNode m : clazz.methods)
if (m.name.equals(name) && m.desc.equals(desc))
return m;
return null;
}
private static NodeCopier copier;
public static void resetCopy(InsnList srcList) {
copier = new NodeCopier(srcList);
}
public static void copyInsn(InsnList destList, AbstractInsnNode insn) {
if (insn == null)
return;
copier.copyTo(insn, destList);
}
private static class NodeCopier {
private Map<LabelNode, LabelNode> labelMap = Maps.newHashMap();
public NodeCopier(InsnList sourceList) {
for (AbstractInsnNode instruction = sourceList.getFirst(); instruction != null; instruction = instruction.getNext())
if (instruction instanceof LabelNode)
labelMap.put(((LabelNode) instruction), new LabelNode());
}
public void copyTo(AbstractInsnNode node, InsnList destination) {
if (node == null)
return;
if (destination == null)
return;
destination.add(node.clone(labelMap));
}
}
public static String trackClosestImplementation(String name, String desc, Class<?> clazz) {
if (clazz == Object.class)
return null;
ClassNode n = getClassNode(clazz);
for (MethodNode m : n.methods)
if (m.name.equals(name) && m.desc.equals(desc))
return Type.getInternalName(clazz);
return trackClosestImplementation(name, desc, clazz.getSuperclass());
}
}
|
package gov.nih.nci.cananolab.service.community.impl;
import gov.nih.nci.cananolab.dto.common.AccessibilityBean;
import gov.nih.nci.cananolab.dto.common.CollaborationGroupBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.exception.CommunityException;
import gov.nih.nci.cananolab.exception.NoAccessException;
import gov.nih.nci.cananolab.service.BaseServiceHelper;
import gov.nih.nci.cananolab.service.community.CommunityService;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.GroupSearchCriteria;
import gov.nih.nci.security.dao.SearchCriteria;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CommunityServiceLocalImpl extends BaseServiceHelper implements
CommunityService {
public CommunityServiceLocalImpl() {
}
public CommunityServiceLocalImpl(UserBean user) {
super(user);
}
public void saveCollaborationGroup(CollaborationGroupBean collaborationGroup)
throws CommunityException {
try {
if (getUser() == null) {
throw new NoAccessException();
}
AuthorizationService authService = super.getAuthService();
AuthorizationManager authManager = authService
.getAuthorizationManager();
Group group = authService
.createAGroup(collaborationGroup.getName());
List<AccessibilityBean> accessibilities = collaborationGroup
.getUserAccessibilities();
String[] userIds = new String[accessibilities.size()];
int i = 0;
for (AccessibilityBean access : accessibilities) {
UserBean user = access.getUser();
userIds[i] = user.getUserId();
// assign user accessibility to the collaboration group
Role role = authService.getRole(access.getRoleName());
authManager.assignUserRoleToProtectionGroup(user.getUserId(),
new String[] { role.getId().toString() },
"CollaborationGroup_" + group.getGroupId());
i++;
}
authManager.addUsersToGroup(group.getGroupId().toString(), userIds);
} catch (Exception e) {
String error = "Error finding existing collaboration groups accessible by the user";
throw new CommunityException(error, e);
}
}
public List<CollaborationGroupBean> findCollaborationGroups()
throws CommunityException {
List<CollaborationGroupBean> collaborationGroups = new ArrayList<CollaborationGroupBean>();
try {
AuthorizationService authService = super.getAuthService();
AuthorizationManager authManager = authService
.getAuthorizationManager();
Group dummy = new Group();
dummy.setGroupName("CollaborationGroup_*");
SearchCriteria sc = new GroupSearchCriteria(dummy);
List results = authManager.getObjects(sc);
for (Object obj : results) {
Group doGroup = (Group) obj;
String pe = "CollaborationGroup_" + doGroup.getGroupId();
if (authService.checkCreatePermission(getUser(), pe)) {
CollaborationGroupBean cGroup = new CollaborationGroupBean();
cGroup.setName(doGroup.getName());
cGroup.setDescription(doGroup.getGroupDesc());
// set user accessibilities
Set<User> users = authManager.getUsers(doGroup.getGroupId()
.toString());
List<String> userNames = new ArrayList<String>(users.size());
for (User user : users) {
userNames.add(user.getLoginName());
}
Map<String, String> userRoles = authService
.getUserRoles(pe);
List<AccessibilityBean> access = new ArrayList<AccessibilityBean>();
for (User user : users) {
AccessibilityBean accessibility = new AccessibilityBean();
accessibility.setGroupName(doGroup.getGroupName());
accessibility.setRoleName(userRoles.get(user
.getLoginName()));
accessibility.setUser(new UserBean(user));
access.add(accessibility);
}
cGroup.setUserAccessibilities(access);
collaborationGroups.add(cGroup);
}
}
} catch (Exception e) {
String error = "Error finding existing collaboration groups accessible by the user";
throw new CommunityException(error, e);
}
return collaborationGroups;
}
}
|
package com.bio4j.exporter;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.graph.step.map.FlatMapStep;
import com.tinkerpop.gremlin.process.graph.step.map.MapStep;
import com.tinkerpop.gremlin.process.graph.step.map.StartStep;
import com.tinkerpop.gremlin.process.util.DefaultTraversal;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.bio4j.exporter.ExporterCore;
import com.bio4j.exporter.Relationship;
public interface GoTraversal<S, E> extends Traversal<S, E> {
// Iterates all GeneOntology terms
public default GoTraversal<S, Vertex> goTerms() {
return (GoTraversal<S, Vertex>) this.addStep(
new StartStep<Vertex>(this, this.memory().<Graph>get("g").V()));
}
// Iterates a specific GeneOntology term
public default GoTraversal<S, Vertex> goTerm(int id) {
return (GoTraversal<S, Vertex>) this.addStep(
new StartStep<Vertex>(this, this.memory().<Graph>get("g").v(id)));
}
//Iterates all related inbound vertices with given relation
public default GoTraversal<S, Vertex> in(Relationship relationship) {
String rel = ExporterCore.returnRelString(relationship);
FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().in(rel));
return (GoTraversal<S, Vertex>) this.addStep(flatMapStep);
}
//Iterates all related inbound vertices
public default GoTraversal<S, Vertex> in() {
FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().in());
return (GoTraversal<S, Vertex>) this.addStep(flatMapStep);
}
//Iterates all related inbound edges
public default GoTraversal<S, Edge> inE() {
FlatMapStep<Vertex, Edge> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().inE());
return (GoTraversal<S, Edge>) this.addStep(flatMapStep);
}
//Iterates all related inbound edges with given relation
public default GoTraversal<S, Edge> inE(Relationship relationship) {
String rel = ExporterCore.returnRelString(relationship);
FlatMapStep<Vertex, Edge> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().inE(rel));
return (GoTraversal<S, Edge>) this.addStep(flatMapStep);
}
//Iterates all related outbound vertices with given relation
public default GoTraversal<S, Vertex> out(Relationship relationship) {
String rel = ExporterCore.returnRelString(relationship);
FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().out(rel));
return (GoTraversal<S, Vertex>) this.addStep(flatMapStep);
}
//Iterates all related outbound vertices
public default GoTraversal<S, Vertex> out() {
FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().out());
return (GoTraversal<S, Vertex>) this.addStep(flatMapStep);
}
//Iterates all related outbound edges
public default GoTraversal<S, Edge> outE() {
FlatMapStep<Vertex, Edge> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().outE());
return (GoTraversal<S, Edge>) this.addStep(flatMapStep);
}
//Iterates all related outbound edges with given relation
public default GoTraversal<S, Edge> outE(Relationship relationship) {
String rel = ExporterCore.returnRelString(relationship);
FlatMapStep<Vertex, Edge> flatMapStep = new FlatMapStep<>(this);
flatMapStep.setFunction(v -> v.get().outE(rel));
return (GoTraversal<S, Edge>) this.addStep(flatMapStep);
}
public default GoTraversal<S,String> id() {
MapStep<Vertex,String> mapStep = new MapStep<>(this);
mapStep.setFunction(v -> v.get().<String>value("com.bio4j.titan.model.go.nodes.TitanGoTerm.TitanGoTermType.id"));
return (GoTraversal<S,String>) this.addStep(mapStep);
}
public default GoTraversal<S,String> synonyms() {
//TODO
return null;
}
public default GoTraversal<S,String> name() {
MapStep<Vertex,String> mapStep = new MapStep<>(this);
mapStep.setFunction(v -> v.get().<String>value("com.bio4j.titan.model.go.nodes.TitanGoTerm.TitanGoTermType.name"));
return (GoTraversal<S,String>) this.addStep(mapStep);
}
public default GoTraversal<S,String> definition() {
MapStep<Vertex,String> mapStep = new MapStep<>(this);
mapStep.setFunction(v -> v.get().<String>value("com.bio4j.titan.model.go.nodes.TitanGoTerm.TitanGoTermType.definition"));
return (GoTraversal<S,String>) this.addStep(mapStep);
}
public default GoTraversal<S,String> comment() {
MapStep<Vertex,String> mapStep = new MapStep<>(this);
mapStep.setFunction(v -> v.get().<String>value("com.bio4j.titan.model.go.nodes.TitanGoTerm.TitanGoTermType.comment"));
return (GoTraversal<S,String>) this.addStep(mapStep);
}
public static GoTraversal of() {
return new DefaultGoTraversal();
}
public class DefaultGoTraversal extends DefaultTraversal implements GoTraversal {}
}
|
package org.springframework.social.provider.jdbc;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.provider.support.Connection;
import org.springframework.social.provider.support.ConnectionRepository;
/**
* JDBC-based connection repository implementation.
* @author Keith Donald
*/
public class JdbcConnectionRepository implements ConnectionRepository {
private final JdbcTemplate jdbcTemplate;
private final TextEncryptor textEncryptor;
private final SimpleJdbcInsert connectionInsert;
/**
* Creates a JDBC-based connection repository.
* @param dataSource the data source
* @param textEncryptor the encryptor to use when storing oauth keys
*/
public JdbcConnectionRepository(DataSource dataSource, TextEncryptor textEncryptor) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.textEncryptor = textEncryptor;
this.connectionInsert = createConnectionInsert();
}
public boolean isConnected(Serializable accountId, String providerId) {
return jdbcTemplate.queryForObject("select exists(select 1 from Connection where accountId = ? and providerId = ?)", Boolean.class, accountId, providerId);
}
public List<Connection> findConnections(Serializable accountId, String providerId) {
return jdbcTemplate.query("select id, accessToken, secret, refreshToken from Connection where accountId = ? and providerId = ? order by id", new RowMapper<Connection>() {
public Connection mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Connection(rs.getLong("id"), decrypt(rs.getString("accessToken")), decrypt(rs.getString("secret")), decrypt(rs.getString("refreshToken")));
}
}, accountId, providerId);
}
public void removeConnection(Serializable accountId, String providerId, Long connectionId) {
jdbcTemplate.update("delete from Connection where accountId = ? and providerId = ? and id = ?", accountId, providerId, connectionId);
}
public Connection saveConnection(Serializable accountId, String providerId, Connection connection) {
try {
Map<String, Object> args = new HashMap<String, Object>();
args.put("accountId", accountId);
args.put("providerId", providerId);
args.put("accessToken", encrypt(connection.getAccessToken()));
args.put("secret", encrypt(connection.getSecret()));
args.put("refreshToken", encrypt(connection.getRefreshToken()));
Number connectionId = connectionInsert.executeAndReturnKey(args);
return new Connection((Long) connectionId, connection.getAccessToken(), connection.getSecret(), connection.getRefreshToken());
} catch (DuplicateKeyException e) {
throw new IllegalArgumentException("Access token is not unique: a connection already exists!", e);
}
}
// internal helpers
private String encrypt(String text) {
return text != null ? textEncryptor.encrypt(text) : text;
}
private String decrypt(String encryptedText) {
return encryptedText != null ? textEncryptor.decrypt(encryptedText) : encryptedText;
}
private SimpleJdbcInsert createConnectionInsert() {
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate);
insert.setTableName("Connection");
insert.setColumnNames(Arrays.asList("accountId", "providerId", "accessToken", "secret", "refreshToken"));
insert.setGeneratedKeyName("id");
return insert;
}
}
|
package com.doctusoft.java;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class LambdAssert {
private LambdAssert() {
throw Failsafe.staticClassInstantiated();
}
public static <T> T assertComputes(Supplier<T> actual) {
return assertComputes(actual, () -> actual.toString());
}
public static <T> T assertComputes(Object context, Supplier<T> actual) {
return assertComputes(actual, () -> String.valueOf(context));
}
public static <T> T assertComputes(Supplier<T> actual, Supplier<String> message) {
try {
return actual.get();
} catch (Exception e) {
throw new AssertionError(message.get() + " threw unexpected exception", e);
}
}
public static <T> T assertReturns(Supplier<T> actual, Predicate<? super T> expected) {
return assertReturns(actual, expected, () -> actual.toString());
}
public static <T> T assertReturns(Object context, Supplier<T> actual, Predicate<? super T> expected) {
return assertReturns(actual, expected, () -> String.valueOf(context));
}
public static <T> T assertReturns(Supplier<T> actual, Predicate<? super T> expected, Supplier<String> message) {
T value = assertComputes(actual, message);
if (!expected.test(value)) {
throw new AssertionError(message.get() + " returned unexpected value: " + value);
}
return value;
}
public static void assertRuns(Runnable action) {
assertRuns(action, () -> action.toString());
}
public static void assertRuns(Object context, Runnable action) {
assertRuns(action, () -> String.valueOf(context));
}
public static void assertRuns(Runnable action, Supplier<String> message) {
try {
action.run();
} catch (Exception e) {
throw new AssertionError(message.get() + " threw unexpected exception", e);
}
}
public static void assertThrows(Runnable action, Predicate<? super Exception> expectedException) {
assertThrows(action, expectedException, () -> action.toString());
}
public static void assertThrows(Object context, Runnable action, Predicate<? super Exception> expectedException) {
assertThrows(action, expectedException, () -> String.valueOf(context));
}
public static void assertThrows(Runnable action, Predicate<? super Exception> expectedException, Supplier<String> message) {
try {
action.run();
throw new AssertionError(message.get() + " completed without exception");
} catch (Exception e) {
assertException(e, expectedException, message);
}
}
public static void assertThrows(Supplier<?> actual, Predicate<? super Exception> expectedException) {
assertThrows(actual, expectedException, () -> actual.toString());
}
public static void assertThrows(Object context, Supplier<?> actual, Predicate<? super Exception> expectedException) {
assertThrows(actual, expectedException, () -> String.valueOf(context));
}
public static void assertThrows(Supplier<?> actual, Predicate<? super Exception> expectedException, Supplier<String> message) {
try {
Object value = actual.get();
throw new AssertionError(message.get() + " completed without exception and returned: " + value);
} catch (Exception e) {
assertException(e, expectedException, message);
}
}
private static void assertException(Exception actual, Predicate<? super Exception> expected, Supplier<String> message) {
if (!expected.test(actual)) {
throw new AssertionError(message.get() + " threw unexpected exception", actual);
}
}
}
|
package com.emc.rest.smart;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import org.apache.http.HttpHost;
import org.apache.http.client.utils.URIUtils;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
public class SmartFilter extends ClientFilter {
public static final String BYPASS_LOAD_BALANCER = "com.emc.rest.smart.bypassLoadBalancer";
private SmartConfig smartConfig;
public SmartFilter(SmartConfig smartConfig) {
this.smartConfig = smartConfig;
}
@Override
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
// check for bypass flag
Boolean bypass = (Boolean) request.getProperties().get(BYPASS_LOAD_BALANCER);
if (bypass != null && bypass) {
return getNext().handle(request);
}
// get highest ranked host for next request
Host host = smartConfig.getLoadBalancer().getTopHost(request.getProperties());
// replace the host in the request
URI uri = request.getURI();
try {
uri = URIUtils.rewriteURI(uri, new HttpHost(host.getName(), uri.getPort(), uri.getScheme()));
} catch (URISyntaxException e) {
throw new RuntimeException("load-balanced host generated invalid URI", e);
}
request.setURI(uri);
// track requests stats for LB ranking
host.connectionOpened(); // not really, but we can't (cleanly) intercept any lower than this
try {
// call to delegate
ClientResponse response = getNext().handle(request);
// capture request stats
if (response.getStatus() >= 500 && response.getStatus() != 501) {
// except for 501 (not implemented), all 50x responses are considered server errors
host.callComplete(true);
} else {
host.callComplete(false);
}
// wrap the input stream so we can capture the actual connection close
response.setEntityInputStream(new WrappedInputStream(response.getEntityInputStream(), host));
return response;
} catch (RuntimeException e) {
// capture requests stats (error)
host.callComplete(true);
host.connectionClosed();
throw e;
}
}
/**
* captures closure in host statistics
*/
protected class WrappedInputStream extends FilterInputStream {
private Host host;
private boolean closed = false;
public WrappedInputStream(InputStream in, Host host) {
super(in);
this.host = host;
}
@Override
public void close() throws IOException {
synchronized (this) {
if (!closed) {
host.connectionClosed(); // capture closure
closed = true;
}
}
super.close();
}
}
}
|
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
/**
* 138. Copy List with Random Pointer
*
* A linked list is given such that each node contains an additional random
* pointer which could point to any node in the list or null.
* Return a deep copy of the list.
*/
public class _138 {
public static class Solution1 {
public Node copyRandomList(Node head) {
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
Map<Node, Node> map = new HashMap();
Node node = head;
//loop for the first time: copy the node themselves with only labels
while (node != null) {
map.put(node, new Node(node.val));
node = node.next;
}
//loop for the second time: copy random and next pointers
node = head;
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
// Definition for singly-linked list with a random pointer.
class Node {
int val;
Node next;
Node random;
Node(int x) {
this.val = x;
}
}
}
}
|
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
/**138. Copy List with Random Pointer
* A linked list is given such that each node contains an additional random
* pointer which could point to any node in the list or null.
* Return a deep copy of the list.*/
public class _138 {
public RandomListNode copyRandomList(RandomListNode head) {
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
Map<RandomListNode, RandomListNode> map = new HashMap();
RandomListNode node = head;
//loop for the first time: copy the node themselves with only labels
while(node != null){
map.put(node, new RandomListNode(node.label));
node = node.next;
}
//loop for the second time: copy random and next pointers
node = head;
while(node != null){
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
// Definition for singly-linked list with a random pointer.
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _199 {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
if (i == size-1) {
result.add(curr.val);
}
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
}
return result;
}
public static void main(String...strings){
_199 test = new _199();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(4);
List<Integer> result = test.rightSideView(root);
for(int i : result){
System.out.print(i + ", ");
}
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
public class _207 {
public static class Solution1 {
/**Kahn's algorithm for topological sorting*/
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
for (int[] prereq : prerequisites) {
indegree[prereq[0]]++;
}
Set<Integer> zeroDegree = new HashSet();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
zeroDegree.add(i);
}
}
if (zeroDegree.isEmpty()) {
return false;
}
while (!zeroDegree.isEmpty()) {
Iterator<Integer> it = zeroDegree.iterator();
int course = it.next();
zeroDegree.remove(course);
for (int[] prereq : prerequisites) {
if (prereq[1] == course) {
indegree[prereq[0]]
if (indegree[prereq[0]] == 0) {
zeroDegree.add(prereq[0]);
}
}
}
}
for (int i : indegree) {
if (i != 0) {
return false;
}
}
return true;
}
}
public static class Solution2 {
/**
* BFS
*/
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
for (int[] pre : prerequisites) {
indegree[pre[0]]++;
}
Queue<Integer> queue = new LinkedList();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
if (queue.isEmpty()) {
return false;
}
while (!queue.isEmpty()) {
int course = queue.poll();
for (int[] pre : prerequisites) {
if (pre[1] == course) {
indegree[pre[0]]
if (indegree[pre[0]] == 0) {
queue.offer(pre[0]);
}
}
}
}
for (int degree : indegree) {
if (degree != 0) {
return false;
}
}
return true;
}
}
public static class Solution3 {
/**
* DFS, the fastest method in all, with the help of a cache and also converted edges into adjacency list,
* although theoretically, all these three methods' time complexity is: O(V+E)
*/
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> courseList = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
courseList.add(new ArrayList<>());
}
for (int[] pre : prerequisites) {
courseList.get(pre[1]).add(pre[0]);
}
int[] visited = new int[numCourses];
//visit each course using DFS
for (int i = 0; i < numCourses; i++) {
if (!dfs(i, courseList, visited)) {
return false;
}
}
return true;
}
private boolean dfs(int course, List<List<Integer>> courseList, int[] visited) {
visited[course] = 1;//mark as temporarily visited
List<Integer> coursesCanBeTaken = courseList.get(course);
for (int i = 0; i < coursesCanBeTaken.size(); i++) {
int courseToTake = coursesCanBeTaken.get(i);
if (visited[courseToTake] == 1) {
return false;
}
if (visited[courseToTake] == 0) {
if (!dfs(courseToTake, courseList, visited)) {
return false;
}
}
}
visited[course] = 2;//mark it as completely done.
return true;
}
}
}
|
package com.fishercoder.solutions;
public class _375 {
public static class Solution1 {
public int getMoneyAmount(int n) {
int[][] table = new int[n + 1][n + 1];
return dp(table, 1, n);
}
private int dp(int[][] table, int s, int e) {
if (s >= e) {
return 0;
}
if (table[s][e] != 0) {
return table[s][e];
}
int res = Integer.MAX_VALUE;
for (int i = s; i <= e; i++) {
int temp = i + Math.max(dp(table, s, i - 1), dp(table, i + 1, e));
res = Math.min(res, temp);
}
table[s][e] = res;
return res;
}
}
public static class Solution2 {
public int getMoneyAmount(int n) {
if (n == 1) {
return 0;
}
int[][] dp = new int[n + 1][n + 1];
for (int x = 1; x < n; x++) {
for (int i = 0; i + x <= n; i++) {
int j = i + x;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k <= j; k++) {
dp[i][j] = Math.min(dp[i][j], k + Math.max(k - 1 >= i ? dp[i][k - 1] : 0, j >= k + 1 ? dp[k + 1][j] : 0));
}
}
}
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n + 1; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
return dp[1][n];
}
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 398. Random Pick Index
*
* Given an array of integers with possible duplicates,
* randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);*/
public class _398 {
//TODO: use reservoir sampling to solve it again
public static class Solution {
//brute force
int[] input;
java.util.Random rand = new java.util.Random();
public Solution(int[] nums) {
input = nums;
}
public int pick(int target) {
List<Integer> list = new ArrayList();
for (int i = 0; i < input.length; i++) {
if (input[i] == target) {
list.add(i);
}
}
if (list.size() == 1) {
return list.get(0);
}
int randomIndex = rand.nextInt(list.size());
return list.get(randomIndex);
}
}
}
|
package com.fishercoder.solutions;
public class _492 {
public static class Solution1 {
public int[] constructRectangle(int area) {
int i = 0;
int j = area;
int[] result = new int[2];
while (i <= j) {
long product = i * j;
if (product == area) {
result[0] = j
result[1] = i++;
} else if (product > area) {
j
} else {
i++;
}
}
return result;
}
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class _938 {
public static class Solution1 {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
List<Integer> list = new ArrayList<>();
dfs(root, low, high, list);
return list.stream().mapToInt(num -> num).sum();
}
private void dfs(TreeNode root, int l, int r, List<Integer> list) {
if (root == null) {
return;
}
if (root.val <= r && root.val >= l) {
list.add(root.val);
}
dfs(root.left, l, r, list);
dfs(root.right, l, r, list);
}
}
}
|
package com.timepath.launcher;
import com.timepath.classloader.CompositeClassLoader;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class Launcher {
public static final Preferences PREFS = Preferences.userNodeForPackage(Launcher.class);
public static final String REPO_MAIN = "public.xml";
private static final Logger LOG = Logger.getLogger(Launcher.class.getName());
private final CompositeClassLoader cl = CompositeClassLoader.createPrivileged();
private final DownloadManager downloadManager = new DownloadManager();
private Package self;
public Launcher() {}
public static void addRepository(Repository r) {
PREFS.node("repositories").putBoolean(r.getLocation(), true);
}
public static void removeRepository(Repository r) {
PREFS.node("repositories").putBoolean(r.getLocation(), false);
}
/**
* @return the downloadManager
*/
public DownloadManager getDownloadManager() {
return downloadManager;
}
public List<Repository> getRepositories() {
List<Repository> lists = new LinkedList<>();
Repository main = Repository.fromIndex("http://dl.dropboxusercontent.com/u/42745598/" + REPO_MAIN);
self = main.getSelf();
lists.add(main);
Preferences repos = PREFS.node("repositories");
try {
for(String repo : repos.keys()) {
if(repos.getBoolean(repo, false)) {
lists.add(Repository.fromIndex(repo));
}
}
} catch(BackingStoreException ex) {
LOG.log(Level.SEVERE, null, ex);
}
return lists;
}
/**
* @return true if self is up to date
*/
public boolean updateRequired() {
return !self.isLatest();
}
/**
* Starts a program on another {@code Thread}. Returns after started
*
* @param program
*/
public void start(Program program) {
program.createThread(cl).start();
}
/**
* @param program
*
* @return a Set of updated {@code Package}s, or null if currently updating
*/
public Set<Package> update(Program program) {
Package parent = program.getPackage();
if(parent.isLocked()) {
LOG.log(Level.INFO, "Package {0} locked, aborting: {1}", new Object[] { parent, program });
return null;
}
parent.setLocked(true);
// check what needs updating
Set<Package> updates = parent.getUpdates();
// map to futures
Map<Package, List<Future<?>>> downloads = new HashMap<>(updates.size());
for(Package pkg : updates) {
List<Future<?>> pkgDownloads = new LinkedList<>();
for(Package pkgDownload : pkg.getDownloads()) {
pkgDownloads.add(downloadManager.submit(pkgDownload));
}
downloads.put(pkg, pkgDownloads);
}
// wait for completion
for(Map.Entry<Package, List<Future<?>>> e : downloads.entrySet()) {
Package pkg = e.getKey();
try {
for(Future<?> future : e.getValue()) {
future.get();
}
LOG.log(Level.INFO, "Updated {0}", pkg);
} catch(InterruptedException | ExecutionException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
parent.setLocked(false);
return downloads.keySet();
}
}
|
package com.tinkerrocks.storage;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.tinkerrocks.structure.*;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class EdgeDB extends StorageAbstractClass {
public void close() {
this.rocksDB.close();
}
public <V> void setProperty(String id, String key, V value) {
try {
put(getColumn(EDGE_COLUMNS.PROPERTIES), (id + key).getBytes(), serialize(value));
} catch (RocksDBException e) {
e.printStackTrace();
}
}
void put(byte[] key, byte[] value) throws RocksDBException {
this.put(null, key, value);
}
void put(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException {
if (columnFamilyHandle != null)
this.rocksDB.put(columnFamilyHandle, StorageConfigFactory.getWriteOptions(), key, value);
else
this.rocksDB.put(StorageConfigFactory.getWriteOptions(), key, value);
}
public void addEdge(byte[] edge_id, String label, RocksElement inVertex, RocksElement outVertex, Object[] keyValues) throws RocksDBException {
if (this.rocksDB.get(edge_id) != null) {
throw Graph.Exceptions.edgeWithIdAlreadyExists(edge_id);
}
if (label == null) {
throw Edge.Exceptions.labelCanNotBeNull();
}
if (label.isEmpty()) {
throw Edge.Exceptions.labelCanNotBeEmpty();
}
put(edge_id, label.getBytes());
put(getColumn(EDGE_COLUMNS.IN_VERTICES), Utils.merge(edge_id,
StorageConstants.PROPERTY_SEPERATOR.getBytes(), (byte[]) inVertex.id()), (byte[]) inVertex.id());
put(getColumn(EDGE_COLUMNS.OUT_VERTICES), Utils.merge(edge_id,
StorageConstants.PROPERTY_SEPERATOR.getBytes(), (byte[]) outVertex.id()), (byte[]) outVertex.id());
Map<String, Object> properties = ElementHelper.asMap(keyValues);
for (Map.Entry<String, Object> entry : properties.entrySet()) {
put(getColumn(EDGE_COLUMNS.PROPERTIES),
Utils.merge(edge_id, StorageConstants.PROPERTY_SEPERATOR.getBytes(), entry.getKey().getBytes()),
serialize(entry.getValue()));
}
}
public List<byte[]> getVertexIDs(byte[] edgeId, Direction direction) {
List<byte[]> vertexIDs = new ArrayList<>(16);
RocksIterator rocksIterator;
byte[] seek_key = Utils.merge(edgeId, StorageConstants.PROPERTY_SEPERATOR.getBytes());
if (direction == Direction.BOTH || direction == Direction.IN) {
rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.IN_VERTICES));
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
vertexIDs.add(Utils.slice(value, seek_key.length));
return true;
});
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.OUT_VERTICES));
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
vertexIDs.add(Utils.slice(value, seek_key.length));
return true;
});
}
return vertexIDs;
}
public Map<String, Object> getProperties(RocksElement element, String[] propertyKeys) throws RocksDBException {
Map<String, Object> results = new HashMap<>();
if (propertyKeys == null || propertyKeys.length == 0) {
RocksIterator rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.PROPERTIES));
byte[] seek_key = Utils.merge((byte[]) element.id(), StorageConstants.PROPERTY_SEPERATOR.getBytes());
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
results.put(new String(Utils.slice(key, seek_key.length, key.length)),
deserialize(value));
return true;
});
// for (rocksIterator.seek(seek_key); rocksIterator.isValid() && Utils.startsWith(rocksIterator.key(), 0, seek_key);
// rocksIterator.next()) {
// results.put(new String(Utils.slice(rocksIterator.key(), seek_key.length, rocksIterator.key().length)),
// deserialize(rocksIterator.value()));
return results;
}
for (String property : propertyKeys) {
byte[] val = rocksDB.get(getColumn(EDGE_COLUMNS.PROPERTIES),
Utils.merge((byte[]) element.id(), StorageConstants.PROPERTY_SEPERATOR.getBytes(),
property.getBytes()));
if (val != null)
results.put(property, deserialize(val));
else
results.put(property, null);
}
return results;
}
public List<Edge> edges(List<byte[]> ids, RocksGraph rocksGraph) throws RocksDBException {
List<Edge> edges = new ArrayList<>();
if (ids.size() == 0) {
RocksIterator iterator = this.rocksDB.newIterator();
iterator.seekToFirst();
while (iterator.isValid()) {
edges.add(getEdge(iterator.key(), rocksGraph));
iterator.next();
}
}
for (byte[] id : ids) {
edges.add(getEdge(id, rocksGraph));
}
return edges;
}
public RocksEdge getEdge(byte[] id, RocksGraph rocksGraph) throws RocksDBException {
try {
return edgeCache.get(id, () -> {
byte[] in_vertex_id = getVertex(id, Direction.IN);
byte[] out_vertex_id = getVertex(id, Direction.OUT);
RocksVertex inVertex = rocksGraph.getStorageHandler().getVertexDB().vertex(in_vertex_id, rocksGraph);
RocksVertex outVertex = rocksGraph.getStorageHandler().getVertexDB().vertex(out_vertex_id, rocksGraph);
return new RocksEdge(id, getLabel(id), rocksGraph, inVertex, outVertex);
});
} catch (ExecutionException e) {
e.printStackTrace();
throw Vertex.Exceptions.edgeAdditionsNotSupported();
}
}
private byte[] getVertex(byte[] id, Direction direction) {
RocksIterator iterator;
if (direction == Direction.BOTH || direction == Direction.OUT)
iterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.OUT_VERTICES));
else {
iterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.IN_VERTICES));
}
byte[] seek_key = Utils.merge(id, StorageConstants.PROPERTY_SEPERATOR.getBytes());
final byte[][] returnValue = new byte[1][1];
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
returnValue[0] = Utils.slice(iterator.key(), seek_key.length);
return false;
});
return returnValue[0];
}
public void remove(RocksEdge rocksEdge) throws RocksDBException {
this.rocksDB.remove((byte[]) rocksEdge.id());
}
public enum EDGE_COLUMNS {
PROPERTIES("PROPERTIES"),
IN_VERTICES("IN_VERTICES"),
OUT_VERTICES("OUT_VERTICES");
String value;
EDGE_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
RocksDB rocksDB;
List<ColumnFamilyHandle> columnFamilyHandleList;
List<ColumnFamilyDescriptor> columnFamilyDescriptors;
Cache<byte[], RocksEdge> edgeCache;
public EdgeDB() throws RocksDBException {
columnFamilyDescriptors = new ArrayList<>(EDGE_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(EDGE_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
for (EDGE_COLUMNS vertex_columns : EDGE_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
StorageConfigFactory.getColumnFamilyOptions()));
}
this.rocksDB = RocksDB.open(StorageConfigFactory.getDBOptions(), StorageConstants.DATABASE_PREFIX + "/edges", columnFamilyDescriptors, columnFamilyHandleList);
this.edgeCache = CacheBuilder.newBuilder().maximumSize(1000000).concurrencyLevel(1000).build();
}
public ColumnFamilyHandle getColumn(EDGE_COLUMNS edge_column) {
return columnFamilyHandleList.get(edge_column.ordinal() + 1);
}
public String getLabel(byte[] id) throws RocksDBException {
return new String(this.rocksDB.get(id));
}
}
|
package com.trsst.server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Category;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Entry;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.standard.StandardQueryParser;
import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler;
import org.apache.lucene.queryparser.flexible.standard.parser.ParseException;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeFilter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.tidy.Tidy;
import com.trsst.Common;
import com.trsst.client.Client;
/**
* Manages storage and indexing of feed and entry documents, and delegates
* storage of resources to another Storage instance.
*
* @author mpowers
*/
public class LuceneStorage implements Storage {
/**
* Shared abdera instance.
*/
private Abdera abdera;
/**
* Deletable storage delegate: used for caching feeds fetched from other
* servers. Basically, if this storage went away, it would be no big deal.
*/
private Storage cacheStorage;
/**
* Persistent storage delegate: used for feeds managed by this server. This
* is basically the user's primary backup of all entries created.
*/
private Storage persistentStorage;
/*
* Lucene readers/writers are thread-safe and shared instances are
* recommended.
*/
private IndexWriter writer;
private IndexReader reader;
private Analyzer analyzer;
/**
* Default constructor manages individual feed, entry, and resource
* documents with a FileStorage.
*
* @throws IOException
*/
public LuceneStorage() throws IOException {
this(new FileStorage());
}
/**
* Manages index and calls to the specified storage delegate to handle
* individual feed, entry, and resource persistence.
*
* @param delegate
* @throws IOException
*/
public LuceneStorage(Storage delegate) throws IOException {
this(delegate, null);
}
/**
* Manages index and calls to the specified storage delegate to handle
* individual feed, entry, and resource persistence. Any feeds managed by
* this server will call to persistent storage rather than cache storage.
*
* @param delegate
* @throws IOException
*/
public LuceneStorage(Storage cache, Storage persistent) throws IOException {
cacheStorage = cache;
persistentStorage = persistent;
abdera = Abdera.getInstance();
Directory dir = FSDirectory.open(new File(Common.getServerRoot(),
"entry.idx"));
analyzer = new StandardAnalyzer(Version.LUCENE_46);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_46,
analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(dir, iwc);
writer.commit();
refreshReader();
}
private void refreshReader() throws IOException {
reader = DirectoryReader.open(writer, true);
}
/**
* Returns feed ids with content hosted on this server. Feeds must be
* ordered by most recent update.
*
* @param start
* the start index from which to return results; if exceeds
* bounds of available results, zero results are returned.
* @param length
* the maximum number of results to return; servers may return
* fewer results.
* @return the specified feed ids hosted on this server.
*/
public String[] getFeedIds(int start, int length) {
return persistentStorage.getFeedIds(start, length);
}
private boolean isManaged(String feedId) {
String[] feedIds = getFeedIds(0, 100);
for (String id : feedIds) {
if (id.equals(feedId)) {
return true;
}
}
return false;
}
private Storage getStorage(String feedId) {
if (persistentStorage == null) {
return cacheStorage;
}
if (isManaged(feedId)) {
return persistentStorage;
}
return cacheStorage;
}
/**
* Returns categories mentioned in content hosted on this server. Categories
* should be ordered by most popular or recently used, or a combination of
* both ("trending").
*
* @param start
* the start index from which to return results; if exceeds
* bounds of available results, zero results are returned.
* @param length
* the maximum number of results to return; servers may return
* fewer results.
* @return the specified trending categories.
*/
public String[] getCategories(int start, int length) {
// TODO: implement category tracking
// return most frequent categories for the past 100 or 1000 entries
return new String[0];
}
public int getEntryCount(Date after, Date before, String query,
String[] mentions, String[] tags, String verb) {
return getEntryCountForFeedId(null, after, before, query, mentions,
tags, verb);
}
public int getEntryCountForFeedId(String feedId, Date after, Date before,
String search, String[] mentions, String[] tags, String verb) {
try {
Filter filter = buildRangeFilter(after, before);
Query query = buildTextQuery(feedId, search, mentions, tags, verb);
CountCollector collector = new CountCollector();
new IndexSearcher(reader).search(query, filter, collector);
return collector.getCount();
} catch (IOException e) {
log.error("Unexpected error getting entry count for feed: "
+ feedId, e);
} catch (QueryNodeException e) {
log.error("Unexpected error executing count query for feed: "
+ feedId, e);
}
return -1;
}
public String[] getEntryIds(int start, int length, Date after, Date before,
String query, String[] mentions, String[] tags, String verb) {
return _getEntryIdsForFeedId(null, start, length, after, before, query,
mentions, tags, verb);
}
public long[] getEntryIdsForFeedId(String feedId, int start, int length,
Date after, Date before, String query, String[] mentions,
String[] tags, String verb) {
String[] ids = _getEntryIdsForFeedId(feedId, start, length, after,
before, query, mentions, tags, verb);
long[] result = null;
if (ids != null) {
result = new long[ids.length];
int i = 0;
int offset = feedId.length() + 1; // entry keys contain feed id
for (String id : ids) {
result[i++] = Long.parseLong(id.substring(offset), 16);
}
}
return result;
}
private String[] _getEntryIdsForFeedId(String feedId, int start,
int length, Date after, Date before, String search,
String[] mentions, String[] tags, String verb) {
try {
Filter filter = buildRangeFilter(after, before);
Query query = buildTextQuery(feedId, search, mentions, tags, verb);
TopDocs hits = new IndexSearcher(reader).search(query, filter,
start + length, new Sort(new SortField("updated",
SortField.Type.LONG, true)));
String[] result = new String[Math.min(length, hits.totalHits)];
int i = 0;
String id;
int replace;
Set<String> fields = new HashSet<String>();
fields.add("entry"); // we only need the entry field
for (ScoreDoc e : hits.scoreDocs) {
id = new IndexSearcher(reader).doc(e.doc).get("entry");
replace = id.lastIndexOf('-');
if (replace != -1) {
id = id.substring(0, replace) + ':'
+ id.substring(replace + 1);
}
result[i++] = id;
}
return result;
} catch (IOException e) {
log.error("Unexpected error getting query for feed: " + feedId, e);
} catch (QueryNodeException e) {
log.error("Unexpected error executing query for feed: " + feedId, e);
}
return null;
}
private Filter buildRangeFilter(Date after, Date before) {
if (after == null && before == null) {
return null;
}
long afterTime;
if (after != null) {
afterTime = after.getTime();
} else {
// all entries are after this key
afterTime = Long.MIN_VALUE;
}
long beforeTime;
if (before != null) {
beforeTime = before.getTime();
} else {
// all entries are before this key
beforeTime = Long.MAX_VALUE;
}
return NumericRangeFilter.newLongRange("updated", afterTime,
beforeTime, false, false);
}
private Query buildTextQuery(String feedId, String search,
String[] mentions, String[] tags, String verb)
throws QueryNodeException {
if (search == null) {
search = "";
}
// feedId = "M9Dvwqp4GcRJe6gh7p73bCcQk8dKLG19z";
// search = "feed:\"HSzp9eneHcqsp4Vdt9pMfP1Qy83FZZwmE\"";
if (verb != null) {
search = search + " verb:" + verb;
}
if (tags != null) {
for (String tag : tags) {
tag = tag.trim();
if (tag.startsWith(Common.FEED_URN_PREFIX)) {
tag = tag.substring(Common.FEED_URN_PREFIX.length());
}
if (tag.startsWith(Common.ENTRY_URN_PREFIX)) {
tag = tag.substring(Common.ENTRY_URN_PREFIX.length());
}
search = search + " tag:\"" + tag.toLowerCase() + "\"";
}
}
if (mentions != null) {
for (String mention : mentions) {
mention = mention.trim();
if (mention.startsWith(Common.FEED_URN_PREFIX)) {
mention = mention
.substring(Common.FEED_URN_PREFIX.length());
}
if (mention.startsWith(Common.ENTRY_URN_PREFIX)) {
mention = mention.substring(Common.ENTRY_URN_PREFIX
.length());
}
// mentions treated as tags in index
search = search + " tag:\"" + mention + "\"";
}
}
if (feedId != null) {
search = "feed:\"" + feedId + "\"" + search;
}
if (search.trim().length() == 0) {
log.trace("No search parameters: " + search);
search = "*"; // return everything
}
StandardQueryParser parser = new StandardQueryParser();
parser.setDefaultOperator(StandardQueryConfigHandler.Operator.AND);
try {
return parser.parse(search, "text");
} catch (ParseException se) {
log.error("Could not parse query: " + search);
throw se;
}
}
/**
* Returns the contents of the unmodified feed element which was previously
* passed to updateFeed for the specified feed; otherwise throws
* FileNotFoundException.
*
* @param feedId
* the specified feed.
* @return a signed feed element and child elements but excluding entry
* elements.
* @throws FileNotFoundException
* if the specified feed does not exist on this server.
* @throws IOException
* if an error occurs obtaining the entry data.
*/
public String readFeed(String feedId) throws FileNotFoundException,
IOException {
return getStorage(feedId).readFeed(feedId);
}
/**
* Receives the contents of a signed feed element to be stored and
* associated with the specified feed. The retured string contains a signed
* feed element and holds all meta-data attributes associated with the feed.
* These contents may be inspected, analyzed, and indexed, but must be
* returned unmodifed to callers of readFeed() so the signature remains
* intact. Note that the feed element DOES NOT contain entry elements.
*
* @param feedId
* the specified feed.
* @param lastUpdated
* the datetime when this feed says it was last updated; used for
* time range queries
* @param feed
* the contents to be persisted.
* @throws IOException
* if a error occurs persisting the entry data.
*/
public void updateFeed(String feedId, Date lastUpdated, String content)
throws IOException {
try {
// NOTE: not yet sure if we want to index feeds
// as we haven't exposed a way to search them
// Feed feed = (Feed) abdera.getParser()
// .parse(new StringReader(content)).getRoot();
// if (feed.getTitle() != null) {
// Document document = new Document();
// document.add(new StringField("feed", feedId, Field.Store.NO));
// document.add(new TextField("title", feed.getTitle(),
// Field.Store.NO));
// document.add(new TextField("subtitle", feed.getSubtitle(),
// Field.Store.NO));
// Person author = feed.getAuthor();
// if (author != null) {
// if (author.getName() != null) {
// document.add(new TextField("name", author.getName(),
// Field.Store.NO));
// if (author.getEmail() != null) {
// document.add(new StringField("address", author
// .getEmail(), Field.Store.NO));
getStorage(feedId).updateFeed(feedId, lastUpdated, content);
// feedWriter.updateDocument(new Term("feed", feedId), document);
} catch (Throwable t) {
log.error(
"Error from update feed: " + feedId + " : " + lastUpdated,
t);
throw new IOException("Could not parse input for: " + feedId
+ " : " + t.getMessage());
}
}
/**
* Returns the contents of a signed entry element for the specified feed
* which was previously passed to updateFeedEntry.
*
* @param feedId
* the specified feed.
* @param entryId
* the desired entry for the specified feed.
* @return a signed entry element.
* @throws FileNotFoundException
* if the specified entry does not exist.
* @throws IOException
* if a error occurs obtaining the entry data.
*/
public String readEntry(String feedId, long entryId)
throws FileNotFoundException, IOException {
return getStorage(feedId).readEntry(feedId, entryId);
}
/**
* Receives the contents of a signed entry element to be stored and
* associated with the specified feed and unique identifier for later
* retrieval by readFeedEntry(). These contents may be inspected, analyzed,
* and indexed, but must be returned unmodifed to callers of readEntry() so
* the signature remains intact.
*
* @param feedId
* the specified feed.
* @param entryId
* the unique identifier for the entry to be persisted.
* @param publishDate
* the datetime when this entry says it was or will be published;
* used for date/time range queries
* @param entry
* an entry element whose contents are to be persisted.
* @throws IOException
* if a error occurs persisting the entry data.
*/
public void updateEntry(String feedId, long entryId, Date publishDate,
String content) throws IOException {
try {
Entry entry = (Entry) abdera.getParser()
.parse(new StringReader(content)).getRoot();
// we also accumulate categories, mentions, and verbs into
// a single combined multivalue string index
Set<String> tags = new HashSet<String>();
// get verb
String verb = null; // "post" is default verb
Element verbElement = entry.getExtension(new QName(
"http://activitystrea.ms/spec/1.0/", "verb", "activity"));
if (verbElement != null) {
if (verbElement.getText() != null) {
verb = verbElement.getText().trim().toLowerCase();
while (verb.length() > 0
&& (verb.charAt(0) == '#' || verb.charAt(0) == '@')) {
// strip our "special" characters
verb = verb.substring(1);
}
}
}
if (verb == null || verb.length() == 0) {
verb = "post"; // "post" is default verb
}
tags.add(verb);
// get categories
List<Category> categories = entry.getCategories();
if (categories != null) {
for (Category e : categories) {
IRI scheme = e.getScheme();
if (scheme != null
&& (Common.TAG_URN.equals(scheme.toString()) || Common.TAG_URN_LEGACY
.equals(scheme.toString()))) {
if (e.getTerm() != null) {
tags.add('#' + e.getTerm().trim().toLowerCase());
}
} else if (scheme != null
&& (Common.MENTION_URN.equals(scheme.toString()) || Common.MENTION_URN_LEGACY
.equals(scheme.toString()))) {
String mention = e.getTerm();
if (mention != null) {
mention = mention.trim();
if (mention.startsWith(Common.FEED_URN_PREFIX)) {
mention = mention
.substring(Common.FEED_URN_PREFIX
.length());
}
if (mention.startsWith(Common.ENTRY_URN_PREFIX)) {
mention = mention
.substring(Common.ENTRY_URN_PREFIX
.length());
}
tags.add('@' + mention);
}
}
}
}
// convert to list and persist
List<String> converted = new LinkedList<String>();
for (String tag : tags) {
converted.add(tag);
}
// extract fields for full-text search index
Document document = new Document();
StringBuffer text = new StringBuffer();
document.add(new StringField("entry", getEntryKeyString(feedId,
entryId), Field.Store.YES));
text.append(entryId).append(' ');
document.add(new StringField("feed", feedId, Field.Store.NO));
text.append(feedId).append(' ');
document.add(new StringField("verb", verb, Field.Store.NO));
text.append(verb).append(' ');
document.add(new LongField("updated", entryId, Field.Store.NO));
text.append(verb).append(' ');
if (entry.getTitle() != null) {
String title = entry.getTitle().toLowerCase();
document.add(new TextField("title", title, Field.Store.NO));
text.append(title).append(' ');
}
if (entry.getSummary() != null) {
String summary = extractTextFromHtml(entry.getSummary())
.toLowerCase();
// System.out.println("extracting: " + summary);
document.add(new TextField("summary", summary, Field.Store.NO));
text.append(summary).append(' ');
}
tags.remove(verb); // don't treat verb as tag in full-text search
for (String tag : tags) {
tag = tag.substring(1); // remove @ or
document.add(new StringField("tag", tag, Field.Store.NO));
text.append(tag).append(' ');
}
document.add(new TextField("text", text.toString(), Field.Store.NO));
// persist the document
getStorage(feedId).updateEntry(feedId, entryId, publishDate,
content);
writer.updateDocument(
new Term("entry", getEntryKeyString(feedId, entryId)),
document);
writer.commit();
refreshReader();
} catch (Throwable t) {
log.error("Error from update entry: " + feedId + " : " + entryId, t);
throw new IOException("Could not parse input for: "
+ getEntryKeyString(feedId, entryId) + " : "
+ t.getMessage());
}
}
private String extractTextFromHtml(String html) {
Tidy tidy = new Tidy();
tidy.setQuiet(true);
tidy.setShowWarnings(false);
org.w3c.dom.Document root = tidy.parseDOM(new StringReader(html), null);
return getText(root.getDocumentElement());
}
private String getText(Node node) {
NodeList children = node.getChildNodes();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
sb.append(getText(child));
sb.append(" ");
break;
case Node.TEXT_NODE:
sb.append(((Text) child).getData());
break;
}
}
return sb.toString();
}
/**
* Delete an existing entry for the specified feed.
*
* @param feedId
* the specified feed.
* @param entryId
* the desired entry for the specified feed.
* @throws FileNotFoundException
* if the specified entry does not exist.
* @throws IOException
* if a error occurs while deleting the entry data.
*/
public void deleteEntry(String feedId, long entryId)
throws FileNotFoundException, IOException {
try {
writer.deleteDocuments(new Term("entry", getEntryKeyString(feedId,
entryId)));
writer.commit();
refreshReader();
} catch (Throwable t) {
log.error("Unexpected error from delete entry: " + feedId + " : "
+ entryId, t);
throw new IOException("Unexpected error while deleting: "
+ getEntryKeyString(feedId, entryId) + " : "
+ t.getMessage());
}
getStorage(feedId).deleteEntry(feedId, entryId);
}
private static final String getEntryKeyString(String feedId, long entityId) {
return feedId + '-' + Long.toHexString(entityId);
}
/**
* Returns the mime-type of the contents of the resource data for the
* specified entry for the specified feed, if known. If not known, returns
* null.
*
* @param feedId
* the specified feed.
* @param entryId
* the specified entry.
* @param resourceId
* the desired resource id for the specified feed and entry.
* @return the mime type of the resource, or null if not known.
* @throws FileNotFoundException
* if the specified resource does not exist on this server.
* @throws IOException
* if a error occurs obtaining the resource data.
*/
public String readFeedEntryResourceType(String feedId, long entryId,
String resourceId) throws FileNotFoundException, IOException {
return getStorage(feedId).readFeedEntryResourceType(feedId, entryId,
resourceId);
}
/**
* Obtains an input stream to read the contents of the resource data for the
* specified entry for the specified feed. Callers must close the input
* stream when finished.
*
* @param feedId
* the specified feed.
* @param entryId
* the specified entry.
* @param resourceId
* the desired resource id for the specified feed and entry.
* @return an input stream to read the contents of the resource.
* @throws FileNotFoundException
* if the specified entry does not exist.
* @throws IOException
* if a error occurs obtaining the resource data.
*/
public InputStream readFeedEntryResource(String feedId, long entryId,
String resourceId) throws FileNotFoundException, IOException {
return getStorage(feedId).readFeedEntryResource(feedId, entryId,
resourceId);
}
/**
* Stores a binary resource for the specified feed and entry by reading the
* specified input stream and persisting the contents for later retrieval by
* readFeedEntryResource(). Implementors must close the input stream when
* finished.
*
* @param feedId
* the specified feed.
* @param entryId
* the specified entry.
* @param resourceId
* the desired resource id for the specified feed and entry.
* @param mimeType
* the mime type of the data if known, otherwise null.
* @param publishDate
* the datetime when the associated entry says it was or will be
* published; used for date/time range queries
* @param data
* an input stream whose contents are to be persisted.
* @throws IOException
* if a error occurs persisting the resource data.
*/
public void updateFeedEntryResource(String feedId, long entryId,
String resourceId, String mimeType, Date publishDate, byte[] data)
throws IOException {
getStorage(feedId).updateFeedEntryResource(feedId, entryId, resourceId,
mimeType, publishDate, data);
}
/**
* Delete an existing resource for the specified feed and entry.
*
* @param feedId
* the specified feed.
* @param entryId
* the specified entry.
* @param resourceId
* the desired resource id for the specified feed and entry.
* @throws IOException
* if a error occurs while deleting the resource data.
*/
public void deleteFeedEntryResource(String feedId, long entryId,
String resourceId) throws IOException {
getStorage(feedId).deleteFeedEntryResource(feedId, entryId, resourceId);
}
private final static org.slf4j.Logger log = org.slf4j.LoggerFactory
.getLogger(Client.class);
private static class CountCollector extends Collector {
int count;
@Override
public void setScorer(Scorer scorer) throws IOException {
// ignore
}
@Override
public void collect(int doc) throws IOException {
count++;
}
@Override
public void setNextReader(AtomicReaderContext context)
throws IOException {
// ignore
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
public int getCount() {
return count;
}
}
}
|
package com.wizzardo.jrt;
import com.wizzardo.http.filter.TokenFilter;
import com.wizzardo.http.framework.Controller;
import com.wizzardo.http.framework.ControllerUrlMapping;
import com.wizzardo.http.framework.Holders;
import com.wizzardo.http.framework.di.DependencyFactory;
import com.wizzardo.http.framework.template.Renderer;
import com.wizzardo.tools.collections.CollectionTools;
import com.wizzardo.tools.io.FileTools;
import com.wizzardo.tools.json.JsonTools;
import com.wizzardo.tools.misc.With;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AppController extends Controller {
RTorrentService rtorrentService;
ControllerUrlMapping mapping = DependencyFactory.get(ControllerUrlMapping.class);
TokenFilter tokenFilter = getTokenFilter();
private TokenFilter getTokenFilter() {
try {
return DependencyFactory.get(TokenFilter.class);
} catch (IllegalStateException ignored) {
}
return null;
}
public Renderer index() {
model().append("config", JsonTools.serialize(new CollectionTools.MapBuilder<>()
.add("ws", mapping.getUrlTemplate("ws").getRelativeUrl())
.add("addTorrent", mapping.getUrlTemplate(AppController.class, "addTorrent").getRelativeUrl())
.add("token", tokenFilter != null ? tokenFilter.generateToken(request) : "")
.add("downloadsPath", Holders.getApplication().getUrlMapping().getUrlTemplate("downloads").getRelativeUrl())
.get()
));
return renderView("index");
}
public Renderer addTorrent() throws IOException {
String link = request.entry("url").asString();
boolean autostart = With.map(request.entry("autostart"), it -> it != null && "on".equals(it.asString()));
byte[] file = request.entry("file").asBytes();
if (file.length != 0) {
File tempFile = File.createTempFile("jrt", "torrent");
tempFile.deleteOnExit();
FileTools.bytes(tempFile, file);
rtorrentService.load(tempFile.getAbsolutePath(), autostart);
} else if (!link.isEmpty()) {
rtorrentService.load(link, autostart);
} else {
throw new IllegalArgumentException("link and file are empty");
}
return renderString("ok");
}
}
|
package com.xiaoleilu.hutool.db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.xiaoleilu.hutool.db.dialect.Dialect;
import com.xiaoleilu.hutool.db.dialect.DialectFactory;
import com.xiaoleilu.hutool.db.meta.Column;
import com.xiaoleilu.hutool.db.meta.Table;
import com.xiaoleilu.hutool.db.sql.Condition;
import com.xiaoleilu.hutool.exceptions.DbRuntimeException;
import com.xiaoleilu.hutool.exceptions.UtilException;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.StaticLog;
import com.xiaoleilu.hutool.util.CharsetUtil;
import com.xiaoleilu.hutool.util.StrUtil;
/**
*
*
* @author Luxiaolei
*
*/
public class DbUtil {
private final static Log log = StaticLog.get();
private DbUtil() {
}
/**
* SQL
*
* @param ds
* @return SQL
*/
public static SqlRunner newSqlRunner(DataSource ds) {
return new SqlRunner(ds);
}
/**
* SQL
*
* @param ds
* @param dialect SQL
* @return SQL
*/
public static SqlRunner newSqlRunner(DataSource ds, Dialect dialect) {
return new SqlRunner(ds, dialect);
}
/**
* SQL<br/>
*
*
* @param objsToClose
*/
public static void close(Object... objsToClose) {
for (Object obj : objsToClose) {
try {
if (obj != null) {
if (obj instanceof ResultSet) {
((ResultSet) obj).close();
} else if (obj instanceof Statement) {
((Statement) obj).close();
} else if (obj instanceof PreparedStatement) {
((PreparedStatement) obj).close();
} else if (obj instanceof Connection) {
((Connection) obj).close();
} else {
log.warn("Object " + obj.getClass().getName() + " not a ResultSet or Statement or PreparedStatement or Connection!");
}
}
} catch (SQLException e) {
}
}
}
/**
* JNDI
* @param jndiName JNDI
* @return
*/
public static DataSource getJndiDs(String jndiName) {
try {
return (DataSource) new InitialContext().lookup(jndiName);
} catch (NamingException e) {
log.error("Find JNDI datasource error!", e);
}
return null;
}
public static List<String> getTables(DataSource ds) {
final List<String> tables = new ArrayList<String>();
Connection conn = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
final DatabaseMetaData metaData = conn.getMetaData();
rs = metaData.getTables(conn.getCatalog(), null, null, new String[]{"TABLES"});
if(rs == null) {
return null;
}
while(rs.next()) {
final String table = rs.getString("TABLE_NAME");
if(StrUtil.isBlank(table) == false) {
tables.add(table);
}
}
} catch (Exception e) {
throw new UtilException("Get tables error!", e);
}finally {
close(rs, conn);
}
return tables;
}
/**
*
* @param rs
* @return
*/
public static String[] getColumnNames(ResultSet rs) {
try {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String[] labelNames = new String[columnCount];
for (int i=0; i<labelNames.length; i++) {
labelNames[i] = rsmd.getColumnLabel(i +1);
}
return labelNames;
} catch (Exception e) {
throw new UtilException("Get colunms error!", e);
}
}
/**
*
* @param ds
* @param tableName
* @return
* @throws SQLException
*/
public static String[] getColumnNames(DataSource ds, String tableName) {
List<String> columnNames = new ArrayList<String>();
Connection conn = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
final DatabaseMetaData metaData = conn.getMetaData();
rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
while(rs.next()) {
columnNames.add(rs.getString("COLUMN_NAME"));
}
return columnNames.toArray(new String[columnNames.size()]);
} catch (Exception e) {
throw new UtilException("Get columns error!", e);
}finally {
close(rs, conn);
}
}
/**
* Entity<br>
* EntityEntityKEY
* @param ds
* @param tableName
* @return Entity
*/
public static Entity createLimitedEntity(DataSource ds, String tableName){
String[] columnNames = getColumnNames(ds, tableName);
return Entity.create(tableName).setFieldNames(columnNames);
}
/**
*
* @param ds
* @param tableName
* @return Table
*/
@SuppressWarnings("resource")
public static Table getTableMeta(DataSource ds, String tableName) {
final Table table = Table.create(tableName);
Connection conn = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
final DatabaseMetaData metaData = conn.getMetaData();
rs = metaData.getPrimaryKeys(conn.getCatalog(), null, tableName);
while(rs.next()) {
table.addPk("COLUMN_NAME");
}
rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
while(rs.next()) {
table.setColumn(Column.create(tableName, rs));
}
} catch (Exception e) {
throw new UtilException("Get columns error!", e);
}finally {
close(rs, conn);
}
return table;
}
/**
* SQL
*
* @param ps PreparedStatement
* @param params SQL
* @throws SQLException
*/
public static void fillParams(PreparedStatement ps, Collection<Object> params) throws SQLException {
fillParams(ps, params.toArray(new Object[params.size()]));
}
/**
* SQL
*
* @param ps PreparedStatement
* @param params SQL
* @throws SQLException
*/
public static void fillParams(PreparedStatement ps, Object... params) throws SQLException {
if (params == null) {
return;
}
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i = 0; i < params.length; i++) {
int paramIndex = i + 1;
if (params[i] != null) {
ps.setObject(paramIndex, params[i]);
} else {
int sqlType = Types.VARCHAR;
try {
sqlType = pmd.getParameterType(paramIndex);
} catch (SQLException e) {
log.warn("Param get type fail, by: " + e.getMessage());
}
ps.setNull(paramIndex, sqlType);
}
}
}
/**
* <br>
* Oracle
* @param ps PreparedStatement
* @return
* @throws SQLException
*/
public static Long getGeneratedKeyOfLong(PreparedStatement ps) throws SQLException {
ResultSet rs = null;
try {
rs = ps.getGeneratedKeys();
Long generatedKey = null;
if(rs != null && rs.next()) {
try{
generatedKey = rs.getLong(1);
}catch (SQLException e){
//Oraclerowid
}
}
return generatedKey;
} catch (SQLException e) {
throw e;
}finally {
close(rs);
}
}
/**
* <br>
* @param ps PreparedStatement
* @return
* @throws SQLException
*/
public static List<Object> getGeneratedKeys(PreparedStatement ps) throws SQLException {
List<Object> keys = new ArrayList<Object>();
ResultSet rs = null;
int i=1;
try {
rs = ps.getGeneratedKeys();
if(rs != null && rs.next()) {
keys.add(rs.getObject(i++));
}
return keys;
} catch (SQLException e) {
throw e;
}finally {
close(rs);
}
}
/**
* where<br>
*
* @param entity
* @param paramValues List
* @return whereSQL
*/
public static String buildEqualsWhere(Entity entity, List<Object> paramValues) {
if(null == entity || entity.isEmpty()) {
return StrUtil.EMPTY;
}
final StringBuilder sb = new StringBuilder(" WHERE ");
boolean isNotFirst = false;
for (Entry<String, Object> entry : entity.entrySet()) {
if(isNotFirst) {
sb.append(" and ");
}else {
isNotFirst = true;
}
sb.append("`").append(entry.getKey()).append("`").append(" = ?");
paramValues.add(entry.getValue());
}
return sb.toString();
}
/**
*
* @param entity
* @return
*/
public static Condition[] buildConditions(Entity entity){
if(null == entity || entity.isEmpty()) {
return null;
}
final Condition[] conditions = new Condition[entity.size()];
int i = 0;
for (Entry<String, Object> entry : entity.entrySet()) {
conditions[i++] = new Condition(entry.getKey(), entry.getValue());
}
return conditions;
}
/**
* JDBC
* @param nameContainsProductInfo
* @return
*/
public static String identifyDriver(String nameContainsProductInfo) {
if(StrUtil.isBlank(nameContainsProductInfo)) {
return null;
}
nameContainsProductInfo = nameContainsProductInfo.toLowerCase();
String driver = null;
if(nameContainsProductInfo.contains("mysql")) {
driver = DialectFactory.DRIVER_MYSQL;
}else if(nameContainsProductInfo.contains("oracle")) {
driver = DialectFactory.DRIVER_ORACLE;
}else if(nameContainsProductInfo.contains("postgresql")) {
driver = DialectFactory.DRIVER_POSTGRESQL;
}else if(nameContainsProductInfo.contains("sqlite")) {
driver = DialectFactory.DRIVER_SQLLITE3;
}
return driver;
}
/**
* JDBC
* @param ds
* @return
*/
public static String identifyDriver(DataSource ds) {
Connection conn = null;
String driver = null;
try {
conn = ds.getConnection();
driver = identifyDriver(conn);
} catch (Exception e) {
throw new DbRuntimeException("Identify driver error!", e);
}finally {
close(conn);
}
return driver;
}
/**
* JDBC
* @param conn
* @return
*/
public static String identifyDriver(Connection conn) {
String driver = null;
try {
DatabaseMetaData meta = conn.getMetaData();
driver = identifyDriver(meta.getDatabaseProductName());
if(StrUtil.isBlank(driver)) {
driver = identifyDriver(meta.getDriverName());
}
} catch (SQLException e) {
throw new DbRuntimeException("Identify driver error!", e);
}
return driver;
}
/**
*
* @param entity
*/
public static void validateEntity(Entity entity){
if(null == entity) {
throw new DbRuntimeException("Entity is null !");
}
if(StrUtil.isBlank(entity.getTableName())) {
throw new DbRuntimeException("Entity`s table name is null !");
}
if(entity.isEmpty()) {
throw new DbRuntimeException("No filed and value in this entity !");
}
}
/**
* RowId
* @param rowId RowId
* @param charset
* @return
*/
public static String rowIdToString(RowId rowId){
return StrUtil.str(rowId.getBytes(), CharsetUtil.CHARSET_ISO_8859_1);
}
}
|
package cz.pfreiberg.knparser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import cz.pfreiberg.knparser.parser.ParserException;
public class KnParser {
private static final Logger log = Logger.getLogger(KnParser.class);
public static void main(String[] args) {
log.info("KnParser started.");
boolean parseWholeFolder = false;
boolean toDatabase = false;
Configuration configuration = new Configuration();
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--all":
parseWholeFolder = true;
break;
case "--database":
toDatabase = true;
break;
case "--input":
i++;
if (i < args.length) {
configuration.setInput(args[i]);
}
break;
case "--output":
i++;
if (i < args.length) {
String path = args[i];
String lastChar = args[i].substring(args[i].length() - 1);
if (!lastChar.equals(File.separator)) {
path = args[i] + File.separator;
}
configuration.setOutput(path);
}
break;
default:
log.fatal("Invalid command line switch.");
return;
}
}
try {
if (configuration.getInput() == null) {
log.fatal("Input is not specified.");
return;
}
loadPropertyFile(toDatabase, configuration);
if (toDatabase) {
if (!configuration.isConnectionParametersValid()) {
log.fatal("KnParser.properties must contain url, username and password to be able to connect to database.");
return;
}
} else {
if (configuration.getOutput() == null) {
log.fatal("Output is not specified.");
return;
}
}
} catch (NullPointerException e) {
log.fatal("KnParser.properties was not found.");
log.debug("Stack trace: " + e);
return;
} catch (IOException e) {
log.fatal("Error during reading KnParser.properties");
log.debug("Stack trace: " + e);
return;
} catch (NumberFormatException e) {
log.fatal("KnParser.properties is corrupted - couldn't obtain number of rows.");
log.debug("Stack trace: " + e);
return;
}
if (parseWholeFolder) {
parseFolder(configuration);
} else {
parseFile(configuration);
}
log.info("KnParser finished.");
}
private static void loadPropertyFile(boolean toDatabase,
Configuration configuration) throws IOException,
NumberFormatException {
Properties properties = new Properties();
properties.load(KnParser.class
.getResourceAsStream("KnParser.properties"));
String numberOfRows = properties.getProperty("numberOfRows");
configuration.setNumberOfRows(Integer.parseInt(numberOfRows));
if (toDatabase) {
ConnectionParameters connection = getConnectionParameters(properties);
configuration.setConnection(connection);
}
}
private static ConnectionParameters getConnectionParameters(
Properties properties) {
ConnectionParameters connection = new ConnectionParameters();
connection.setUrl(properties.getProperty("url"));
connection.setUser(properties.getProperty("username"));
connection.setPassword(properties.getProperty("password"));
return connection;
}
private static void parseFolder(Configuration configuration) {
String input = configuration.getInput();
String output = configuration.getOutput();
List<String> files = getFilenames(input);
for (int i = 0; i < files.size(); i++) {
configuration = new Configuration(input + File.separator
+ files.get(i), output + files.get(i) + File.separator,
configuration.getNumberOfRows(),
configuration.getConnection());
parseFile(configuration);
}
}
private static List<String> getFilenames(String path) {
File folder = new File(path);
if (!folder.isDirectory()) {
log.fatal("Input must be a directory.");
System.exit(0);
}
File[] listOfFiles = folder.listFiles();
List<String> output = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
output.add(listOfFiles[i].getName());
}
}
return output;
}
private static void parseFile(Configuration configuration) {
log.info("Parsing file " + configuration.getInput());
try {
Controller controller = new Controller(configuration);
controller.run();
} catch (FileNotFoundException e) {
log.fatal("Input file was not found, or can't be read.");
log.debug("Stack trace:", e);
} catch (ParserException e) {
log.fatal(e.getMessage());
log.debug("Stack trace:", e);
} catch (IOException e) {
log.fatal("Error during reading input file.");
log.debug("Stack trace:", e);
}
}
}
|
package de.berlin.hu.chemspot;
import de.berlin.hu.chemspot.ChemSpotConfiguration.Component;
import de.berlin.hu.types.PubmedDocument;
import de.berlin.hu.uima.ae.feature.FeatureTokenGenerator;
import de.berlin.hu.uima.ae.feature.FeatureTokenGenerator.Feature_Phase;
import de.berlin.hu.util.Constants;
import org.apache.uima.UIMAException;
import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CAS;
import org.apache.uima.examples.SourceDocumentInformation;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import org.apache.uima.util.XMLInputSource;
import org.u_compare.shared.semantic.NamedEntity;
import org.u_compare.shared.syntactic.Token;
import org.uimafit.factory.AnalysisEngineFactory;
import org.uimafit.factory.JCasFactory;
import org.uimafit.util.JCasUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
public class ChemSpot {
private TypeSystemDescription typeSystem;
private AnalysisEngine posTagger;
private AnalysisEngine sentenceDetector;
private AnalysisEngine sentenceConverter;
private AnalysisEngine tokenConverter;
private AnalysisEngine crfTagger;
private AnalysisEngine dictionaryTagger;
private AnalysisEngine chemicalFormulaTagger;
private AnalysisEngine abbrevTagger;
private AnalysisEngine annotationMerger;
private AnalysisEngine fineTokenizer;
private AnalysisEngine stopwordFilter;
private AnalysisEngine mentionExpander;
private AnalysisEngine normalizer;
//private FeatureTokenGenerator featureGenerator;
private ChemicalNEREvaluator evaluator;
/**
* Initializes ChemSpot without a dictionary automaton and a normalizer.
* @param pathToCRFModelFile the Path to a CRF model
*/
public ChemSpot(String pathToCRFModelFile, String pathToSentenceModelFile) {
new ChemSpot(pathToCRFModelFile, null, pathToSentenceModelFile, null);
}
/**
* Initializes ChemSpot without a normalizer.
* @param pathToCRFModelFile the Path to a CRF model
*/
public ChemSpot(String pathToCRFModelFile, String pathToDictionaryFile, String pathToSentenceModelFile) {
new ChemSpot(pathToCRFModelFile, pathToDictionaryFile, pathToSentenceModelFile, null);
}
/**
* Initializes ChemSpot with a CRF model, an OpenNLP sentence model and a dictionary automaton.
* @param pathToCRFModelFile the path to a CRF model
* @param pathToDictionaryFile the ath to a dictionary automaton
*/
public ChemSpot(String pathToCRFModelFile, String pathToDictionaryFile, String pathToSentenceModelFile, String pathToIDs) {
try {
typeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(new XMLInputSource(this.getClass().getClassLoader().getResource("desc/TypeSystem.xml")));
if (ChemSpotConfiguration.useComponent(Component.TOKENIZER)) {
fineTokenizer = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tokenizer/FineGrainedTokenizerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
tokenConverter = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/converter/OpenNLPToUCompareTokenConverterAE.xml"))));
}
if (ChemSpotConfiguration.useComponent(Component.POS_TAGGER)) {
posTagger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/opennlp/PosTagger.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.SENTENCE_DETECTOR)) {
sentenceDetector = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/opennlp/SentenceDetector.xml"))), "opennlp.uima.ModelName", pathToSentenceModelFile);
sentenceConverter = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/converter/OpenNLPToUCompareSentenceConverterAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.CRF)) {
System.out.println("Loading CRF...");
crfTagger = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/banner/tagger/BANNERTaggerAE.xml"))), "BannerModelFile", pathToCRFModelFile);
}
if (ChemSpotConfiguration.useComponent(Component.DICTIONARY)) {
if (pathToDictionaryFile != null) {
System.out.println("Loading dictionary...");
dictionaryTagger = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/BricsTaggerAE.xml"))), "DrugBankMatcherDictionaryAutomat", pathToDictionaryFile);
} else System.out.println("No dictionary location specified! Tagging without dictionary...");
}
if (ChemSpotConfiguration.useComponent(Component.SUM_TAGGER)) {
chemicalFormulaTagger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/ChemicalFormulaTaggerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.ABBREV)) {
abbrevTagger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/tagger/AbbreviationTaggerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.MENTION_EXPANDER)) {
mentionExpander = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/expander/MentionExpanderAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.ANNOTATION_MERGER)) {
annotationMerger = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/AnnotationMergerAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.NORMALIZER)) {
if (pathToIDs != null) {
normalizer = AnalysisEngineFactory.createPrimitive(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/normalizer/NormalizerAE.xml"))), "PathToIDs", pathToIDs);
} else System.out.println("No location for ids specified! Tagging without subsequent normalization...");
}
if (ChemSpotConfiguration.useComponent(Component.STOPWORD_FILTER)) {
stopwordFilter = AnalysisEngineFactory.createAnalysisEngine(UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(this.getClass().getClassLoader()
.getResource("desc/ae/filter/StopwordFilterAE.xml"))), CAS.NAME_DEFAULT_SOFA);
}
if (ChemSpotConfiguration.useComponent(Component.FEATURE_GENERATOR)) {
//featureGenerator = new FeatureTokenGenerator();
}
setEvaluator(new ChemicalNEREvaluator());
System.out.println("Finished initializing ChemSpot.");
} catch (UIMAException e) {
System.err.println("Failed initializing ChemSpot.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Failed initializing ChemSpot.");
e.printStackTrace();
}
}
/**
* Returns all mentions (non-goldstandard entities) from a jcas object.
*
* @param jcas the jcas
* @return
*/
public static List<Mention> getMentions(JCas jcas) {
List<Mention> mentions = new ArrayList<Mention>();
Iterator<NamedEntity> entities = JCasUtil.iterator(jcas, NamedEntity.class);
while (entities.hasNext()) {
NamedEntity entity = entities.next();
//disregards gold-standard mentions
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
mentions.add(new Mention(entity));
}
}
return mentions;
}
/**
* Returns all goldstandard entities from a jcas object.
*
* @param jcas the jcas
* @return
*/
public static List<Mention> getGoldstandardAnnotations(JCas jcas) {
List<Mention> result = new ArrayList<Mention>();
Iterator<NamedEntity> entities = JCasUtil.iterator(jcas, NamedEntity.class);
while (entities.hasNext()) {
NamedEntity entity = entities.next();
if (Constants.GOLDSTANDARD.equals(entity.getSource())) {
result.add(new Mention(entity));
}
}
return result;
}
/**
* Reads a text from a file and puts the content into the provided jcas.
*
* @param jcas the jcas
* @param pathToFile the path to the text file
* @throws IOException
*/
public static void readFile(JCas jcas, String pathToFile) throws IOException {
FileInputStream stream = new FileInputStream(new File(pathToFile));
String text = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
text = Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
jcas.setDocumentText(text);
PubmedDocument pd = new PubmedDocument(jcas);
pd.setBegin(0);
pd.setEnd(text.length());
pd.setPmid("");
pd.addToIndexes(jcas);
}
/**
* Reads a text from a gzipped file and puts the content into the provided jcas.
*
* @param jcas the jcas
* @param pathToFile the path to the text file
* @throws IOException
*/
public static void readGZFile(JCas jcas, String pathToFile) throws IOException {
File file = new File(pathToFile);
String text;
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream(file)) ) );
StringBuilder textBuffer = new StringBuilder();
Integer currindex = -1;
while(reader.ready()){
PubmedDocument pmdoc = new PubmedDocument(jcas);
String s = reader.readLine();
if (s != null) {
//split line into pmid and text
String pmid = s.substring(0, s.indexOf("\t"));
String annot = s.substring(s.indexOf("\t"));
//two = splitFirst(s, "\t");
pmdoc.setPmid(pmid);
//append text
textBuffer.append(annot).append("\n");
pmdoc.setBegin(currindex + 1);
Integer len = annot.length();
currindex = currindex + len + 1;
pmdoc.setEnd(currindex);
pmdoc.addToIndexes();
}
}
text = textBuffer.toString();
//put document in CAS
jcas.setDocumentText(text);
SourceDocumentInformation srcDocInfo = new SourceDocumentInformation(jcas);
srcDocInfo.setUri(file.getAbsoluteFile().toURI().toString());
srcDocInfo.setOffsetInSource(0);
srcDocInfo.setDocumentSize((int) file.length());
srcDocInfo.setBegin(0);
srcDocInfo.setEnd(currindex);
srcDocInfo.addToIndexes();
}
/**
* Finds chemical entities in the document of a {@code JCas} object and returns a list of mentions.
* @param jcas contains the document text
* @return a list of mentions
*/
public List<Mention> tag(JCas jcas) {
List<NamedEntity> otherEntities = null;
try {
if (fineTokenizer != null) fineTokenizer.process(jcas);
synchronized (this) {
if (fineTokenizer != null) sentenceDetector.process(jcas);
if (fineTokenizer != null) posTagger.process(jcas);
}
if (tokenConverter != null) tokenConverter.process(jcas);
if (sentenceConverter != null) sentenceConverter.process(jcas);
if (crfTagger != null) crfTagger.process(jcas);
if (dictionaryTagger != null) dictionaryTagger.process(jcas);
if (chemicalFormulaTagger != null) chemicalFormulaTagger.process(jcas);
if (abbrevTagger != null) abbrevTagger.process(jcas);
//if (featureGenerator != null) featureGenerator.process(jcas, Feature_Phase.PHASE1);
if (mentionExpander != null) mentionExpander.process(jcas);
//if (featureGenerator != null) featureGenerator.process(jcas, Feature_Phase.PHASE2);
if (annotationMerger != null) annotationMerger.process(jcas);
if (stopwordFilter != null) stopwordFilter.process(jcas);
//if (featureGenerator != null) featureGenerator.process(jcas, Feature_Phase.PHASE3);
if (normalizer != null) normalizer.process(jcas);
//if (featureGenerator != null) featureGenerator.process(jcas, Feature_Phase.PHASE4);
} catch (AnalysisEngineProcessException e) {
System.err.println("Failed to extract chemicals from text.");
e.printStackTrace();
} finally {
if (otherEntities != null && !otherEntities.isEmpty()) {
for (NamedEntity ne : otherEntities) {
ne.addToIndexes();
}
}
}
return getMentions(jcas);
/*Oscar oscar = new Oscar();
ChemicalEntityRecogniser recogniser = new MEMMRecogniser(new PubMedModel(), OntologyTerms.getDefaultInstance(), new ChemNameDictRegistry(Locale.ENGLISH));
List<PubmedDocument> documents = new ArrayList<PubmedDocument>();
for (PubmedDocument doc : JCasUtil.iterate(jcas, PubmedDocument.class)) {
documents.add(doc);
}
if (documents.isEmpty()) {
PubmedDocument doc = new PubmedDocument(jcas);
doc.setBegin(0);
doc.setEnd(jcas.getDocumentText().length());
doc.setPmid("");
doc.addToIndexes(jcas);
documents.add(doc);
}
for (PubmedDocument doc : documents) {
List<uk.ac.cam.ch.wwmm.oscar.document.NamedEntity> entities = recogniser.findNamedEntities(oscar.tokenise(doc.getCoveredText()), ResolutionMode.REMOVE_BLOCKED);
for (uk.ac.cam.ch.wwmm.oscar.document.NamedEntity rne : entities) {
if (!rne.getType().isInstance(NamedEntityType.COMPOUND)){
continue;
}
NamedEntity entity = new NamedEntity(jcas);
entity.setBegin(doc.getBegin() + rne.getStart());
entity.setEnd(doc.getBegin() + rne.getEnd());
for (String id : rne.getOntIds()) {
if (id.contains("CHEBI:")) {
entity.setId("," + id);
}
}
entity.setSource("OSCAR");
entity.addToIndexes();
}
}
return null;*/
}
/**
* Finds chemical entities in a {@code text} and returns a list of mentions.
* @param text natural language text from which ChemSpot shall extract chemical entities
* @return a list of mentions
* @throws UIMAException
*/
public List<Mention> tag(String text) throws UIMAException {
JCas jcas = JCasFactory.createJCas(typeSystem);
jcas.setDocumentText(text);
PubmedDocument pd = new PubmedDocument(jcas);
pd.setBegin(0);
pd.setEnd(text.length());
pd.setPmid("");
pd.addToIndexes(jcas);
return tag(jcas);
}
/**
* Converts all annotations from jcas to the IOB format
*
* @param jcas the jcas
* @return
*/
public static String convertToIOB(JCas jcas) {
StringBuilder sb = new StringBuilder();
HashMap<String, ArrayList<NamedEntity>> goldAnnotations = new HashMap<String, ArrayList<NamedEntity>>();
HashMap<String, ArrayList<NamedEntity>> pipelineAnnotations = new HashMap<String, ArrayList<NamedEntity>>();
System.out.println("Converting annotations to IOB format...");
Iterator<PubmedDocument> abstracts = JCasUtil.iterator(jcas, PubmedDocument.class);
while (abstracts.hasNext()) {
PubmedDocument pubmedAbstract = abstracts.next();
sb.append("### ").append(pubmedAbstract.getPmid()).append("\n");
int offset = pubmedAbstract.getBegin();
String pmid = pubmedAbstract.getPmid();
List<Token> tokens = JCasUtil.selectCovered(Token.class, pubmedAbstract);
for (Token token : tokens) {
token.setLabel("O");
}
List<NamedEntity> entities = JCasUtil.selectCovered(NamedEntity.class, pubmedAbstract);
for (NamedEntity entity : entities) {
int firstTokenBegin = 0;
int lastTokenEnd = 0;
String id = entity.getId();
if (id == null) id = "";
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
if (pipelineAnnotations.containsKey(pmid)) {
pipelineAnnotations.get(pmid).add(entity);
} else {
ArrayList<NamedEntity> tempArray = new ArrayList<NamedEntity>();
tempArray.add(entity);
pipelineAnnotations.put(pmid, tempArray);
}
List<Token> entityTokens = JCasUtil.selectCovered(Token.class, entity);
boolean first = true;
for (Token token : entityTokens) {
if (first) {
if (id.isEmpty()) token.setLabel("B-CHEMICAL"); else token.setLabel("B-CHEMICAL" + "\t" + id);
first = false;
firstTokenBegin = token.getBegin();
} else {
token.setLabel("I-CHEMICAL" + "\t" + id);
}
lastTokenEnd = token.getEnd();
}
assert entity.getBegin() == firstTokenBegin : (id + ": " + entity.getBegin() + " -> " + firstTokenBegin);
assert entity.getEnd() == lastTokenEnd : (id + ": " + entity.getEnd() + " -> " + lastTokenEnd);
} else {
if (goldAnnotations.containsKey(pmid)) {
goldAnnotations.get(pmid).add(entity);
} else {
ArrayList<NamedEntity> tempArray = new ArrayList<NamedEntity>();
tempArray.add(entity);
goldAnnotations.put(pmid, tempArray);
}
}
}
List<Token> tokensToPrint = JCasUtil.selectCovered(Token.class, pubmedAbstract);
boolean firstToken = true;
for (Token token : tokensToPrint) {
if (firstToken && (token.getBegin() - offset) != 0) {
sb.append(" " + "\t" + 0 + "\t").append(token.getBegin() - offset).append("\t\t|O\n");
}
firstToken = false;
sb.append(token.getCoveredText()).append("\t").append(token.getBegin() - offset).append("\t").append(token.getEnd() - offset).append("\t\t|").append(token.getLabel()).append("\n");
}
}
return sb.toString();
}
public static String serializeAnnotations(JCas jcas) {
int offset;
StringBuilder sb = new StringBuilder();
Iterator<PubmedDocument> documentIterator = JCasUtil.iterator(jcas, PubmedDocument.class);
while (documentIterator.hasNext()) {
PubmedDocument document = documentIterator.next();
offset = document.getBegin();
String pmid = document.getPmid();
int numberOfEntities = 0;
Iterator<NamedEntity> entityIterator = JCasUtil.iterator(document, NamedEntity.class, true, true);
while (entityIterator.hasNext()) {
NamedEntity entity = entityIterator.next();
if (!Constants.GOLDSTANDARD.equals(entity.getSource())) {
//offset fix for GeneView
//int begin = entity.getBegin() - offset;
int begin = entity.getBegin() - offset - 1;
//int end = entity.getEnd() - offset - 1;
int end = entity.getEnd() - offset - 2;
String id = (new Mention(entity)).getCHID();
String text = entity.getCoveredText();
if (id == null || id.isEmpty()) {
sb.append(pmid + "\t" + begin + "\t" + end + "\t" + text + "\t" + "\\N\n");
} else {
sb.append(pmid + "\t" + begin + "\t" + end + "\t" + text + "\t" + id + "\n");
}
}
numberOfEntities++;
}
if (numberOfEntities == 0) {
sb.append(pmid + "\t-1\t-1\t\\N\t\\N\n");
}
}
return sb.toString();
}
public ChemicalNEREvaluator getEvaluator() {
return evaluator;
}
public void setEvaluator(ChemicalNEREvaluator evaluator) {
this.evaluator = evaluator;
}
}
|
package dk.kleistsvendsen;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.inject.Inject;
import roboguice.activity.RoboActivity;
public class HomeActivity extends RoboActivity {
@Inject
private IGameTimer gameTimer;
private TextView timeLeftText;
private TextView timePlayedText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
connectButtons_();
}
private void connectButtons_() {
Button startButton = (Button) findViewById(R.id.start_button);
timeLeftText = (TextView) findViewById(R.id.timeLeftText);
timePlayedText = (TextView) findViewById(R.id.timePlayedText);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gameTimer.startTimer();
timeLeftText.setText(Long.toString(gameTimer.timePlayed()));
timePlayedText.setText(Long.toString(gameTimer.tic()));
}
});
Button pauseButton = (Button) findViewById(R.id.pause_button);
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gameTimer.pauseTimer();
timeLeftText.setText(Long.toString(gameTimer.timePlayed()));
timePlayedText.setText(Long.toString(gameTimer.tic()));
}
});
Button resetButton = (Button) findViewById(R.id.reset_button);
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gameTimer.resetTimer();
timeLeftText.setText(Long.toString(gameTimer.timePlayed()));
timePlayedText.setText(Long.toString(gameTimer.tic()));
}
});
}
}
|
package elegit;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.controlsfx.control.NotificationPane;
import org.controlsfx.control.action.Action;
import org.eclipse.jgit.api.MergeResult;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.lib.Repository;
import java.io.IOException;
/**
*
* A controller for the BranchManager view that holds all a repository's
* branches (in the form of BranchHelpers) and manages branch creation,
* deletion, and tracking of remotes.
*
*/
public class BranchManagerController {
public Text branchOffFromText;
public TextField newBranchNameField;
@FXML
private Button newBranchButton;
public ListView<RemoteBranchHelper> remoteListView;
public ListView<LocalBranchHelper> localListView;
private Repository repo;
private RepoHelper repoHelper;
private BranchModel branchModel;
@FXML
private NotificationPane notificationPane;
@FXML
private Button mergeButton;
@FXML
private Button deleteLocalBranchesButton;
@FXML
private Button trackRemoteBranchButton;
@FXML
private Button swapMergeBranchesButton;
private SessionModel sessionModel;
private LocalCommitTreeModel localCommitTreeModel;
private RemoteCommitTreeModel remoteCommitTreeModel;
private Stage stage;
static final Logger logger = LogManager.getLogger();
public void initialize() throws Exception {
logger.info("Started up branch manager");
this.sessionModel = SessionModel.getSessionModel();
this.repoHelper = this.sessionModel.getCurrentRepoHelper();
this.repo = this.repoHelper.getRepo();
this.branchModel = repoHelper.getBranchModel();
for (CommitTreeModel commitTreeModel : CommitTreeController.allCommitTreeModels) {
if (commitTreeModel.getViewName().equals(LocalCommitTreeModel
.LOCAL_TREE_VIEW_NAME)) {
this.localCommitTreeModel = (LocalCommitTreeModel)commitTreeModel;
} else if (commitTreeModel.getViewName().equals(RemoteCommitTreeModel
.REMOTE_TREE_VIEW_NAME)) {
this.remoteCommitTreeModel = (RemoteCommitTreeModel)commitTreeModel;
}
}
this.remoteListView.setItems(FXCollections.observableArrayList(branchModel.getRemoteBranchesTyped()));
this.localListView.setItems(FXCollections.observableArrayList(branchModel.getLocalBranchesTyped()));
// Local list view can select multiple (for merges):
this.localListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
this.remoteListView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
this.setIcons();
this.updateButtons();
}
/**
* A helper method that sets the icons and colors for buttons
*/
private void setIcons() {
Text cloudDownIcon = GlyphsDude.createIcon(FontAwesomeIcon.CLOUD_DOWNLOAD);
cloudDownIcon.setFill(Color.WHITE);
this.trackRemoteBranchButton.setGraphic(cloudDownIcon);
Text trashIcon = GlyphsDude.createIcon(FontAwesomeIcon.TRASH);
trashIcon.setFill(Color.WHITE);
this.deleteLocalBranchesButton.setGraphic(trashIcon);
Text arrowsIcon = GlyphsDude.createIcon(FontAwesomeIcon.EXCHANGE);
arrowsIcon.setFill(Color.WHITE);
this.swapMergeBranchesButton.setGraphic(arrowsIcon);
this.swapMergeBranchesButton.setTooltip(new Tooltip("Swap which branch is merging into which."));
Text branchIcon = GlyphsDude.createIcon(FontAwesomeIcon.CODE_FORK);
branchIcon.setFill(Color.WHITE);
this.newBranchButton.setGraphic(branchIcon);
}
/**
* Shows the branch manager
* @param pane NotificationPane
*/
public void showStage(NotificationPane pane) {
stage = new Stage();
stage.setTitle("Branch Manager");
stage.setScene(new Scene(pane, 550, 450));
stage.initModality(Modality.APPLICATION_MODAL);
stage.setOnCloseRequest(event -> logger.info("Closed branch manager window"));
stage.show();
}
/**
* Closes the branch manager
*/
public void closeWindow() {
stage.close();
}
/**
* Handles a mouse click on the remote list view
*/
public void handleRemoteListViewMouseClick() {
if (!localListView.getSelectionModel().isEmpty()) {
localListView.getSelectionModel().clearSelection();
}
try {
this.updateButtons();
} catch (IOException e1) {
logger.error("Branch manager remote list view mouse click error");
logger.debug(e1.getStackTrace());
e1.printStackTrace();
}
}
/**
* Handles a mouse click on the local list view
*/
public void handleLocalListViewMouseClick() {
if (!remoteListView.getSelectionModel().isEmpty()) {
remoteListView.getSelectionModel().clearSelection();
}
try {
this.updateButtons();
} catch (IOException e1) {
logger.error("Branch manager local list view mouse click error");
logger.debug(e1.getStackTrace());
e1.printStackTrace();
}
}
public void onNewBranchButton() {
try {
logger.info("New branch button clicked");
LocalBranchHelper newLocalBranch = this.createNewLocalBranch(this.newBranchNameField.getText());
this.localListView.getItems().add(newLocalBranch);
this.newBranchNameField.clear();
} catch (InvalidRefNameException e1) {
logger.warn("Invalid branch name warning");
this.showInvalidBranchNameNotification();
} catch (RefNotFoundException e1) {
// When a repo has no commits, you can't create branches because there
// are no commits to point to. This error gets raised when git can't find
// HEAD.
logger.warn("Can't create branch without a commit in the repo warning");
this.showNoCommitsYetNotification();
} catch (GitAPIException e1) {
logger.warn("Git error");
logger.debug(e1.getStackTrace());
this.showGenericGitErrorNotification();
e1.printStackTrace();
} catch (IOException e1) {
logger.warn("Unspecified IOException");
logger.debug(e1.getStackTrace());
this.showGenericErrorNotification();
e1.printStackTrace();
}
}
/**
* Updates the track remote, merge, and delete local buttons'
* text and/or disabled/enabled status.
*
* @throws IOException
*/
private void updateButtons() throws IOException {
String currentBranchName = this.repo.getBranch();
this.branchOffFromText.setText(String.format("Branch off from %s:", currentBranchName));
// Update delete button
if (this.localListView.getSelectionModel().getSelectedIndices().size() > 0) {
this.deleteLocalBranchesButton.setDisable(false);
// But keep trackRemoteBranchButton disabled
this.trackRemoteBranchButton.setDisable(true);
}
// Update track button
if (this.remoteListView.getSelectionModel().getSelectedIndices().size() > 0) {
this.trackRemoteBranchButton.setDisable(false);
// But keep the other buttons disabled
this.deleteLocalBranchesButton.setDisable(true);
this.mergeButton.setDisable(true);
this.swapMergeBranchesButton.setDisable(true);
}
// Update merge button
mergeButton.setMnemonicParsing(false);
if (this.localListView.getSelectionModel().getSelectedIndices().size() == 1) {
this.mergeButton.setDisable(false);
this.swapMergeBranchesButton.setDisable(false);
String selectedBranchName = this.localListView.getSelectionModel().getSelectedItem().getBranchName();
this.mergeButton.setText(String.format("Merge %s into %s", selectedBranchName, currentBranchName));
} else {
this.mergeButton.setText(String.format("Merge selected branch into %s", currentBranchName));
this.mergeButton.setDisable(true);
this.swapMergeBranchesButton.setDisable(true);
}
}
/**
* Tracks the selected branch (in the remoteListView) locally.
*
* @throws GitAPIException
* @throws IOException
*/
public void trackSelectedBranchLocally() throws GitAPIException, IOException {
logger.info("Track remote branch locally button clicked");
RemoteBranchHelper selectedRemoteBranch = this.remoteListView.getSelectionModel().getSelectedItem();
try {
if (selectedRemoteBranch != null) {
LocalBranchHelper tracker = this.branchModel.trackRemoteBranch(selectedRemoteBranch);
this.localListView.getItems().add(tracker);
CommitTreeController.setBranchHeads(this.remoteCommitTreeModel, this.repoHelper);
CommitTreeController.setBranchHeads(this.localCommitTreeModel, this.repoHelper);
}
} catch (RefAlreadyExistsException e) {
logger.warn("Branch already exists locally warning");
this.showRefAlreadyExistsNotification();
}
}
/**
* Deletes the selected branches (in the localListView) through git.
*/
public void deleteSelectedLocalBranches() throws IOException {
logger.info("Delete branches button clicked");
for (LocalBranchHelper selectedBranch : this.localListView.getSelectionModel().getSelectedItems()) {
try {
if (selectedBranch != null) {
// Local delete:
this.branchModel.deleteLocalBranch(selectedBranch);
this.localListView.getItems().remove(selectedBranch);
// Reset the branch heads
CommitTreeController.setBranchHeads(this.localCommitTreeModel, this.repoHelper);
CommitTreeController.setBranchHeads(this.remoteCommitTreeModel, this.repoHelper);
}
} catch (NotMergedException e) {
logger.warn("Can't delete branch because not merged warning");
this.showNotMergedNotification(selectedBranch);
} catch (CannotDeleteCurrentBranchException e) {
logger.warn("Can't delete current branch warning");
this.showCannotDeleteBranchNotification(selectedBranch);
} catch (GitAPIException e) {
logger.warn("Git error");
this.showGenericGitErrorNotificationWithBranch(selectedBranch);
}
}
// TODO: add optional delete from remote, too.
}
/**
* Creates a new local branch using git.
*
* @param branchName the name of the new branch.
* @return the new local branch's LocalBranchHelper.
* @throws GitAPIException
* @throws IOException
*/
private LocalBranchHelper createNewLocalBranch(String branchName) throws GitAPIException, IOException {
return this.branchModel.createNewLocalBranch(branchName);
}
/**
* Deletes a given local branch through git, forcefully.
*/
private void forceDeleteLocalBranch(LocalBranchHelper branchToDelete) {
logger.info("Deleting local branch");
try {
if (branchToDelete != null) {
// Local delete:
this.branchModel.forceDeleteLocalBranch(branchToDelete);
// Update local list view
this.localListView.getItems().remove(branchToDelete);
// Reset the branch heads
CommitTreeController.setBranchHeads(this.localCommitTreeModel, this.repoHelper);
CommitTreeController.setBranchHeads(this.remoteCommitTreeModel, this.repoHelper);
}
} catch (CannotDeleteCurrentBranchException e) {
logger.warn("Can't delete current branch warning");
this.showCannotDeleteBranchNotification(branchToDelete);
} catch (GitAPIException e) {
logger.warn("Git error");
this.showGenericGitErrorNotificationWithBranch(branchToDelete);
e.printStackTrace();
}
}
/**
* Performs a git merge between the currently checked out branch and
* the selected local branch.
*
* @throws IOException
* @throws GitAPIException
*/
public void mergeSelectedBranchWithCurrent() throws IOException, GitAPIException {
logger.info("Merging selected branch with current");
// Get the branch to merge with
LocalBranchHelper selectedBranch = this.localListView.getSelectionModel().getSelectedItem();
// Get the merge result from the branch merge
MergeResult mergeResult= this.branchModel.mergeWithBranch(selectedBranch);
if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING)){
this.showConflictsNotification();
ConflictingFileWatcher.watchConflictingFiles(sessionModel.getCurrentRepoHelper());
} else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
this.showUpToDateNotification();
} else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.FAILED)) {
this.showFailedMergeNotification();
} else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.MERGED)
|| mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.MERGED_NOT_COMMITTED)) {
this.showMergeSuccessNotification();
} else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.FAST_FORWARD)) {
this.showFastForwardMergeNotification();
} else {
System.out.println(mergeResult.getMergeStatus());
// todo: handle all cases (maybe combine some)
}
}
/**
* Swaps the branches to be merged.
*
* For example, this action will change
* `Merge MASTER into DEVELOP` into `Merge DEVELOP into MASTER.`
*
* @throws GitAPIException
* @throws IOException
*/
public void swapMergeBranches() throws GitAPIException, IOException {
LocalBranchHelper selectedBranch = this.localListView.getSelectionModel().getSelectedItem();
LocalBranchHelper checkedOutBranch = (LocalBranchHelper) this.branchModel.getCurrentBranch();
selectedBranch.checkoutBranch();
this.localListView.getSelectionModel().select(checkedOutBranch);
this.updateButtons();
this.showBranchSwapNotification(selectedBranch.getBranchName());
}
/// BEGIN: ERROR NOTIFICATIONS:
private void showBranchSwapNotification(String newlyCheckedOutBranchName) {
logger.info("Checked out a branch notification");
this.notificationPane.setText(String.format("%s is now checked out.", newlyCheckedOutBranchName));
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showFastForwardMergeNotification() {
logger.info("Fast forward merge complete notification");
this.notificationPane.setText("Fast-forward merge completed (HEAD was updated).");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showMergeSuccessNotification() {
logger.info("Merge completed notification");
this.notificationPane.setText("Merge completed.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showFailedMergeNotification() {
logger.warn("Merge failed notification");
this.notificationPane.setText("The merge failed.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showUpToDateNotification() {
logger.warn("No merge necessary notification");
this.notificationPane.setText("No merge necessary. Those two branches are already up-to-date.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showGenericGitErrorNotificationWithBranch(LocalBranchHelper branch) {
logger.warn("Git error on branch notification");
this.notificationPane.setText(String.format("Sorry, there was a git error on branch %s.", branch.getBranchName()));
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showGenericGitErrorNotification() {
logger.warn("Git error notification");
this.notificationPane.setText("Sorry, there was a git error.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showGenericErrorNotification() {
logger.warn("Generic error notification");
this.notificationPane.setText("Sorry, there was an error.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showNotMergedNotification(LocalBranchHelper nonmergedBranch) {
logger.warn("Not merged notification");
this.notificationPane.setText("That branch has to be merged before you can do that.");
Action forceDeleteAction = new Action("Force delete", e -> {
this.forceDeleteLocalBranch(nonmergedBranch);
this.notificationPane.hide();
});
this.notificationPane.getActions().clear();
this.notificationPane.getActions().setAll(forceDeleteAction);
this.notificationPane.show();
}
private void showCannotDeleteBranchNotification(LocalBranchHelper branch) {
logger.warn("Cannot delete current branch notification");
this.notificationPane.setText(String.format("Sorry, %s can't be deleted right now. " +
"Try checking out a different branch first.", branch.getBranchName()));
// probably because it's checked out
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showRefAlreadyExistsNotification() {
logger.info("Branch already exists notification");
this.notificationPane.setText("Looks like that branch already exists locally!");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showInvalidBranchNameNotification() {
logger.warn("Invalid branch name notification");
this.notificationPane.setText("That branch name is invalid.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showConflictsNotification() {
logger.info("Merge conflicts notification");
this.notificationPane.setText("That merge resulted in conflicts. Check the working tree to resolve them.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showNoCommitsYetNotification() {
logger.warn("No commits yet notification");
this.notificationPane.setText("You cannot make a branch since your repo has no commits yet. Make a commit first!");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
/// END: ERROR NOTIFICATIONS ^^^
}
|
package eu.euporias.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
|
package greed.model;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Greed is good! Cheers!
*/
public class ProblemDescription {
private String intro;
private String[] notes;
private String[] constraints;
private String mod;
private String extractMod(String intro)
{
/* d, modulo 1,000,000,007.</ */
String pattern = "mod(ulo)? (\\d[\\d,\\.]*\\d)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(intro);
String res = null;
// The modulo tends to be at the end of the statement. If there were
// multiple modulo 1,XXX,XXX,XXX statements, it is better to get the last.
while (m.find( )) {
try {
res = "" +
java.text.NumberFormat.
getNumberInstance(java.util.Locale.US).parse(m.group(2));
} catch (Exception e) {
}
}
return res;
}
public ProblemDescription(String intro, String[] notes, String[] constraints) {
this.intro = intro;
this.notes = notes;
this.constraints = constraints;
mod = extractMod(intro);
}
public String getIntro() {
return intro;
}
public String[] getNotes() {
return notes;
}
public String[] getConstraints() {
return constraints;
}
public String getMod() {
return mod;
}
}
|
package ibm.coghack;
/**
* Responsible for determining characteristics about a sentence from its text content.
*/
public class SentenceClassifier {
/**
* String prefixes used to determine if a sentence is a question.
*/
private static String[] questionPrefixes = {"tell me about", "what", "how", "do you", "can you", "ok", "have"};
/**
* Determines if a sentence is a question.
* @param sentence
* @return <code>true</code> if the sentence is deemed a question <code>false</code> otherwise
*/
public static boolean isAQuestion(String sentence){
String lowerCaseSentence = sentence.toLowerCase().trim();
for(String questionPrefix : questionPrefixes){
if(lowerCaseSentence.toLowerCase().startsWith(questionPrefix)){
return true;
}
}
return false;
}
}
|
package info.xonix;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Xspf2PodcastServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(Xspf2PodcastServlet.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String xspfUrl = req.getParameter("xspf");
String imgUrl = req.getParameter("img");
log.info("Received xspf URL: " + xspfUrl);
resp.setCharacterEncoding("UTF-8");
try (InputStream xslInputStream = getClass().getClassLoader().getResourceAsStream("xspf2rss.xsl");
PrintWriter writer = resp.getWriter()) {
if (xspfUrl == null) {
resp.setContentType("text/html");
resp.setStatus(400);
writer.println("Please provide xspf URL!");
writer.flush();
return;
}
resp.setContentType("application/rss+xml");
String xspfText = Util.receiveUrlText(xspfUrl);
if (imgUrl != null && !"".equals(imgUrl = imgUrl.trim())) {
// inject imgUrl into xspf for xsl
xspfText = xspfText.replace("<trackList>", "<img>" + imgUrl + "</img><trackList>");
}
try {
writer.print(Util.xsltTransform(xspfText, xslInputStream));
} catch (Exception ex) {
log.log(Level.SEVERE, "Unable to do XSLT for: " + xspfText, ex);
}
writer.flush();
}
}
}
|
package io.github.classgraph;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.github.classgraph.Scanner.ClassfileScanWorkUnit;
import nonapi.io.github.classgraph.ScanSpec;
import nonapi.io.github.classgraph.concurrency.WorkQueue;
import nonapi.io.github.classgraph.types.ParseException;
import nonapi.io.github.classgraph.utils.InputStreamOrByteBufferAdapter;
import nonapi.io.github.classgraph.utils.JarUtils;
import nonapi.io.github.classgraph.utils.Join;
import nonapi.io.github.classgraph.utils.LogNode;
/**
* A classfile binary format parser. Implements its own buffering to avoid the overhead of using DataInputStream.
* This class should only be used by a single thread at a time, but can be re-used to scan multiple classfiles in
* sequence, to avoid re-allocating buffer memory.
*/
class Classfile {
/** The InputStream or ByteBuffer for the current classfile. */
private InputStreamOrByteBufferAdapter inputStreamOrByteBuffer;
/** The classpath element that contains this classfile. */
private final ClasspathElement classpathElement;
/** The classpath order. */
private final List<ClasspathElement> classpathOrder;
/** The relative path to the classfile (should correspond to className). */
private final String relativePath;
/** The classfile resource. */
private final Resource classfileResource;
/** The name of the class. */
private String className;
/** Whether this is an external class. */
private final boolean isExternalClass;
/** The class modifiers. */
private int classModifiers;
/** Whether this class is an interface. */
private boolean isInterface;
/** Whether this class is an annotation. */
private boolean isAnnotation;
/** The superclass name. (can be null if no superclass, or if superclass is blacklisted.) */
private String superclassName;
/** The implemented interfaces. */
private List<String> implementedInterfaces;
/** The class annotations. */
private AnnotationInfoList classAnnotations;
/** The fully qualified name of the defining method. */
private String fullyQualifiedDefiningMethodName;
/** Class containment entries. */
private List<SimpleEntry<String, String>> classContainmentEntries;
/** Annotation default parameter values. */
private AnnotationParameterValueList annotationParamDefaultValues;
/** Referenced class names. */
private Set<String> refdClassNames;
/** The field info list. */
private FieldInfoList fieldInfoList;
/** The method info list. */
private MethodInfoList methodInfoList;
/** The type signature. */
private String typeSignature;
/**
* Class names already scheduled for scanning. If a class name is not in this list, the class is external, and
* has not yet been scheduled for scanning.
*/
private final Set<String> classNamesScheduledForScanning;
/** Any additional work units scheduled for scanning. */
private List<ClassfileScanWorkUnit> additionalWorkUnits;
/** The scan spec. */
private final ScanSpec scanSpec;
/** The log. */
private final LogNode log;
/** The number of constant pool entries plus one. */
private int cpCount;
/** The byte offset for the beginning of each entry in the constant pool. */
private int[] entryOffset;
/** The tag (type) for each entry in the constant pool. */
private int[] entryTag;
/** The indirection index for String/Class entries in the constant pool. */
private int[] indirectStringRefs;
/** An empty array for the case where there are no annotations. */
private static final AnnotationInfo[] NO_ANNOTATIONS = new AnnotationInfo[0];
/** Thrown when a classfile's contents are not in the correct format. */
class ClassfileFormatException extends IOException {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*
* @param message
* the message
*/
public ClassfileFormatException(final String message) {
super(message);
}
/**
* Constructor.
*
* @param message
* the message
* @param cause
* the cause
*/
public ClassfileFormatException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Speed up exception (stack trace is not needed for this exception).
*
* @return this
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
/** Thrown when a classfile needs to be skipped. */
class SkipClassException extends IOException {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*
* @param message
* the message
*/
public SkipClassException(final String message) {
super(message);
}
/**
* Speed up exception (stack trace is not needed for this exception).
*
* @return this
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
/**
* Extend scanning to a superclass, interface or annotation.
*
* @param className
* the class name
* @param relationship
* the relationship type
*/
private void scheduleScanningIfExternalClass(final String className, final String relationship) {
// Don't scan Object
if (className != null && !className.equals("java.lang.Object")
// Only schedule each external class once for scanning, across all threads
&& classNamesScheduledForScanning.add(className)) {
// Search for the named class' classfile among classpath elements, in classpath order (this is O(N)
// for each class, but there shouldn't be too many cases of extending scanning upwards)
final String classfilePath = JarUtils.classNameToClassfilePath(className);
// First check current classpath element, to avoid iterating through other classpath elements
Resource classResource = classpathElement.getResource(classfilePath);
ClasspathElement foundInClasspathElt = null;
if (classResource != null) {
// Found the classfile in the current classpath element
foundInClasspathElt = classpathElement;
} else {
// Didn't find the classfile in the current classpath element -- iterate through other elements
for (final ClasspathElement classpathOrderElt : classpathOrder) {
if (classpathOrderElt != classpathElement) {
classResource = classpathOrderElt.getResource(classfilePath);
if (classResource != null) {
foundInClasspathElt = classpathOrderElt;
break;
}
}
}
}
if (classResource != null) {
// Found class resource
if (log != null) {
log.log("Scheduling external class for scanning: " + relationship + " " + className
+ (foundInClasspathElt == classpathElement ? ""
: " -- found in classpath element " + foundInClasspathElt));
}
if (additionalWorkUnits == null) {
additionalWorkUnits = new ArrayList<>();
}
// Schedule class resource for scanning
additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource,
/* isExternalClass = */ true));
} else {
if (log != null) {
log.log("External " + relationship + " " + className + " was not found in "
+ "non-blacklisted packages -- cannot extend scanning to this class");
}
}
}
}
/**
* Check if scanning needs to be extended upwards to an external superclass, interface or annotation.
*/
private void extendScanningUpwards() {
// Check superclass
if (superclassName != null) {
scheduleScanningIfExternalClass(superclassName, "superclass");
}
// Check implemented interfaces
if (implementedInterfaces != null) {
for (final String interfaceName : implementedInterfaces) {
scheduleScanningIfExternalClass(interfaceName, "interface");
}
}
// Check class annotations
if (classAnnotations != null) {
for (final AnnotationInfo annotationInfo : classAnnotations) {
scheduleScanningIfExternalClass(annotationInfo.getName(), "class annotation");
}
}
// Check method annotations and method parameter annotations
if (methodInfoList != null) {
for (final MethodInfo methodInfo : methodInfoList) {
if (methodInfo.annotationInfo != null) {
for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) {
scheduleScanningIfExternalClass(methodAnnotationInfo.getName(), "method annotation");
}
if (methodInfo.parameterAnnotationInfo != null
&& methodInfo.parameterAnnotationInfo.length > 0) {
for (final AnnotationInfo[] paramAnns : methodInfo.parameterAnnotationInfo) {
if (paramAnns != null && paramAnns.length > 0) {
for (final AnnotationInfo paramAnn : paramAnns) {
scheduleScanningIfExternalClass(paramAnn.getName(),
"method parameter annotation");
}
}
}
}
}
}
}
// Check field annotations
if (fieldInfoList != null) {
for (final FieldInfo fieldInfo : fieldInfoList) {
if (fieldInfo.annotationInfo != null) {
for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) {
scheduleScanningIfExternalClass(fieldAnnotationInfo.getName(), "field annotation");
}
}
}
}
}
/**
* Link classes. Not threadsafe, should be run in a single-threaded context.
*
* @param classNameToClassInfo
* map from class name to class info
* @param packageNameToPackageInfo
* map from package name to package info
* @param moduleNameToModuleInfo
* map from module name to module info
*/
void link(final Map<String, ClassInfo> classNameToClassInfo,
final Map<String, PackageInfo> packageNameToPackageInfo,
final Map<String, ModuleInfo> moduleNameToModuleInfo) {
boolean isModuleDescriptor = false;
boolean isPackageDescriptor = false;
ClassInfo classInfo = null;
if (className.equals("module-info")) {
isModuleDescriptor = true;
} else if (className.equals("package-info") || className.endsWith(".package-info")) {
isPackageDescriptor = true;
} else {
// Handle regular classfile
classInfo = ClassInfo.addScannedClass(className, classModifiers, isExternalClass, classNameToClassInfo,
classpathElement, classfileResource);
classInfo.setModifiers(classModifiers);
classInfo.setIsInterface(isInterface);
classInfo.setIsAnnotation(isAnnotation);
if (superclassName != null) {
classInfo.addSuperclass(superclassName, classNameToClassInfo);
}
if (implementedInterfaces != null) {
for (final String interfaceName : implementedInterfaces) {
classInfo.addImplementedInterface(interfaceName, classNameToClassInfo);
}
}
if (classAnnotations != null) {
for (final AnnotationInfo classAnnotation : classAnnotations) {
classInfo.addClassAnnotation(classAnnotation, classNameToClassInfo);
}
}
if (classContainmentEntries != null) {
ClassInfo.addClassContainment(classContainmentEntries, classNameToClassInfo);
}
if (annotationParamDefaultValues != null) {
classInfo.addAnnotationParamDefaultValues(annotationParamDefaultValues);
}
if (fullyQualifiedDefiningMethodName != null) {
classInfo.addFullyQualifiedDefiningMethodName(fullyQualifiedDefiningMethodName);
}
if (fieldInfoList != null) {
classInfo.addFieldInfo(fieldInfoList, classNameToClassInfo);
}
if (methodInfoList != null) {
classInfo.addMethodInfo(methodInfoList, classNameToClassInfo);
}
if (typeSignature != null) {
classInfo.setTypeSignature(typeSignature);
}
if (refdClassNames != null) {
classInfo.addReferencedClassNames(refdClassNames);
}
}
// Get or create PackageInfo, if this is not a module descriptor (the module descriptor's package is "")
PackageInfo packageInfo = null;
if (!isModuleDescriptor) {
// Get package for this class or package descriptor
packageInfo = PackageInfo.getOrCreatePackage(PackageInfo.getParentPackageName(className),
packageNameToPackageInfo);
if (isPackageDescriptor) {
// Add any class annotations on the package-info.class file to the ModuleInfo
packageInfo.addAnnotations(classAnnotations);
} else if (classInfo != null) {
// Add ClassInfo to PackageInfo, and vice versa
packageInfo.addClassInfo(classInfo);
classInfo.packageInfo = packageInfo;
}
}
// Get or create ModuleInfo, if there is a module name
final String moduleName = classpathElement.getModuleName();
if (moduleName != null) {
// Get or create a ModuleInfo object for this module
ModuleInfo moduleInfo = moduleNameToModuleInfo.get(moduleName);
if (moduleInfo == null) {
moduleNameToModuleInfo.put(moduleName,
moduleInfo = new ModuleInfo(classfileResource.getModuleRef(), classpathElement));
}
if (isModuleDescriptor) {
// Add any class annotations on the module-info.class file to the ModuleInfo
moduleInfo.addAnnotations(classAnnotations);
}
if (classInfo != null) {
// Add ClassInfo to ModuleInfo, and vice versa
moduleInfo.addClassInfo(classInfo);
classInfo.moduleInfo = moduleInfo;
}
if (packageInfo != null) {
// Add PackageInfo to ModuleInfo
moduleInfo.addPackageInfo(packageInfo);
}
}
}
/**
* Get the byte offset within the buffer of a string from the constant pool, or 0 for a null string.
*
* @param cpIdx
* the constant pool index
* @param subFieldIdx
* should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for
* CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1.
* @return the constant pool string offset
* @throws ClassfileFormatException
* If a problem is detected
*/
private int getConstantPoolStringOffset(final int cpIdx, final int subFieldIdx)
throws ClassfileFormatException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
final int t = entryTag[cpIdx];
if ((t != 12 && subFieldIdx != 0) || (t == 12 && subFieldIdx != 0 && subFieldIdx != 1)) {
throw new ClassfileFormatException(
"Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
int cpIdxToUse;
if (t == 0) {
// Assume this means null
return 0;
} else if (t == 1) {
// CONSTANT_Utf8
cpIdxToUse = cpIdx;
} else if (t == 7 || t == 8 || t == 19) {
// t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String;
// t == 19 => CONSTANT_Method_Info
final int indirIdx = indirectStringRefs[cpIdx];
if (indirIdx == -1) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
if (indirIdx == 0) {
// I assume this represents a null string, since the zeroeth entry is unused
return 0;
}
cpIdxToUse = indirIdx;
} else if (t == 12) {
// CONSTANT_NameAndType_info
final int compoundIndirIdx = indirectStringRefs[cpIdx];
if (compoundIndirIdx == -1) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
final int indirIdx = (subFieldIdx == 0 ? (compoundIndirIdx >> 16) : compoundIndirIdx) & 0xffff;
if (indirIdx == 0) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
cpIdxToUse = indirIdx;
} else {
throw new ClassfileFormatException("Wrong tag number " + t + " at constant pool index " + cpIdx + ", "
+ "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
}
if (cpIdxToUse < 1 || cpIdxToUse >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return entryOffset[cpIdxToUse];
}
/**
* Get a string from the constant pool, optionally replacing '/' with '.'.
*
* @param cpIdx
* the constant pool index
* @param replaceSlashWithDot
* if true, replace slash with dot in the result.
* @param stripLSemicolon
* if true, strip 'L' from the beginning and ';' from the end before returning (for class reference
* constants)
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx, final boolean replaceSlashWithDot,
final boolean stripLSemicolon) throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
return constantPoolStringOffset == 0 ? null
: inputStreamOrByteBuffer.readString(constantPoolStringOffset, replaceSlashWithDot,
stripLSemicolon);
}
/**
* Get a string from the constant pool.
*
* @param cpIdx
* the constant pool index
* @param subFieldIdx
* should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for
* CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1.
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx, final int subFieldIdx)
throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx);
return constantPoolStringOffset == 0 ? null
: inputStreamOrByteBuffer.readString(constantPoolStringOffset, /* replaceSlashWithDot = */ false,
/* stripLSemicolon = */ false);
}
/**
* Get a string from the constant pool.
*
* @param cpIdx
* the constant pool index
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* subFieldIdx = */ 0);
}
/**
* Get the first UTF8 byte of a string in the constant pool, or '\0' if the string is null or empty.
*
* @param cpIdx
* the constant pool index
* @return the first byte of the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private byte getConstantPoolStringFirstByte(final int cpIdx) throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
if (constantPoolStringOffset == 0) {
return '\0';
}
final int utfLen = inputStreamOrByteBuffer.readUnsignedShort(constantPoolStringOffset);
if (utfLen == 0) {
return '\0';
}
return inputStreamOrByteBuffer.buf[constantPoolStringOffset + 2];
}
/**
* Get a string from the constant pool, and interpret it as a class name by replacing '/' with '.'.
*
* @param cpIdx
* the constant pool index
* @return the constant pool class name
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolClassName(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false);
}
/**
* Get a string from the constant pool representing an internal string descriptor for a class name
* ("Lcom/xyz/MyClass;"), and interpret it as a class name by replacing '/' with '.', and removing the leading
* "L" and the trailing ";".
*
* @param cpIdx
* the constant pool index
* @return the constant pool class descriptor
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolClassDescriptor(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ true);
}
/**
* Compare a string in the constant pool with a given constant, without constructing the String object.
*
* @param cpIdx
* the constant pool index
* @param otherString
* the other string
* @return true, if successful
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private boolean constantPoolStringEquals(final int cpIdx, final String otherString)
throws ClassfileFormatException, IOException {
final int strOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
if (strOffset == 0) {
return otherString == null;
} else if (otherString == null) {
return false;
}
final int strLen = inputStreamOrByteBuffer.readUnsignedShort(strOffset);
final int otherLen = otherString.length();
if (strLen != otherLen) {
return false;
}
final int strStart = strOffset + 2;
for (int i = 0; i < strLen; i++) {
if ((char) (inputStreamOrByteBuffer.buf[strStart + i] & 0xff) != otherString.charAt(i)) {
return false;
}
}
return true;
}
/**
* Read an unsigned short from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the unsigned short
* @throws IOException
* If an I/O exception occurred.
*/
private int cpReadUnsignedShort(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return inputStreamOrByteBuffer.readUnsignedShort(entryOffset[cpIdx]);
}
/**
* Read an int from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the int
* @throws IOException
* If an I/O exception occurred.
*/
private int cpReadInt(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return inputStreamOrByteBuffer.readInt(entryOffset[cpIdx]);
}
/**
* Read a long from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the long
* @throws IOException
* If an I/O exception occurred.
*/
private long cpReadLong(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return inputStreamOrByteBuffer.readLong(entryOffset[cpIdx]);
}
/**
* Get a field constant from the constant pool.
*
* @param tag
* the tag
* @param fieldTypeDescriptorFirstChar
* the first char of the field type descriptor
* @param cpIdx
* the constant pool index
* @return the field constant pool value
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private Object getFieldConstantPoolValue(final int tag, final char fieldTypeDescriptorFirstChar,
final int cpIdx) throws ClassfileFormatException, IOException {
switch (tag) {
case 1: // Modified UTF8
case 7: // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers
case 8: // String
// Forward or backward indirect reference to a modified UTF8 entry
return getConstantPoolString(cpIdx);
case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER
final int intVal = cpReadInt(cpIdx);
switch (fieldTypeDescriptorFirstChar) {
case 'I':
return intVal;
case 'S':
return (short) intVal;
case 'C':
return (char) intVal;
case 'B':
return (byte) intVal;
case 'Z':
return intVal != 0;
default:
// Fall through
}
throw new ClassfileFormatException("Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar
+ ", " + "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
case 4: // float
return Float.intBitsToFloat(cpReadInt(cpIdx));
case 5: // long
return cpReadLong(cpIdx);
case 6: // double
return Double.longBitsToDouble(cpReadLong(cpIdx));
default:
// ClassGraph doesn't expect other types
// (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled)
throw new ClassfileFormatException("Unknown constant pool tag " + tag + ", "
+ "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
}
}
/**
* Read annotation entry from classfile.
*
* @return the annotation, as an {@link AnnotationInfo} object.
* @throws IOException
* If an IO exception occurs.
*/
private AnnotationInfo readAnnotation() throws IOException {
// Lcom/xyz/Annotation; -> Lcom.xyz.Annotation;
final String annotationClassName = getConstantPoolClassDescriptor(
inputStreamOrByteBuffer.readUnsignedShort());
final int numElementValuePairs = inputStreamOrByteBuffer.readUnsignedShort();
AnnotationParameterValueList paramVals = null;
if (numElementValuePairs > 0) {
paramVals = new AnnotationParameterValueList(numElementValuePairs);
for (int i = 0; i < numElementValuePairs; i++) {
final String paramName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
final Object paramValue = readAnnotationElementValue();
paramVals.add(new AnnotationParameterValue(paramName, paramValue));
}
}
return new AnnotationInfo(annotationClassName, paramVals);
}
/**
* Read annotation element value from classfile.
*
* @return the annotation element value
* @throws IOException
* If an IO exception occurs.
*/
private Object readAnnotationElementValue() throws IOException {
final int tag = (char) inputStreamOrByteBuffer.readUnsignedByte();
switch (tag) {
case 'B':
return (byte) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'C':
return (char) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'D':
return Double.longBitsToDouble(cpReadLong(inputStreamOrByteBuffer.readUnsignedShort()));
case 'F':
return Float.intBitsToFloat(cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()));
case 'I':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'J':
return cpReadLong(inputStreamOrByteBuffer.readUnsignedShort());
case 'S':
return (short) cpReadUnsignedShort(inputStreamOrByteBuffer.readUnsignedShort());
case 'Z':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()) != 0;
case 's':
return getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
case 'e': {
// Return type is AnnotationEnumVal.
final String annotationClassName = getConstantPoolClassDescriptor(
inputStreamOrByteBuffer.readUnsignedShort());
final String annotationConstName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationEnumValue(annotationClassName, annotationConstName);
}
case 'c':
// Return type is AnnotationClassRef (for class references in annotations)
final String classRefTypeDescriptor = getConstantPoolString(
inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationClassRef(classRefTypeDescriptor);
case '@':
// Complex (nested) annotation. Return type is AnnotationInfo.
return readAnnotation();
case '[':
// Return type is Object[] (of nested annotation element values)
final int count = inputStreamOrByteBuffer.readUnsignedShort();
final Object[] arr = new Object[count];
for (int i = 0; i < count; ++i) {
// Nested annotation element value
arr[i] = readAnnotationElementValue();
}
return arr;
default:
throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '"
+ ((char) tag) + "': element size unknown, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
}
/**
* Read constant pool entries.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void readConstantPoolEntries() throws IOException {
// Only record class dependency info if inter-class dependencies are enabled
List<Integer> classNameCpIdxs = null;
List<Integer> typeSignatureIdxs = null;
if (scanSpec.enableInterClassDependencies) {
classNameCpIdxs = new ArrayList<Integer>();
typeSignatureIdxs = new ArrayList<Integer>();
}
// Read size of constant pool
cpCount = inputStreamOrByteBuffer.readUnsignedShort();
// Allocate storage for constant pool
entryOffset = new int[cpCount];
entryTag = new int[cpCount];
indirectStringRefs = new int[cpCount];
Arrays.fill(indirectStringRefs, 0, cpCount, -1);
// Read constant pool entries
for (int i = 1, skipSlot = 0; i < cpCount; i++) {
if (skipSlot == 1) {
// Skip a slot (keeps Scrutinizer happy -- it doesn't like i++ in case 6)
skipSlot = 0;
continue;
}
entryTag[i] = inputStreamOrByteBuffer.readUnsignedByte();
entryOffset[i] = inputStreamOrByteBuffer.curr;
switch (entryTag[i]) {
case 0: // Impossible, probably buffer underflow
throw new ClassfileFormatException("Unknown constant pool tag 0 in classfile " + relativePath
+ " (possible buffer underflow issue). Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
case 1: // Modified UTF8
final int strLen = inputStreamOrByteBuffer.readUnsignedShort();
inputStreamOrByteBuffer.skip(strLen);
break;
case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER
case 4: // float
inputStreamOrByteBuffer.skip(4);
break;
case 5: // long
case 6: // double
inputStreamOrByteBuffer.skip(8);
skipSlot = 1; // double slot
break;
case 7: // Class reference (format is e.g. "java/lang/String")
// Forward or backward indirect reference to a modified UTF8 entry
indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
if (scanSpec.enableInterClassDependencies) {
// If this is a class ref, and inter-class dependencies are enabled, record the dependency
classNameCpIdxs.add(indirectStringRefs[i]);
}
break;
case 8: // String
// Forward or backward indirect reference to a modified UTF8 entry
indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
break;
case 9: // field ref
// Refers to a class ref (case 7) and then a name and type (case 12)
inputStreamOrByteBuffer.skip(4);
break;
case 10: // method ref
// Refers to a class ref (case 7) and then a name and type (case 12)
inputStreamOrByteBuffer.skip(4);
break;
case 11: // interface method ref
// Refers to a class ref (case 7) and then a name and type (case 12)
inputStreamOrByteBuffer.skip(4);
break;
case 12: // name and type
final int nameRef = inputStreamOrByteBuffer.readUnsignedShort();
final int typeRef = inputStreamOrByteBuffer.readUnsignedShort();
if (scanSpec.enableInterClassDependencies) {
typeSignatureIdxs.add(typeRef);
}
indirectStringRefs[i] = (nameRef << 16) | typeRef;
break;
case 15: // method handle
inputStreamOrByteBuffer.skip(3);
break;
case 16: // method type
inputStreamOrByteBuffer.skip(2);
break;
case 18: // invoke dynamic
inputStreamOrByteBuffer.skip(4);
break;
case 19: // module (for module-info.class in JDK9+)
// see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4
indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
break;
case 20: // package (for module-info.class in JDK9+)
// see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4
inputStreamOrByteBuffer.skip(2);
break;
default:
throw new ClassfileFormatException("Unknown constant pool tag " + entryTag[i]
+ " (element size unknown, cannot continue reading class). Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
}
}
// Find classes referenced in the constant pool (note that there are some class refs that will not be
// found this way, e.g. enum classes and class refs in annotation parameter values, since they are
// referenced as strings (tag 1) rather than classes (tag 7) or type signatures (part of tag 12)).
if (scanSpec.enableInterClassDependencies) {
refdClassNames = new HashSet<>();
// Get class names from direct class references in constant pool
for (final int cpIdx : classNameCpIdxs) {
final String refdClassName = getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true,
/* stripLSemicolon = */ false);
if (refdClassName != null) {
if (refdClassName.startsWith("[")) {
// Parse array type signature, e.g. "[Ljava.lang.String;" -- uses '.' rather than '/'
try {
final TypeSignature typeSig = TypeSignature.parse(refdClassName.replace('.', '/'),
/* definingClass = */ null);
typeSig.findReferencedClassNames(refdClassNames);
} catch (final ParseException e) {
// Should not happen
throw new ClassfileFormatException("Could not parse class name: " + refdClassName, e);
}
} else {
refdClassNames.add(refdClassName);
}
}
}
// Get class names from type signatures in "name and type" entries in constant pool
for (final int cpIdx : typeSignatureIdxs) {
final String typeSigStr = getConstantPoolString(cpIdx);
if (typeSigStr != null) {
try {
if (typeSigStr.indexOf('(') >= 0 || "<init>".equals(typeSigStr)) {
// Parse the type signature
final MethodTypeSignature typeSig = MethodTypeSignature.parse(typeSigStr,
/* definingClassName = */ null);
// Extract class names from type signature
typeSig.findReferencedClassNames(refdClassNames);
} else {
// Parse the type signature
final TypeSignature typeSig = TypeSignature.parse(typeSigStr,
/* definingClassName = */ null);
// Extract class names from type signature
typeSig.findReferencedClassNames(refdClassNames);
}
} catch (final ParseException e) {
throw new ClassfileFormatException("Could not parse type signature: " + typeSigStr, e);
}
}
}
}
}
/**
* Read basic class information.
*
* @throws IOException
* if an I/O exception occurs.
* @throws ClassfileFormatException
* if the classfile is incorrectly formatted.
* @throws SkipClassException
* if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is
* false)
*/
private void readBasicClassInfo() throws IOException, ClassfileFormatException, SkipClassException {
// Modifier flags
classModifiers = inputStreamOrByteBuffer.readUnsignedShort();
isInterface = (classModifiers & 0x0200) != 0;
isAnnotation = (classModifiers & 0x2000) != 0;
// The fully-qualified class name of this class, with slashes replaced with dots
final String classNamePath = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
if (classNamePath == null) {
throw new ClassfileFormatException("Class name is null");
}
className = classNamePath.replace('/', '.');
if ("java.lang.Object".equals(className)) {
// Don't process java.lang.Object (it has a null superclass), though you can still search for classes
// that are subclasses of java.lang.Object (as an external class).
throw new SkipClassException("No need to scan java.lang.Object");
}
// Check class visibility modifiers
final boolean isModule = (classModifiers & 0x8000) != 0; // Equivalently filename is "module-info.class"
final boolean isPackage = relativePath.regionMatches(relativePath.lastIndexOf('/') + 1,
"package-info.class", 0, 18);
if (!scanSpec.ignoreClassVisibility && !Modifier.isPublic(classModifiers) && !isModule && !isPackage) {
throw new SkipClassException("Class is not public, and ignoreClassVisibility() was not called");
}
// Make sure classname matches relative path
if (!relativePath.endsWith(".class")) {
// Should not happen
throw new SkipClassException("Classfile filename " + relativePath + " does not end in \".class\"");
}
final int len = classNamePath.length();
if (relativePath.length() != len + 6 || !classNamePath.regionMatches(0, relativePath, 0, len)) {
throw new SkipClassException(
"Relative path " + relativePath + " does not match class name " + className);
}
// Superclass name, with slashes replaced with dots
final int superclassNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
if (superclassNameCpIdx > 0) {
superclassName = getConstantPoolClassName(superclassNameCpIdx);
}
}
/**
* Read the class' interfaces.
*
* @throws IOException
* if an I/O exception occurs.
*/
private void readInterfaces() throws IOException {
// Interfaces
final int interfaceCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < interfaceCount; i++) {
final String interfaceName = getConstantPoolClassName(inputStreamOrByteBuffer.readUnsignedShort());
if (implementedInterfaces == null) {
implementedInterfaces = new ArrayList<>();
}
implementedInterfaces.add(interfaceName);
}
}
/**
* Read the class' fields.
*
* @throws IOException
* if an I/O exception occurs.
* @throws ClassfileFormatException
* if the classfile is incorrectly formatted.
*/
private void readFields() throws IOException, ClassfileFormatException {
// Fields
final int fieldCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < fieldCount; i++) {
// Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.5
final int fieldModifierFlags = inputStreamOrByteBuffer.readUnsignedShort();
final boolean isPublicField = ((fieldModifierFlags & 0x0001) == 0x0001);
final boolean isStaticFinalField = ((fieldModifierFlags & 0x0018) == 0x0018);
final boolean fieldIsVisible = isPublicField || scanSpec.ignoreFieldVisibility;
final boolean getStaticFinalFieldConstValue = scanSpec.enableStaticFinalFieldConstantInitializerValues
&& isStaticFinalField && fieldIsVisible;
if (!fieldIsVisible || (!scanSpec.enableFieldInfo && !getStaticFinalFieldConstValue)) {
// Skip field
inputStreamOrByteBuffer.readUnsignedShort(); // fieldNameCpIdx
inputStreamOrByteBuffer.readUnsignedShort(); // fieldTypeDescriptorCpIdx
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int j = 0; j < attributesCount; j++) {
inputStreamOrByteBuffer.readUnsignedShort(); // attributeNameCpIdx
final int attributeLength = inputStreamOrByteBuffer.readInt();
inputStreamOrByteBuffer.skip(attributeLength);
}
} else {
final int fieldNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final String fieldName = getConstantPoolString(fieldNameCpIdx);
final int fieldTypeDescriptorCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final char fieldTypeDescriptorFirstChar = (char) getConstantPoolStringFirstByte(
fieldTypeDescriptorCpIdx);
String fieldTypeDescriptor;
String fieldTypeSignature = null;
fieldTypeDescriptor = getConstantPoolString(fieldTypeDescriptorCpIdx);
Object fieldConstValue = null;
AnnotationInfoList fieldAnnotationInfo = null;
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int j = 0; j < attributesCount; j++) {
final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int attributeLength = inputStreamOrByteBuffer.readInt();
// See if field name matches one of the requested names for this class, and if it does,
// check if it is initialized with a constant value
if ((getStaticFinalFieldConstValue)
&& constantPoolStringEquals(attributeNameCpIdx, "ConstantValue")) {
// http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2
final int cpIdx = inputStreamOrByteBuffer.readUnsignedShort();
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx
+ ", should be in range [1, " + (cpCount - 1)
+ "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
fieldConstValue = getFieldConstantPoolValue(entryTag[cpIdx], fieldTypeDescriptorFirstChar,
cpIdx);
} else if (fieldIsVisible && constantPoolStringEquals(attributeNameCpIdx, "Signature")) {
fieldTypeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
} else if (scanSpec.enableAnnotationInfo
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) {
// Read annotation names
final int fieldAnnotationCount = inputStreamOrByteBuffer.readUnsignedShort();
if (fieldAnnotationInfo == null && fieldAnnotationCount > 0) {
fieldAnnotationInfo = new AnnotationInfoList(1);
}
if (fieldAnnotationInfo != null) {
for (int k = 0; k < fieldAnnotationCount; k++) {
final AnnotationInfo fieldAnnotation = readAnnotation();
fieldAnnotationInfo.add(fieldAnnotation);
}
}
} else {
// No match, just skip attribute
inputStreamOrByteBuffer.skip(attributeLength);
}
}
if (scanSpec.enableFieldInfo && fieldIsVisible) {
if (fieldInfoList == null) {
fieldInfoList = new FieldInfoList();
}
fieldInfoList.add(new FieldInfo(className, fieldName, fieldModifierFlags, fieldTypeDescriptor,
fieldTypeSignature, fieldConstValue, fieldAnnotationInfo));
}
}
}
}
/**
* Read the class' methods.
*
* @throws IOException
* if an I/O exception occurs.
* @throws ClassfileFormatException
* if the classfile is incorrectly formatted.
*/
private void readMethods() throws IOException, ClassfileFormatException {
// Methods
final int methodCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < methodCount; i++) {
// Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6
final int methodModifierFlags = inputStreamOrByteBuffer.readUnsignedShort();
final boolean isPublicMethod = ((methodModifierFlags & 0x0001) == 0x0001);
final boolean methodIsVisible = isPublicMethod || scanSpec.ignoreMethodVisibility;
String methodName = null;
String methodTypeDescriptor = null;
String methodTypeSignature = null;
// Always enable MethodInfo for annotations (this is how annotation constants are defined)
final boolean enableMethodInfo = scanSpec.enableMethodInfo || isAnnotation;
if (enableMethodInfo || isAnnotation) { // Annotations store defaults in method_info
final int methodNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
methodName = getConstantPoolString(methodNameCpIdx);
final int methodTypeDescriptorCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
methodTypeDescriptor = getConstantPoolString(methodTypeDescriptorCpIdx);
} else {
inputStreamOrByteBuffer.skip(4); // name_index, descriptor_index
}
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
String[] methodParameterNames = null;
int[] methodParameterModifiers = null;
AnnotationInfo[][] methodParameterAnnotations = null;
AnnotationInfoList methodAnnotationInfo = null;
boolean methodHasBody = false;
if (!methodIsVisible || (!enableMethodInfo && !isAnnotation)) {
// Skip method attributes
for (int j = 0; j < attributesCount; j++) {
inputStreamOrByteBuffer.skip(2); // attribute_name_index
final int attributeLength = inputStreamOrByteBuffer.readInt();
inputStreamOrByteBuffer.skip(attributeLength);
}
} else {
// Look for method annotations
for (int j = 0; j < attributesCount; j++) {
final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int attributeLength = inputStreamOrByteBuffer.readInt();
if (scanSpec.enableAnnotationInfo
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) {
final int methodAnnotationCount = inputStreamOrByteBuffer.readUnsignedShort();
if (methodAnnotationInfo == null && methodAnnotationCount > 0) {
methodAnnotationInfo = new AnnotationInfoList(1);
}
if (methodAnnotationInfo != null) {
for (int k = 0; k < methodAnnotationCount; k++) {
final AnnotationInfo annotationInfo = readAnnotation();
methodAnnotationInfo.add(annotationInfo);
}
}
} else if (scanSpec.enableAnnotationInfo
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleParameterAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleParameterAnnotations")))) {
final int paramCount = inputStreamOrByteBuffer.readUnsignedByte();
methodParameterAnnotations = new AnnotationInfo[paramCount][];
for (int k = 0; k < paramCount; k++) {
final int numAnnotations = inputStreamOrByteBuffer.readUnsignedShort();
methodParameterAnnotations[k] = numAnnotations == 0 ? NO_ANNOTATIONS
: new AnnotationInfo[numAnnotations];
for (int l = 0; l < numAnnotations; l++) {
methodParameterAnnotations[k][l] = readAnnotation();
}
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "MethodParameters")) {
// Read method parameters. For Java, these are only produced in JDK8+, and only if the
// commandline switch `-parameters` is provided at compiletime.
final int paramCount = inputStreamOrByteBuffer.readUnsignedByte();
methodParameterNames = new String[paramCount];
methodParameterModifiers = new int[paramCount];
for (int k = 0; k < paramCount; k++) {
final int cpIdx = inputStreamOrByteBuffer.readUnsignedShort();
// If the constant pool index is zero, then the parameter is unnamed => use null
methodParameterNames[k] = cpIdx == 0 ? null : getConstantPoolString(cpIdx);
methodParameterModifiers[k] = inputStreamOrByteBuffer.readUnsignedShort();
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) {
// Add type params to method type signature
methodTypeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
} else if (constantPoolStringEquals(attributeNameCpIdx, "AnnotationDefault")) {
if (annotationParamDefaultValues == null) {
annotationParamDefaultValues = new AnnotationParameterValueList();
}
this.annotationParamDefaultValues.add(new AnnotationParameterValue(methodName,
// Get annotation parameter default value
readAnnotationElementValue()));
} else if (constantPoolStringEquals(attributeNameCpIdx, "Code")) {
methodHasBody = true;
inputStreamOrByteBuffer.skip(attributeLength);
} else {
inputStreamOrByteBuffer.skip(attributeLength);
}
}
// Create MethodInfo
if (enableMethodInfo) {
if (methodInfoList == null) {
methodInfoList = new MethodInfoList();
}
methodInfoList.add(new MethodInfo(className, methodName, methodAnnotationInfo,
methodModifierFlags, methodTypeDescriptor, methodTypeSignature, methodParameterNames,
methodParameterModifiers, methodParameterAnnotations, methodHasBody));
}
}
}
}
/**
* Read class attributes.
*
* @throws IOException
* if an I/O exception occurs.
* @throws ClassfileFormatException
* if the classfile is incorrectly formatted.
*/
private void readClassAttributes() throws IOException, ClassfileFormatException {
// Class attributes (including class annotations, class type variables, module info, etc.)
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < attributesCount; i++) {
final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int attributeLength = inputStreamOrByteBuffer.readInt();
if (scanSpec.enableAnnotationInfo
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) {
final int annotationCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int m = 0; m < annotationCount; m++) {
if (classAnnotations == null) {
classAnnotations = new AnnotationInfoList();
}
classAnnotations.add(readAnnotation());
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) {
final int numInnerClasses = inputStreamOrByteBuffer.readUnsignedShort();
for (int j = 0; j < numInnerClasses; j++) {
final int innerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int outerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) {
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(getConstantPoolClassName(innerClassInfoCpIdx),
getConstantPoolClassName(outerClassInfoCpIdx)));
}
inputStreamOrByteBuffer.skip(2); // inner_name_idx
inputStreamOrByteBuffer.skip(2); // inner_class_access_flags
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) {
// Get class type signature, including type variables
typeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
} else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) {
final String innermostEnclosingClassName = getConstantPoolClassName(
inputStreamOrByteBuffer.readUnsignedShort());
final int enclosingMethodCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
String definingMethodName;
if (enclosingMethodCpIdx == 0) {
// A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in
// class initializer code, e.g. assigned to a class field.
definingMethodName = "<clinit>";
} else {
definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0);
// Could also fetch method type signature using subFieldIdx = 1, if needed
}
// Link anonymous inner classes into the class with their containing method
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(className, innermostEnclosingClassName));
// Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner
// class
this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName;
} else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) {
final int moduleNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx);
// (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo:
// https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25
inputStreamOrByteBuffer.skip(attributeLength - 2);
} else {
inputStreamOrByteBuffer.skip(attributeLength);
}
}
}
/**
* Directly examine contents of classfile binary header to determine annotations, implemented interfaces, the
* super-class etc. Creates a new ClassInfo object, and adds it to classNameToClassInfoOut. Assumes classpath
* masking has already been performed, so that only one class of a given name will be added.
*
* @param classpathElement
* the classpath element
* @param classpathOrder
* the classpath order
* @param classNamesScheduledForScanning
* the class names scheduled for scanning
* @param relativePath
* the relative path
* @param classfileResource
* the classfile resource
* @param isExternalClass
* if this is an external class
* @param workQueue
* the work queue
* @param scanSpec
* the scan spec
* @param log
* the log
* @throws IOException
* If an IO exception occurs.
* @throws ClassfileFormatException
* If a problem occurs while parsing the classfile.
* @throws SkipClassException
* if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is
* false)
*/
Classfile(final ClasspathElement classpathElement, final List<ClasspathElement> classpathOrder,
final Set<String> classNamesScheduledForScanning, final String relativePath,
final Resource classfileResource, final boolean isExternalClass,
final WorkQueue<ClassfileScanWorkUnit> workQueue, final ScanSpec scanSpec, final LogNode log)
throws IOException, ClassfileFormatException, SkipClassException {
this.classpathElement = classpathElement;
this.classpathOrder = classpathOrder;
this.relativePath = relativePath;
this.classNamesScheduledForScanning = classNamesScheduledForScanning;
this.classfileResource = classfileResource;
this.isExternalClass = isExternalClass;
this.scanSpec = scanSpec;
this.log = log;
try {
// Open classfile as a ByteBuffer or InputStream
inputStreamOrByteBuffer = classfileResource.openOrRead();
// Check magic number
if (inputStreamOrByteBuffer.readInt() != 0xCAFEBABE) {
throw new ClassfileFormatException("Classfile does not have correct magic number");
}
// Read classfile minor version
inputStreamOrByteBuffer.readUnsignedShort();
// Read classfile major version
inputStreamOrByteBuffer.readUnsignedShort();
// Read the constant pool
readConstantPoolEntries();
// Read basic class info (
readBasicClassInfo();
// Read interfaces
readInterfaces();
// Read fields
readFields();
// Read methods
readMethods();
// Read class attributes
readClassAttributes();
} finally {
// Close ByteBuffer or InputStream
classfileResource.close();
inputStreamOrByteBuffer = null;
}
// Check if any superclasses, interfaces or annotations are external (non-whitelisted) classes
// that need to be scheduled for scanning, so that all of the "upwards" direction of the class
// graph is scanned for any whitelisted class, even if the superclasses / interfaces / annotations
// are not themselves whitelisted.
if (scanSpec.extendScanningUpwardsToExternalClasses) {
extendScanningUpwards();
// If any external classes were found, schedule them for scanning
if (additionalWorkUnits != null) {
workQueue.addWorkUnits(additionalWorkUnits);
}
}
// Write class info to log
if (log != null) {
final LogNode subLog = log.log("Found "
+ (isAnnotation ? "annotation class" : isInterface ? "interface class" : "class")
+ " " + className);
if (superclassName != null) {
subLog.log(
"Super" + (isInterface && !isAnnotation ? "interface" : "class") + ": " + superclassName);
}
if (implementedInterfaces != null) {
subLog.log("Interfaces: " + Join.join(", ", implementedInterfaces));
}
if (classAnnotations != null) {
subLog.log("Class annotations: " + Join.join(", ", classAnnotations));
}
if (annotationParamDefaultValues != null) {
for (final AnnotationParameterValue apv : annotationParamDefaultValues) {
subLog.log("Annotation default param value: " + apv);
}
}
if (fieldInfoList != null) {
for (final FieldInfo fieldInfo : fieldInfoList) {
subLog.log("Field: " + fieldInfo);
}
}
if (methodInfoList != null) {
for (final MethodInfo methodInfo : methodInfoList) {
subLog.log("Method: " + methodInfo);
}
}
if (typeSignature != null) {
ClassTypeSignature typeSig = null;
try {
typeSig = ClassTypeSignature.parse(typeSignature, /* classInfo = */ null);
} catch (final ParseException e) {
// Ignore
}
subLog.log("Class type signature: " + (typeSig == null ? typeSignature
: typeSig.toString(className, /* typeNameOnly = */ false, classModifiers, isAnnotation,
isInterface)));
}
if (refdClassNames != null) {
final List<String> refdClassNamesSorted = new ArrayList<>(refdClassNames);
Collections.sort(refdClassNamesSorted);
subLog.log("Referenced class names: " + Join.join(", ", refdClassNamesSorted));
}
}
}
}
|
package io.github.mzmine.gui;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javafx.application.HostServices;
import javafx.event.EventHandler;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import org.controlsfx.control.StatusBar;
import com.google.common.collect.ImmutableList;
import io.github.mzmine.datamodel.MZmineProject;
import io.github.mzmine.datamodel.PeakList;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.gui.NewVersionCheck.CheckType;
import io.github.mzmine.gui.helpwindow.HelpWindow;
import io.github.mzmine.gui.mainwindow.MainWindowController;
import io.github.mzmine.main.GoogleAnalyticsTracker;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.modules.MZmineRunnableModule;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.project.ProjectManager;
import io.github.mzmine.project.impl.MZmineProjectImpl;
import io.github.mzmine.taskcontrol.impl.WrappedTask;
import io.github.mzmine.util.ExitCode;
import io.github.mzmine.util.GUIUtils;
import io.github.mzmine.util.javafx.FxColorUtil;
import io.github.mzmine.util.javafx.FxIconUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.ListView;
import javafx.scene.control.TableView;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import static io.github.mzmine.modules.io.projectload.ProjectLoaderParameters.projectFile;
/**
* MZmine JavaFX Application class
*/
public class MZmineGUI extends Application implements Desktop {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private static final Image mzMineIcon = FxIconUtil.loadImageFromResources("MZmineIcon.png");
private static final String mzMineFXML = "mainwindow/MainWindow.fxml";
private static MainWindowController mainWindowController;
private static Stage mainStage;
private static Scene rootScene;
@Override
public void start(Stage stage) {
MZmineGUI.mainStage = stage;
MZmineCore.setDesktop(this);
logger.finest("Initializing MZmine main window");
try {
// Load the main window
URL mainFXML = this.getClass().getResource(mzMineFXML);
FXMLLoader loader = new FXMLLoader(mainFXML);
rootScene = loader.load();
mainWindowController = loader.getController();
stage.setScene(rootScene);
} catch (Exception e) {
e.printStackTrace();
logger.severe("Error loading MZmine GUI from FXML: " + e);
Platform.exit();
}
stage.setTitle("MZmine " + MZmineCore.getMZmineVersion());
stage.setMinWidth(600);
stage.setMinHeight(400);
// Set application icon
stage.getIcons().setAll(mzMineIcon);
stage.setOnCloseRequest(e -> {
requestQuit();
e.consume();
});
// Drag over surface
rootScene.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard dragBoard = event.getDragboard();
if (dragBoard.hasFiles()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
}
});
// Dropping over surface
rootScene.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard dragboard = event.getDragboard();
boolean success = false;
if (dragboard.hasFiles()) {
success = true;
for (File selectedFile:dragboard.getFiles()) {
final String moduleClass = "io.github.mzmine.modules.io.projectload.ProjectLoadModule";
Class<? extends MZmineRunnableModule> moduleJavaClass;
try {
moduleJavaClass = (Class<? extends MZmineRunnableModule>) Class.forName(moduleClass);
} catch (Throwable e) {
MZmineCore.getDesktop().displayMessage("Cannot load module class " + moduleClass);
return;
}
ParameterSet moduleParameters =
MZmineCore.getConfiguration().getModuleParameters(moduleJavaClass);
moduleParameters.getParameter(projectFile).setValue(selectedFile);
ParameterSet parametersCopy = moduleParameters.cloneParameterSet();
logger.finest("Starting module Open project with parameters " + parametersCopy);
MZmineCore.runMZmineModule(moduleJavaClass, parametersCopy);
}
}
event.setDropCompleted(success);
event.consume();
}
});
// Configure desktop properties such as the application taskbar icon
// on a new thread. It is important to start this thread after the
// JavaFX subsystem has started. Otherwise we could be treated like a
// Swing application.
Thread desktopSetupThread = new Thread(new DesktopSetup());
desktopSetupThread.setPriority(Thread.MIN_PRIORITY);
desktopSetupThread.start();
setStatusBarText("Welcome to MZmine " + MZmineCore.getMZmineVersion());
stage.show();
// update the size and position of the main window
/*
* ParameterSet paramSet = configuration.getPreferences(); WindowSettingsParameter settings =
* paramSet .getParameter(MZminePreferences.windowSetttings);
* settings.applySettingsToWindow(desktop.getMainWindow());
*/
// add last project menu items
/*
* if (desktop instanceof MainWindow) { ((MainWindow) desktop).createLastUsedProjectsMenu(
* configuration.getLastProjects()); // listen for changes
* configuration.getLastProjectsParameter() .addFileListChangedListener(list -> { // new list of
* last used projects Desktop desk = getDesktop(); if (desk instanceof MainWindow) {
* ((MainWindow) desk) .createLastUsedProjectsMenu(list); } }); }
*/
// Activate project - bind it to the desktop's project tree
MZmineProjectImpl currentProject =
(MZmineProjectImpl) MZmineCore.getProjectManager().getCurrentProject();
MZmineGUI.activateProject(currentProject);
// Check for updated version
NewVersionCheck NVC = new NewVersionCheck(CheckType.DESKTOP);
Thread nvcThread = new Thread(NVC);
nvcThread.setPriority(Thread.MIN_PRIORITY);
nvcThread.start();
// Tracker
GoogleAnalyticsTracker GAT =
new GoogleAnalyticsTracker("MZmine Loaded (GUI mode)", "/JAVA/Main/GUI");
Thread gatThread = new Thread(GAT);
gatThread.setPriority(Thread.MIN_PRIORITY);
gatThread.start();
// register shutdown hook only if we have GUI - we don't want to
// save configuration on exit if we only run a batch
ShutDownHook shutDownHook = new ShutDownHook();
Runtime.getRuntime().addShutdownHook(shutDownHook);
}
public static void requestQuit() {
Platform.runLater(() -> {
Alert alert = new Alert(AlertType.CONFIRMATION);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(mzMineIcon);
alert.setTitle("Confirmation");
alert.setHeaderText("Exit MZmine");
String s = "Are you sure you want to exit?";
alert.setContentText(s);
Optional<ButtonType> result = alert.showAndWait();
if ((result.isPresent()) && (result.get() == ButtonType.OK)) {
// Quit the JavaFX thread
Platform.exit();
// Call System.exit() because there are probably some background
// threads still running
System.exit(0);
}
});
}
public static void requestCloseProject() {
Platform.runLater(() -> {
Alert alert = new Alert(AlertType.CONFIRMATION);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(mzMineIcon);
alert.setTitle("Confirmation");
alert.setHeaderText("Close project");
String s = "Are you sure you want to close the current project?";
alert.setContentText(s);
Optional<ButtonType> result = alert.showAndWait();
if ((result.isPresent()) && (result.get() == ButtonType.OK)) {
// Close all windows related to previous project
GUIUtils.closeAllWindows();
// Create a new, empty project
MZmineProject newProject = new MZmineProjectImpl();
// Replace the current project with the new one
ProjectManager projectManager = MZmineCore.getProjectManager();
projectManager.setCurrentProject(newProject);
MZmineCore.getDesktop().setStatusBarText("Project space cleaned");
// Ask the garbage collector to free the previously used memory
System.gc();
}
});
}
public static void addWindow(Node node, String title) {
BorderPane parent = new BorderPane();
parent.setCenter(node);
Scene newScene = new Scene(parent);
// Copy CSS styles
newScene.getStylesheets().addAll(rootScene.getStylesheets());
Stage newStage = new Stage();
newStage.setTitle(title);
newStage.getIcons().add(mzMineIcon);
newStage.setScene(newScene);
newStage.show();
}
public static void activateProject(MZmineProject project) {
Platform.runLater(() -> {
MZmineCore.getProjectManager().setCurrentProject(project);
ListView<RawDataFile> rawDataTree = mainWindowController.getRawDataTree();
rawDataTree.setItems(project.getRawDataFiles());
ListView<PeakList> featureTree = mainWindowController.getFeatureTree();
featureTree.setItems(project.getFeatureLists());
});
}
public static @Nonnull List<RawDataFile> getSelectedRawDataFiles() {
final var rawDataListView = mainWindowController.getRawDataTree();
final var selectedRawDataFiles =
ImmutableList.copyOf(rawDataListView.getSelectionModel().getSelectedItems());
return selectedRawDataFiles;
}
public static @Nonnull List<PeakList> getSelectedFeatureLists() {
final var featureListView = mainWindowController.getFeatureTree();
final var selectedFeatureLists =
ImmutableList.copyOf(featureListView.getSelectionModel().getSelectedItems());
return selectedFeatureLists;
}
public static <ModuleType extends MZmineRunnableModule> void setupAndRunModule(
@Nonnull Class<ModuleType> moduleClass) {
final ParameterSet moduleParameters =
MZmineCore.getConfiguration().getModuleParameters(moduleClass);
ExitCode result = moduleParameters.showSetupDialog(true);
if (result == ExitCode.OK) {
MZmineCore.runMZmineModule(moduleClass, moduleParameters);
}
}
public static void showAboutWindow() {
// Show the about window
Platform.runLater(() -> {
final URL aboutPage =
MZmineGUI.class.getClassLoader().getResource("aboutpage/AboutMZmine.html");
HelpWindow aboutWindow = new HelpWindow(aboutPage.toString());
aboutWindow.show();
});
}
@Override
public String getName() {
return "MZmine desktop";
}
@Override
public Class<? extends ParameterSet> getParameterSetClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public Stage getMainWindow() {
return mainStage;
}
@Override
public TableView<WrappedTask> getTasksView() {
return mainWindowController.getTasksView();
}
@Override
public void openWebPage(URL url) {
HostServices openWPService = getHostServices();
openWPService.showDocument(String.valueOf(url));
}
@Override
public void setStatusBarText(String message) {
setStatusBarText(message, Color.BLACK);
}
@Override
public void setStatusBarText(String message, Color textColor) {
Platform.runLater(() -> {
if (mainWindowController == null)
return;
final StatusBar statusBar = mainWindowController.getStatusBar();
if (statusBar == null)
return;
statusBar.setText(message);
statusBar.setStyle("-fx-text-fill: " + FxColorUtil.colorToHex(textColor));
});
}
@Override
public void displayMessage(String msg) {
displayMessage("Message", msg);
}
@Override
public void displayMessage(String title, String msg) {
Platform.runLater(() -> {
Dialog<ButtonType> dialog = new Dialog<>();
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(mzMineIcon);
dialog.setTitle(title);
dialog.setContentText(msg);
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
dialog.showAndWait();
});
}
@Override
public void displayErrorMessage(String msg) {
displayMessage("Error", msg);
}
@Override
public void displayException(Exception e) {
displayErrorMessage(e.toString());
}
@Override
public RawDataFile[] getSelectedDataFiles() {
return getSelectedRawDataFiles().toArray(new RawDataFile[0]);
}
@Override
public PeakList[] getSelectedPeakLists() {
return getSelectedFeatureLists().toArray(new PeakList[0]);
}
@Override
public ExitCode exitMZmine() {
requestQuit();
return ExitCode.UNKNOWN;
}
}
|
package mensajeria;
import java.io.Serializable;
public class PaquetePersonajeDom extends Paquete implements Serializable, Cloneable {
private int id;
private int idMapa;
private String casta;
private String nombre;
private String raza;
private int saludTope;
private int energiaTope;
private int fuerza;
private int destreza;
private int inteligencia;
private int nivel;
private int experiencia;
public int getMapa(){
return idMapa;
}
public void setMapa(int mapa){
idMapa = mapa;
}
public int getNivel() {
return nivel;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
public int getExperiencia() {
return experiencia;
}
public void setExperiencia(int experiencia) {
this.experiencia = experiencia;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCasta() {
return casta;
}
public void setCasta(String casta) {
this.casta = casta;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRaza() {
return raza;
}
public void setRaza(String raza) {
this.raza = raza;
}
public int getSaludTope() {
return saludTope;
}
public void setSaludTope(int saludTope) {
this.saludTope = saludTope;
}
public int getEnergiaTope() {
return energiaTope;
}
public void setEnergiaTope(int energiaTope) {
this.energiaTope = energiaTope;
}
public int getFuerza() {
return fuerza;
}
public void setFuerza(int fuerza) {
this.fuerza = fuerza;
}
public int getDestreza() {
return destreza;
}
public void setDestreza(int destreza) {
this.destreza = destreza;
}
public int getInteligencia() {
return inteligencia;
}
public void setInteligencia(int inteligencia) {
this.inteligencia = inteligencia;
}
public Object clone() {
Object obj = null;
obj = super.clone();
return obj;
}
}
|
package mho.qbar.objects;
import mho.wheels.ordering.comparators.LexComparator;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.Optional;
/**
* An ordering for {@link Monomial}s.
*/
public enum MonomialOrder implements Comparator<Monomial> {
/**
* Lexicographic order
*/
LEX {
/**
* Compares {@code Iterable}s of {@code Integer}s lexicographically.
*/
private @NotNull Comparator<Iterable<Integer>> INTEGER_LEX = new LexComparator<>();
@Override
public int compare(@NotNull Monomial a, @NotNull Monomial b) {
if (a == b) return 0;
return INTEGER_LEX.compare(a.getExponents(), b.getExponents());
}
},
/**
* Graded lexicographic order
*/
GRLEX {
/**
* Compares {@code Iterable}s of {@code Integer}s lexicographically.
*/
private @NotNull Comparator<Iterable<Integer>> INTEGER_LEX = new LexComparator<>();
@Override
public int compare(@NotNull Monomial a, @NotNull Monomial b) {
if (a == b) return 0;
int thisDegree = a.degree();
int thatDegree = b.degree();
if (thisDegree > thatDegree) return 1;
if (thisDegree < thatDegree) return -1;
return INTEGER_LEX.compare(a.getExponents(), b.getExponents());
}
},
/**
* Graded reverse lexicographic order. The default for {@code Monomial}s.
*/
GREVLEX {
@Override
public int compare(@NotNull Monomial a, @NotNull Monomial b) {
if (a == b) return 0;
int aDegree = a.degree();
int bDegree = b.degree();
if (aDegree > bDegree) return 1;
if (aDegree < bDegree) return -1;
int aSize = a.size();
int bSize = b.size();
if (aSize > bSize) return -1;
if (aSize < bSize) return 1;
for (int i = aSize - 1; i >= 0; i
Variable v = Variable.of(i);
int thisExponent = a.exponent(v);
int thatExponent = b.exponent(v);
if (thisExponent > thatExponent) return -1;
if (thisExponent < thatExponent) return 1;
}
return 0;
}
};
/**
* Reads an {@link MonomialOrder} from a {@code String}.
*
* <ul>
* <li>{@code s} must be non-null.</li>
* <li>The result is non-null.</li>
* </ul>
*
* @param s the input {@code String}
* @return the {@code MonomialOrder} represented by {@code s}, or {@code Optional.empty} if {@code s} does not
* represent a {@code MonomialOrder}
*/
public static @NotNull Optional<MonomialOrder> readStrict(@NotNull String s) {
switch (s) {
case "LEX":
return Optional.of(MonomialOrder.LEX);
case "GRLEX":
return Optional.of(MonomialOrder.GRLEX);
case "GREVLEX":
return Optional.of(MonomialOrder.GREVLEX);
default:
return Optional.empty();
}
}
}
|
package mkremins.fanciful;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.amoebaman.util.Reflection;
import org.bukkit.Achievement;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.libs.com.google.gson.stream.JsonWriter;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class FancyMessage implements JsonRepresentedObject, Cloneable {
private List<MessagePart> messageParts;
private String jsonString;
private boolean dirty;
private static Constructor<?> nmsPacketPlayOutChatConstructor;
public FancyMessage clone() throws CloneNotSupportedException{
FancyMessage instance = (FancyMessage)super.clone();
instance.messageParts = new ArrayList<MessagePart>(messageParts.size());
for(int i = 0; i < messageParts.size(); i++){
instance.messageParts.add(i, messageParts.get(i).clone());
}
instance.dirty = false;
instance.jsonString = null;
return instance;
}
/**
* Creates a JSON message with text.
* @param firstPartText The existing text in the message.
*/
public FancyMessage(final String firstPartText) {
messageParts = new ArrayList<MessagePart>();
messageParts.add(new MessagePart(firstPartText));
jsonString = null;
dirty = false;
if(nmsPacketPlayOutChatConstructor == null){
try {
nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent"));
nmsPacketPlayOutChatConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Creates a JSON message without text.
*/
public FancyMessage() {
this(null);
}
public FancyMessage text(String text) {
MessagePart latest = latest();
if (latest.hasText()) {
throw new IllegalStateException("text for this message part is already set");
}
latest.text = text;
dirty = true;
return this;
}
public FancyMessage color(final ChatColor color) {
if (!color.isColor()) {
throw new IllegalArgumentException(color.name() + " is not a color");
}
latest().color = color;
dirty = true;
return this;
}
public FancyMessage style(ChatColor... styles) {
for (final ChatColor style : styles) {
if (!style.isFormat()) {
throw new IllegalArgumentException(style.name() + " is not a style");
}
}
latest().styles.addAll(Arrays.asList(styles));
dirty = true;
return this;
}
/**
* Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently edited part of the {@code FancyMessage} is clicked.
* @param path The path of the file on the client filesystem.
* @return This builder instance.
*/
public FancyMessage file(final String path) {
onClick("open_file", path);
return this;
}
/**
* Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently edited part of the {@code FancyMessage} is clicked.
* @param url The URL of the page to open when the link is clicked.
* @return This builder instance.
*/
public FancyMessage link(final String url) {
onClick("open_url", url);
return this;
}
/**
* Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is clicked.
* The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key.
* @param command The text to display in the chat bar of the client.
* @return This builder instance.
*/
public FancyMessage suggest(final String command) {
onClick("suggest_command", command);
return this;
}
/**
* Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when the currently edited part of the {@code FancyMessage} is clicked.
* The client <b>will</b> immediately send the command to the server to be executed when the editing component is clicked.
* @param command The text to display in the chat bar of the client.
* @return This builder instance.
*/
public FancyMessage command(final String command) {
onClick("run_command", command);
return this;
}
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param name The name of the achievement to display, excluding the "achievement." prefix.
* @return This builder instance.
*/
public FancyMessage achievementTooltip(final String name) {
onHover("show_achievement", new JsonString("achievement." + name));
return this;
}
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param which The achievement to display.
* @return This builder instance.
*/
public FancyMessage achievementTooltip(final Achievement which) {
try {
Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement));
} catch (Exception e) {
e.printStackTrace();
return this;
}
}
public FancyMessage statisticTooltip(final Statistic which) {
Type type = which.getType();
if (type != Type.UNTYPED) {
throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (Exception e) {
e.printStackTrace();
return this;
}
}
public FancyMessage statisticTooltip(final Statistic which, Material item) {
Type type = which.getType();
if (type == Type.UNTYPED) {
throw new IllegalArgumentException("That statistic needs no additional parameter!");
}
if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) {
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (Exception e) {
e.printStackTrace();
return this;
}
}
public FancyMessage statisticTooltip(final Statistic which, EntityType entity) {
Type type = which.getType();
if (type == Type.UNTYPED) {
throw new IllegalArgumentException("That statistic needs no additional parameter!");
}
if (type != Type.ENTITY) {
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (Exception e) {
e.printStackTrace();
return this;
}
}
/**
* Set the behavior of the current editing component to display information about an item when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param itemJSON A string representing the JSON-serialized NBT data tag of an {@link ItemStack}.
* @return This builder instance.
*/
public FancyMessage itemTooltip(final String itemJSON) {
onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter
return this;
}
/**
* Set the behavior of the current editing component to display information about an item when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param itemStack The stack for which to display information.
* @return This builder instance.
*/
public FancyMessage itemTooltip(final ItemStack itemStack) {
try {
Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
} catch (Exception e) {
e.printStackTrace();
return this;
}
}
/**
* Set the behavior of the current editing component to display raw text when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param text The text, which supports newlines, which will be displayed to the client upon hovering.
* @return This builder instance.
*/
public FancyMessage tooltip(final String text) {
onHover("show_text", new JsonString(text));
return this;
}
/**
* Set the behavior of the current editing component to display raw text when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created.
* @return This builder instance.
*/
public FancyMessage tooltip(final Iterable<String> lines) {
StringBuilder builder = new StringBuilder();
for(String object : lines){
builder.append(object);
builder.append('\n');
}
tooltip(builder.toString());
return this;
}
/**
* Set the behavior of the current editing component to display raw text when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
* @param lines The lines of text which will be displayed to the client upon hovering.
* @return This builder instance.
*/
public FancyMessage tooltip(final String... lines) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < lines.length; i++){
builder.append(lines[i]);
builder.append('\n');
}
tooltip(builder.toString());
return this;
}
/**
* Set the behavior of the current editing component to display formatted text when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied unless the tooltip formatting overrides them.</p>
* @param text The formatted text which will be displayed to the client upon hovering.
* @return This builder instance.
*/
public FancyMessage tooltip(FancyMessage text){
for(MessagePart component : text.messageParts){
if(component.clickActionData != null && component.clickActionName != null){
throw new IllegalArgumentException("The tooltip text cannot have click data.");
}else if(component.hoverActionData != null && component.hoverActionName != null){
throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
}
}
onHover("show_text", text);
return this;
}
/**
* Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text.
* <p>Tooltips inherit display characteristics, such as color and styles, from the message component on which they are applied unless the tooltip formatting overrides them.</p>
* @param text The formatted text which will be displayed to the client upon hovering.
* @return This builder instance.
*/
public FancyMessage tooltip(FancyMessage... lines){
FancyMessage result = new FancyMessage();
for(FancyMessage text : lines){
try{
for(MessagePart component : text.messageParts){
if(component.clickActionData != null && component.clickActionName != null){
throw new IllegalArgumentException("The tooltip text cannot have click data.");
}else if(component.hoverActionData != null && component.hoverActionName != null){
throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
}
result.messageParts.add(component.clone());
}
result.messageParts.add(new MessagePart("\n"));
}catch (CloneNotSupportedException e) {
e.printStackTrace();
return this;
}
}
return tooltip(result);
}
/**
* Terminate construction of the current editing component, and begin construction of a new message component.
* After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method.
* @param obj The text which will populate the new message component.
* @return This builder instance.
*/
public FancyMessage then(final Object obj) {
if (!latest().hasText()) {
throw new IllegalStateException("previous message part has no text");
}
messageParts.add(new MessagePart(obj.toString()));
dirty = true;
return this;
}
/**
* Terminate construction of the current editing component, and begin construction of a new message component.
* After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method.
* @return This builder instance.
*/
public FancyMessage then() {
if (!latest().hasText()) {
throw new IllegalStateException("previous message part has no text");
}
messageParts.add(new MessagePart());
dirty = true;
return this;
}
public void writeJson(JsonWriter writer) throws IOException{
if (messageParts.size() == 1) {
latest().writeJson(writer);
} else {
writer.beginObject().name("text").value("").name("extra").beginArray();
for (final MessagePart part : messageParts) {
part.writeJson(writer);
}
writer.endArray().endObject();
}
}
/**
* Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}.
* This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}.
* @return The JSON string representing this object.
*/
public String toJSONString() {
if (!dirty && jsonString != null) {
return jsonString;
}
StringWriter string = new StringWriter();
JsonWriter json = new JsonWriter(string);
try {
writeJson(json);
json.close();
} catch (Exception e) {
throw new RuntimeException("invalid message");
}
jsonString = string.toString();
dirty = false;
return jsonString;
}
/**
* Sends this message to a player. The player will receive the fully-fledged formatted display of this message.
* @param player The player who will receive the message.
*/
public void send(Player player){
try {
Object handle = Reflection.getHandle(player);
Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle);
Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(toJSONString()));
} catch (Exception e) {
e.printStackTrace();
}
}
// The ChatSerializer's instance of Gson
private net.minecraft.util.com.google.gson.Gson nmsChatSerializerGsonInstance;
private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException{
if(nmsChatSerializerGsonInstance == null){
// Find the field and its value, completely bypassing obfuscation
for(Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()){
if(Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType() == net.minecraft.util.com.google.gson.Gson.class){
// We've found our field
declaredField.setAccessible(true);
nmsChatSerializerGsonInstance = (net.minecraft.util.com.google.gson.Gson)declaredField.get(null);
break;
}
}
}
// Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
// Of course, the implementation may change, but fuzzy matches might break with signature changes
Object serializedChatComponent = nmsChatSerializerGsonInstance.fromJson(json, Reflection.getNMSClass("IChatBaseComponent"));
return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}
/**
* Sends this message to a command sender.
* If the sender is a player, they will receive the fully-fledged formatted display of this message.
* Otherwise, they will receive a version of this message with less formatting.
* @param sender The command sender who will receive the message.
* @see #toOldMessageFormat()
*/
public void send(CommandSender sender) {
if (sender instanceof Player) {
send((Player) sender);
} else {
sender.sendMessage(toOldMessageFormat());
}
}
/**
* Sends this message to multiple command senders.
* @param senders The command senders who will receive the message.
* @see #send(CommandSender)
*/
public void send(final Iterable<? extends CommandSender> senders) {
for (final CommandSender sender : senders) {
send(sender);
}
}
/**
* Convert this message to a human-readable string with limited formatting.
* This method is used to send this message to clients without JSON formatting support.
* <p>
* Serialization of this message by using this message will include (in this order for each message part):
* <ol>
* <li>The color of each message part.</li>
* <li>The applicable stylizations for each message part.</li>
* <li>The core text of the message part.</li>
* </ol>
* The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
* </p>
* <p>
* Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.</p>
* @return A human-readable string representing limited formatting in addition to the core text of this message.
*/
public String toOldMessageFormat() {
StringBuilder result = new StringBuilder();
for (MessagePart part : messageParts) {
result.append(part.color == null ? "" : part.color);
for(ChatColor formatSpecifier : part.styles){
result.append(formatSpecifier);
}
result.append(part.text);
}
return result.toString();
}
private MessagePart latest() {
return messageParts.get(messageParts.size() - 1);
}
private void onClick(final String name, final String data) {
final MessagePart latest = latest();
latest.clickActionName = name;
latest.clickActionData = data;
dirty = true;
}
private void onHover(final String name, final JsonRepresentedObject data) {
final MessagePart latest = latest();
latest.hoverActionName = name;
latest.hoverActionData = data;
dirty = true;
}
}
|
package myessentials.entities;
/**
* Helper class for storing position of a chunk
*/
public class ChunkPos {
private final int dim;
private final int x;
private final int z;
public ChunkPos(int dim, int x, int z) {
this.dim = dim;
this.x = x;
this.z = z;
}
public int getX() {
return x;
}
public int getZ() {
return z;
}
public int getDim() {
return dim;
}
@Override
public String toString() {
return "ChunkPos(x: " + x + ", z: " + z + " | Dim: " + dim + ")";
}
}
|
package net.amigocraft.mglib.api;
import static net.amigocraft.mglib.MGUtil.*;
import static net.amigocraft.mglib.Main.locale;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import com.google.common.collect.Lists;
import net.amigocraft.mglib.MGUtil;
import net.amigocraft.mglib.Main;
import net.amigocraft.mglib.RollbackManager;
import net.amigocraft.mglib.UUIDFetcher;
import net.amigocraft.mglib.event.player.PlayerHitArenaBorderEvent;
import net.amigocraft.mglib.event.player.PlayerJoinMinigameRoundEvent;
import net.amigocraft.mglib.event.player.PlayerLeaveMinigameRoundEvent;
import net.amigocraft.mglib.event.round.MinigameRoundEndEvent;
import net.amigocraft.mglib.event.round.MinigameRoundPrepareEvent;
import net.amigocraft.mglib.event.round.MinigameRoundStartEvent;
import net.amigocraft.mglib.event.round.MinigameRoundTickEvent;
import net.amigocraft.mglib.exception.ArenaNotExistsException;
import net.amigocraft.mglib.exception.InvalidLocationException;
import net.amigocraft.mglib.exception.PlayerNotPresentException;
import net.amigocraft.mglib.exception.PlayerOfflineException;
import net.amigocraft.mglib.exception.PlayerPresentException;
import net.amigocraft.mglib.exception.RoundFullException;
import net.amigocraft.mglib.misc.JoinResult;
import net.amigocraft.mglib.misc.Metadatable;
public class Round implements Metadatable {
private int minPlayers;
private int maxPlayers;
private int prepareTime;
private int roundTime;
private Location exitLocation;
private String plugin;
private int time = 0;
private Stage stage;
private String world;
private String arena;
private List<Location> spawns = new ArrayList<Location>();
private Location minBound;
private Location maxBound;
private HashMap<String, MGPlayer> players = new HashMap<String, MGPlayer>();
private int timerHandle = -1;
private boolean damage;
private boolean pvp;
private boolean rollback;
private boolean ended;
/**
* Creates a new {@link Round} with the given parameters.
* <br><br>
* Please use {@link Minigame#createRound(String)} unless you
* understand the implications of using this constructor.
* @param plugin the plugin which this round should be associated with.
* @param arena the name of the arena in which this round takes place in.
* @throws ArenaNotExistsException if the specified arena does not exist.
*/
public Round(String plugin, String arena) throws ArenaNotExistsException {
YamlConfiguration y = loadArenaYaml(plugin);
if (!y.contains(arena))
throw new ArenaNotExistsException();
ConfigurationSection cs = y.getConfigurationSection(arena); // make the code easier to read
world = cs.getString("world"); // get the name of the world of the arena
World w = Bukkit.getWorld(world); // convert it to a Bukkit world
if (w == null)
w = Bukkit.createWorld(new WorldCreator(world));
if (w == null) // but what if world is kill?
throw new IllegalArgumentException("World " + world + " cannot be loaded!"); // then round is kill
for (String k : cs.getConfigurationSection("spawns").getKeys(false)){ // load spawns into round object
Location l = new Location(w, cs.getDouble("spawns." + k + ".x"),
cs.getDouble("spawns." + k + ".y"),
cs.getDouble("spawns." + k + ".z"));
if (cs.isSet(k + ".pitch"))
l.setPitch((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".pitch"));
if (cs.isSet(k + ".yaw"))
l.setYaw((float)cs.getDouble(cs.getCurrentPath() + ".spawns." + k + ".yaw"));
spawns.add(l); // register spawn
}
if (cs.getBoolean("boundaries")){ // check if arena has boundaries defined
minBound = new Location(w, cs.getDouble("minX"), cs.getDouble("minY"), cs.getDouble("minZ"));
maxBound = new Location(w, cs.getDouble("maxX"), cs.getDouble("maxY"), cs.getDouble("maxZ"));
}
else {
minBound = null;
maxBound = null;
}
this.plugin = plugin; // set globals
this.arena = arena;
ConfigManager cm = getConfigManager();
this.prepareTime = cm.getDefaultPreparationTime();
this.roundTime = cm.getDefaultPlayingTime();
this.minPlayers = cm.getMinPlayers();
this.maxPlayers = cm.getMaxPlayers();
this.exitLocation = cm.getDefaultExitLocation();
this.damage = cm.isDamageAllowed();
this.pvp = cm.isPvPAllowed();
this.rollback = cm.isRollbackEnabled();
stage = Stage.WAITING; // default to waiting stage
String[] defaultKeysA = new String[]{"world", "spawns", "minX", "minY", "minZ", "maxX", "maxY", "maxZ"};
List<String> defaultKeys = Arrays.asList(defaultKeysA);
for (String k : cs.getKeys(true)){
if (!defaultKeys.contains(k.split("\\.")[0]))
setMetadata(k, cs.get(k));
}
Minigame.getMinigameInstance(plugin).getRounds().put(arena, this); // register round with minigame instance
}
/**
* Gets the name of the minigame plugin associated with this {@link Round}.
* @return The name of the minigame plugin associated with this {@link Round}.
* @since 0.1.0
*/
public String getPlugin(){
return plugin;
}
/**
* Gets the instance of the MGLib API registered by the plugin associated with this {@link Round}.
* @return The instance of the MGLib API registered by the plugin associated with this {@link Round}.
* @since 0.1.0
*/
public Minigame getMinigame(){
return Minigame.getMinigameInstance(plugin);
}
/**
* Gets the name of the arena associated with this {@link Round}.
* @return The name of the arena associated with this {@link Round}.
* @since 0.1.0
*/
public String getArena(){
return arena;
}
/**
* Gets the current {@link Stage} of this {@link Round}.
* @return The current {@link Stage} of this {@link Round}.
* @since 0.1.0
*/
public Stage getStage(){
return stage;
}
/**
* Gets the current time in seconds of this {@link Round}, where 0 represents the first second of it.
* @return the current time in seconds of this {@link Round}, where 0 represents the first second of it.
* @since 0.1.0
*/
public int getTime(){
return time;
}
/**
* Gets the time remaining in this round.
* @return the time remaining in this round, or -1 if there is no time limit or if the {@link Stage stage} is not
* {@link Stage#PLAYING PLAYING} or {@link Stage#PREPARING PREPARING}
* @since 0.1.0
*/
public int getRemainingTime(){
switch (this.getStage()){
case PREPARING:
if (this.getPreparationTime() > 0)
return this.getPreparationTime() - this.getTime();
else
return -1;
case PLAYING:
if (this.getPlayingTime() > 0)
return this.getPlayingTime() - this.getTime();
else
return -1;
default:
return -1;
}
}
/**
* Gets the round's preparation time.
* @return The round's preparation time.
* @since 0.1.0
*/
public int getPreparationTime(){
return prepareTime;
}
/**
* Gets the round's playing time.
* @return The round's playing time.
* @since 0.1.0
*/
public int getPlayingTime(){
return roundTime;
}
/**
* Gets the round's timer's task's handle, or -1 if a timer is not started.
* @return The round's timer's task's handle, or -1 if a timer is not started.
* @since 0.1.0
*/
public int getTimerHandle(){
return timerHandle;
}
/**
* Sets the associated arena of this {@link Round}.
* @param arena The arena to associate with this {@link Round}.
* @since 0.1.0
*/
public void setArena(String arena){
this.arena = arena;
}
/**
* Sets the current stage of this {@link Round}.
* @param s The stage to set this {@link Round} to.
* @since 0.1.0
*/
public void setStage(Stage s){
stage = s;
}
/**
* Sets the remaining time of this {@link Round}.
* @param t The time to set this {@link Round} to.
* @since 0.1.0
*/
public void setTime(int t){
time = t;
}
/**
* Sets the round's preparation time.
* @param t The number of seconds to set the preparation time to. Use -1 for no limit, or 0 for
* no preparation phase.
* @since 0.1.0
*/
public void setPreparationTime(int t){
prepareTime = t;
}
/**
* Sets the round's playing time.
* @param t The number of seconds to set the preparation time to. Use -1 for no limit.
* @since 0.1.0
*/
public void setPlayingTime(int t){
roundTime = t;
}
/**
* Decrements the time remaining in the round by 1.
* <br><br>
* Please do not call this method from your plugin unless you understand the implications. Let MGLib handle
* the timer.
* @since 0.1.0
*/
public void tick(){
time += 1;
}
/**
* Subtracts <b>t</b> seconds from the elapsed time in the round.
* @param t The number of seconds to subtract.
* @since 0.1.0
*/
public void subtractTime(int t){
time -= t;
}
/**
* Adds <b>t</b> seconds to the elapsed time in the round.
* @param t The number of seconds to add.
* @since 0.1.0
*/
public void addTime(int t){
time += t;
}
/**
* Destroys this {@link Round}.
* <br><br>
* <b>Please do not call this method from your plugin unless you understand the implications.</b>
* @since 0.1.0
*/
public void destroy(){
Minigame.getMinigameInstance(plugin).getRounds().remove(this);
}
/**
* Retrieves a list of {@link MGPlayer MGPlayers} in this round.
* @return A list of {@link MGPlayer MGPlayers} in this round.
* @since 0.1.0
*/
public List<MGPlayer> getPlayerList(){
return Lists.newArrayList(players.values());
}
/**
* Retrieves a {@link HashMap} of players in this round.
* @return a {@link HashMap} mapping the names of players in the round to their respective {@link MGPlayer} objects.
* @since 0.1.0
*/
public HashMap<String, MGPlayer> getPlayers(){
return players;
}
/**
* Retrieves a {@link HashMap} of all players on a given team.
* @param team the team to retrieve players from.
* @return a {@link HashMap} mapping the names of players on a given team to their respective {@link MGPlayer} objects.
* @since 0.3.0
*/
public HashMap<String, MGPlayer> getTeam(String team){
HashMap<String, MGPlayer> t = new HashMap<String, MGPlayer>();
for (MGPlayer p : getPlayerList()){
if (p.getTeam() != null && p.getTeam().equals(team))
t.put(p.getName(), p);
}
return t;
}
/**
* Retrieves a list of non-spectating {@link MGPlayer MGPlayers} in this round.
* @return a list of non-spectating {@link MGPlayer MGPlayers} in this round.
* @since 0.2.0
*/
public List<MGPlayer> getAlivePlayerList(){
List<MGPlayer> list = new ArrayList<MGPlayer>();
for (MGPlayer p : players.values())
if (!p.isSpectating())
list.add(p);
return list;
}
/**
* Retrieves a list of spectating {@link MGPlayer MGPlayers} in this {@link Round}.
* @return a list of spectating {@link MGPlayer MGPlayers} in this {@link Round}.
* @since 0.2.0
*/
public List<MGPlayer> getSpectatingPlayerList(){
List<MGPlayer> list = new ArrayList<MGPlayer>();
for (MGPlayer p : players.values())
if (p.isSpectating())
list.add(p);
return list;
}
/**
* Retrieves the number of {@link MGPlayer MGPlayers} in this {@link Round}.
* @return the number of {@link MGPlayer MGPlayers} in this {@link Round}.
* @since 0.2.0
*/
public int getPlayerCount(){
return players.size();
}
/**
* Retrieves the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round}.
* @return the number of in-game (non-spectating) {@link MGPlayer MGPlayers} in this {@link Round}.
* @since 0.2.0
*/
public int getAlivePlayerCount(){
int count = 0;
for (MGPlayer p : players.values())
if (!p.isSpectating())
count += 1;
return count;
}
/**
* Retrieves the number of spectating {@link MGPlayer MGPlayers} in this {@link Round}.
* @return the number of spectating {@link MGPlayer MGPlayers} in this {@link Round}.
* @since 0.2.0
*/
public int getSpectatingPlayerCount(){
int count = 0;
for (MGPlayer p : players.values())
if (p.isSpectating())
count += 1;
return count;
}
public void start(){
if (stage == Stage.WAITING){ // make sure the round isn't already started
final Round r = this;
if (r.getPreparationTime() > 0){
r.setTime(0); // reset time
r.setStage(Stage.PREPARING); // set stage to preparing
MGUtil.callEvent(new MinigameRoundPrepareEvent(r)); // call an event for anyone who cares
}
else {
r.setTime(0); // reset timer
r.setStage(Stage.PLAYING);
MGUtil.callEvent(new MinigameRoundStartEvent(r));
}
if (time != -1){ // I'm pretty sure this is wrong, but I'm also pretty tired
timerHandle = Bukkit.getScheduler().runTaskTimer(Main.plugin, new Runnable(){
public void run(){
int oldTime = r.getTime();
boolean stageChange = false;
int limit = r.getStage() == Stage.PLAYING ? r.getPlayingTime() : r.getPreparationTime();
if (r.getTime() >= limit && limit > 0){ // timer reached its limit
if (r.getStage() == Stage.PREPARING){ // if we're still preparing...
r.setStage(Stage.PLAYING); // ...set stage to playing
stageChange = true;
r.setTime(0); // reset timer
MGUtil.callEvent(new MinigameRoundStartEvent(r));
}
else { // we're playing and the round just ended
end(true);
stageChange = true;
}
}
if (!stageChange)
r.tick();
//TODO: Allow for a grace period upon player disconnect
if (r.getMinBound() != null){
// this whole bit handles keeping player inside the arena
//TODO: Possibly make an event for when a player wanders out of an arena
for (MGPlayer p : r.getPlayerList()){
Player pl = p.getBukkitPlayer();
Location l = pl.getLocation();
boolean event = true;
if (l.getX() < r.getMinBound().getX())
pl.teleport(new Location(l.getWorld(), r.getMinBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN);
else if (l.getX() > r.getMaxBound().getX())
pl.teleport(new Location(l.getWorld(), r.getMaxBound().getX(), l.getY(), l.getZ()), TeleportCause.PLUGIN);
else if (l.getY() < r.getMinBound().getY())
pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN);
else if (l.getY() > r.getMaxBound().getY())
pl.teleport(new Location(l.getWorld(), l.getX(), r.getMinBound().getY(), l.getZ()), TeleportCause.PLUGIN);
else if (l.getZ() < r.getMinBound().getZ())
pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN);
else if (l.getZ() > r.getMaxBound().getZ())
pl.teleport(new Location(l.getWorld(), l.getX(), l.getY(), r.getMinBound().getZ()), TeleportCause.PLUGIN);
else
event = false;
if (event)
MGUtil.callEvent(new PlayerHitArenaBorderEvent(p));
}
}
if (r.getStage() == Stage.PLAYING || r.getStage() == Stage.PREPARING)
MGUtil.callEvent(new MinigameRoundTickEvent(r, oldTime, stageChange));
}
}, 0L, 20L).getTaskId(); // iterates once per second
}
}
else
throw new IllegalStateException(Bukkit.getPluginManager().getPlugin(plugin) +
" attempted to start a round which had already been started.");
}
public void end(boolean timeUp){
ended = true;
MGUtil.callEvent(new MinigameRoundEndEvent(this, timeUp));
setStage(Stage.RESETTING);
setTime(-1);
if (timerHandle != -1)
Bukkit.getScheduler().cancelTask(timerHandle); // cancel the round's timer task
timerHandle = -1; // reset timer handle since the task no longer exists
for (MGPlayer mp : getPlayerList()){ // iterate and remove players
try {
removePlayer(mp.getName());
}
catch (Exception ex){} // I don't care if this happens
}
if (getConfigManager().isRollbackEnabled()) // check if rollbacks are enabled
getRollbackManager().rollback(getArena()); // roll back arena
setStage(Stage.WAITING);
}
public void end(){
end(false);
}
/**
* Retrieves whether this round has been ended.
* @return whether this round has been ended.
* @since 0.3.0
*/
public boolean hasEnded(){
return ended;
}
/**
* Retrieves the location representing the minimum boundary on all three axes of the arena this round takes place in.
* @return the location representing the minimum boundary on all three axes of the arena this round takes place in, or
* null if the arena does not have boundaries.
* @since 0.1.0
*/
public Location getMinBound(){
return minBound;
}
/**
* Retrieves the location representing the maximum boundary on all three axes of the arena this round takes place in.
* @return the location representing the maximum boundary on all three axes of the arena this round takes place in, or
* null if the arena does not have boundaries.
* @since 0.1.0
*/
public Location getMaxBound(){
return maxBound;
}
/**
* Sets the minimum boundary on all three axes of this round object.
* @param x The minimum x-value.
* @param y The minimum y-value.
* @param z The minimum z-value.
* @since 0.1.0
*/
public void setMinBound(double x, double y, double z){
this.minBound = new Location(this.minBound.getWorld(), x, y, z);
}
/**
* Sets the maximum boundary on all three axes of this round object.
* @param x The maximum x-value.
* @param y The maximum y-value.
* @param z The maximum z-value.
* @since 0.1.0
*/
public void setMaxBound(double x, double y, double z){
this.minBound = new Location(this.minBound.getWorld(), x, y, z);
}
/**
* Retrieves a list of possible spawns for this round's arena.
* @return a list of possible spawns for this round's arena.
* @since 0.1.0
*/
public List<Location> getSpawns(){
return spawns;
}
/**
* Returns the {@link MGPlayer} in this round associated with the given username.
* @param player The username to search for.
* @return The {@link MGPlayer} in this round associated with the given username, or <b>null</b> if none is found.
* @since 0.1.0
*/
public MGPlayer getMGPlayer(String player){
return players.get(player);
}
/**
* Retrieves the world of this arena.
* @return The name of the world containing this arena.
* @since 0.1.0
*/
public String getWorld(){
return world;
}
/**
* Adds a player by the given name to this {@link Round round}.
* @param name the player to add to this {@link Round round}.
* (will default to random/sequential (depending on configuration) if out of bounds).
* @return the {@link JoinResult result} of the player being added to the round.
* @throws PlayerOfflineException if the player is not online.
* @throws PlayerPresentException if the player is already in a round.
* @throws RoundFullException if the round is full.
* @since 0.1.0
*/
public JoinResult addPlayer(String name) throws PlayerOfflineException, PlayerPresentException, RoundFullException {
return addPlayer(name, -1);
}
/**
* Adds a player by the given name to this {@link Round round}.
* @param name the player to add to this {@link Round round}.
* @param spawn the spawn number to teleport the player to
* (will default to random/sequential (depending on configuration) if out of bounds).
* @return the {@link JoinResult result} of the player being added to the round.
* @throws PlayerOfflineException if the player is not online.
* @throws PlayerPresentException if the player is already in a round.
* @throws RoundFullException if the round is full.
* @since 0.3.0
*/
@SuppressWarnings("deprecation")
public JoinResult addPlayer(String name, int spawn) throws PlayerOfflineException, PlayerPresentException, RoundFullException {
final Player p = Bukkit.getPlayer(name);
if (p == null) // check that the specified player is online
throw new PlayerOfflineException();
if (getPlayerCount() >= getMaxPlayers() && getMaxPlayers() > 0)
throw new RoundFullException();
if (getStage() == Stage.PREPARING){
if (!getConfigManager().getAllowJoinRoundWhilePreparing()){
p.sendMessage(ChatColor.RED + locale.getMessage("no-join-prepare"));
return JoinResult.ROUND_PREPARING;
}
}
else if (getStage() == Stage.PLAYING){
if (!getConfigManager().getAllowJoinRoundInProgress()){
p.sendMessage(ChatColor.RED + locale.getMessage("no-join-progress"));
return JoinResult.ROUND_PLAYING;
}
}
MGPlayer mp = Minigame.getMinigameInstance(plugin).getMGPlayer(name);
if (mp == null){
try {
mp = (MGPlayer)getConfigManager().getPlayerClass().getDeclaredConstructors()[0]
.newInstance(plugin, name, arena);
}
catch (InvocationTargetException ex){ // any error thrown from the called constructor
ex.getTargetException().printStackTrace();
}
catch (IllegalArgumentException ex){ // thrown when the overriding constructor doesn't match what's expected
Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is malformed");
ex.printStackTrace();
}
catch (SecurityException ex){ // I have no idea why this would happen.
ex.printStackTrace();
}
catch (InstantiationException ex){ // if this happens then the overriding plugin seriously screwed something up
Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is seriously wack. Fix it, developer.");
ex.printStackTrace();
}
catch (IllegalAccessException ex){ // thrown if the called method from the overriding class is not public
Main.log.severe("The constructor overriding MGLib's default MGPlayer for plugin " + plugin + " is not visible");
ex.printStackTrace();
}
}
else if (mp.getArena() == null)
mp.setArena(arena);
else
throw new PlayerPresentException();
ItemStack[] contents = p.getInventory().getContents();
PlayerInventory pInv = (PlayerInventory)p.getInventory();
ItemStack helmet = pInv.getHelmet(), chestplate = pInv.getChestplate(), leggings = pInv.getLeggings(), boots = pInv.getBoots();
try {
File invDir = new File(Main.plugin.getDataFolder(), "inventories");
File invF = new File(Main.plugin.getDataFolder() + File.separator +
"inventories" + File.separator +
UUIDFetcher.getUUIDOf(p.getName()) + ".dat");
if (!invF.exists()){
invDir.mkdirs();
invF.createNewFile();
}
YamlConfiguration invY = new YamlConfiguration();
invY.load(invF);
for (int i = 0; i < contents.length; i++)
invY.set(Integer.toString(i), contents[i]);
if (helmet != null)
invY.set("h", helmet);
if (chestplate != null)
invY.set("c", chestplate);
if (leggings != null)
invY.set("l", leggings);
if (boots != null)
invY.set("b", boots);
invY.save(invF);
}
catch (Exception ex){
ex.printStackTrace();
p.sendMessage(ChatColor.RED + locale.getMessage("inv-save-fail"));
return JoinResult.INVENTORY_SAVE_ERROR;
}
((PlayerInventory)p.getInventory()).clear();
((PlayerInventory)p.getInventory()).setArmorContents(new ItemStack[]{null, null, null, null});
p.updateInventory();
for (PotionEffect pe : p.getActivePotionEffects())
p.removePotionEffect(pe.getType()); // remove any potion effects before adding the player
if ((getStage() == Stage.PREPARING || getStage() == Stage.PLAYING) &&
getConfigManager().getSpectateOnJoin())
mp.setSpectating(true);
else
mp.setSpectating(false);
mp.setPrevGameMode(p.getGameMode());
p.setGameMode(getConfigManager().getDefaultGameMode());
players.put(name, mp); // register player with round object
Location sp = (spawn >= 0 && spawns.size() > spawn) ? spawns.get(spawn) :
getConfigManager().isRandomSpawning() ?
spawns.get(new Random().nextInt(spawns.size())) :
spawns.get(players.size() % spawns.size());
p.teleport(sp, TeleportCause.PLUGIN); // teleport the player to it
MGUtil.callEvent(new PlayerJoinMinigameRoundEvent(this, mp));
if (getStage() == Stage.WAITING && getPlayerCount() >= getMinPlayers() && getPlayerCount() > 0)
start();
return JoinResult.SUCCESS;
}
/**
* Removes a given player from this {@link Round round} and teleports them to the given location.
* @param name The player to remove from this {@link Round round}.
* @param location The location to teleport the player to.
* @throws PlayerOfflineException if the player is not online.
* @throws PlayerNotPresentException if the player are not in this round.
* @since 0.1.0
*/
public void removePlayer(String name, Location location) throws PlayerOfflineException, PlayerNotPresentException {
@SuppressWarnings("deprecation")
Player p = Bukkit.getPlayer(name);
MGPlayer mp = players.get(name);
if (mp == null)
throw new PlayerNotPresentException();
if (p != null){
PlayerLeaveMinigameRoundEvent event = new PlayerLeaveMinigameRoundEvent(this, mp);
MGUtil.callEvent(event);
mp.setArena(null); // they're not in an arena anymore
mp.setSpectating(false); // make sure they're not dead when they join a new round
players.remove(name); // remove player from round
p.setGameMode(mp.getPrevGameMode()); // restore the player's gamemode
mp.reset(location); // reset the object and send the player to the exit point
}
}
/**
* Removes a given player from this {@link Round round} and teleports them to the round or plugin's default exit location
* (defaults to the main world's spawn point).
* @param name The player to remove from this {@link Round round}.
* @throws PlayerNotPresentException if the given player is not in this round.
* @throws PlayerOfflineException if the given player is offline.
* @since 0.1.0
*/
public void removePlayer(String name) throws PlayerOfflineException, PlayerNotPresentException{
removePlayer(name, getConfigManager().getDefaultExitLocation());
}
/**
* Retrieves the minimum number of players required to automatically start the round.
* @return the minimum number of players required to automatically start the round.
* @since 0.2.0
*/
public int getMinPlayers(){
return minPlayers;
}
/**
* Sets the minimum number of players required to automatically start the round.
* @param players the minimum number of players required to automatically start the round.
* @since 0.2.0
*/
public void setMinPlayers(int players){
this.minPlayers = players;
}
/**
* Retrieves the maximum number of players allowed in a round at once.
* @return the maximum number of players allowed in a round at once.
* @since 0.1.0
*/
public int getMaxPlayers(){
return maxPlayers;
}
/**
* Sets the maximum number of players allowed in a round at once.
* @param players the maximum number of players allowed in a round at once.
* @since 0.1.0
*/
public void setMaxPlayers(int players){
this.maxPlayers = players;
}
/**
* Creates a new LobbySign to be managed
* @param location The location to create the sign at.
* @param type The type of the sign ("status" or "players")
* @param index The number of the sign (applicable only for "players" signs)
* @throws ArenaNotExistsException if the specified arena does not exist.
* @throws InvalidLocationException if the specified location does not contain a sign.
* @throws IndexOutOfBoundsException if the specified index for a player sign is less than 1.
* @since 0.1.0
*/
public void addSign(Location location, LobbyType type, int index)
throws ArenaNotExistsException, InvalidLocationException, IndexOutOfBoundsException {
this.getMinigame().getLobbyManager().add(location, this.getArena(), type, index);
}
/**
* Updates all lobby signs linked to this round's arena.
* @since 0.1.0
*/
public void updateSigns(){
this.getMinigame().getLobbyManager().update(arena);
}
/**
* Retrieves this round's exit location.
* @return this round's exit location.
* @since 0.1.0
*/
public Location getExitLocation(){
return exitLocation;
}
/**
* Sets this round's exit location.
* @param location the new exit location for this round.
* @since 0.1.0
*/
public void setExitLocation(Location location){
this.exitLocation = location;
}
/**
* Retrieves whether PvP is allowed.
* @return whether PvP is allowed.
* @since 0.1.0
*/
public boolean isPvPAllowed(){
return pvp;
}
/**
* Sets whether PvP is allowed.
* @param allowed whether PvP is allowed.
* @since 0.1.0
*/
public void setPvPAllowed(boolean allowed){
this.pvp = allowed;
}
/**
* Retrieves whether players in rounds may receive damage. (default: true)
* @return whether players in rounds may receive damage.
* @since 0.1.0
*/
public boolean isDamageAllowed(){
return damage;
}
/**
* Sets whether players in rounds may receive damage. (default: false)
* @param allowed whether players in rounds may receive damage.
* @since 0.1.0
*/
public void setDamageAllowed(boolean allowed){
this.damage = allowed;
}
/**
* Retrieves whether rollback is enabled in this round.
* @return whether rollback is enabled in this round.
* @since 0.2.0
*/
public boolean isRollbackEnabled(){
return rollback;
}
/**
* Sets whether rollback is enabled by default.
* @param enabled whether rollback is enabled by default.
* @since 0.2.0
*/
public void setRollbackEnabled(boolean enabled){
this.rollback = enabled;
}
/**
* Retrieves the {@link ConfigManager} of the plugin owning this round.
* @return the {@link ConfigManager} of the plugin owning this round.
* @since 0.2.0
*/
public ConfigManager getConfigManager(){
return getMinigame().getConfigManager();
}
/**
* Retrieves the {@link RollbackManager} of the plugin owning this round.
* @return the {@link RollbackManager} of the plugin owning this round.
* @since 0.2.0
*/
public RollbackManager getRollbackManager(){
return getMinigame().getRollbackManager();
}
/**
* Broadcasts a message to all players in this round.
* @param message the message to broadcast.
* @param broadcastToSpectators whether the message should be broadcast to spectators.
* @since 0.2.0
*/
public void broadcast(String message, boolean broadcastToSpectators){
for (MGPlayer p : players.values())
if (!p.isSpectating() || broadcastToSpectators)
p.getBukkitPlayer().sendMessage(message);
}
/**
* Broadcasts a message to all players in this round.
* @param message the message to broadcast.
* @since 0.2.0
*/
public void broadcast(String message){
broadcast(message, true);
}
@Override
public Object getMetadata(String key){
return metadata.get(key);
}
@Override
public void setMetadata(String key, Object value){
metadata.put(key, value);
}
@Override
public void removeMetadata(String key){
metadata.remove(key);
}
@Override
public boolean hasMetadata(String key){
return metadata.containsKey(key);
}
@Override
public HashMap<String, Object> getAllMetadata(){
return metadata;
}
public boolean equals(Object p){
Round r = (Round)p;
return arena.equals(r.getArena());
}
public int hashCode(){
return 41 * (plugin.hashCode() + arena.hashCode() + 41);
}
}
|
package net.jodah.failsafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import net.jodah.failsafe.function.BiPredicate;
import net.jodah.failsafe.function.Predicate;
import net.jodah.failsafe.internal.util.Assert;
import net.jodah.failsafe.util.Duration;
/**
* A policy that defines when retries should be performed.
*
* <p>
* The {@code retryOn} methods describe when a retry should be performed for a particular failure. The {@code retryWhen}
* method describes when a retry should be performed for a particular result. If multiple {@code retryOn} or
* {@code retryWhen} conditions are specified, any matching condition can allow a retry. The {@code abortOn},
* {@code abortWhen} and {@code abortIf} methods describe when retries should be aborted.
*
* @author Jonathan Halterman
*/
public final class RetryPolicy {
static final RetryPolicy NEVER = new RetryPolicy().withMaxRetries(0);
private Duration delay;
private double delayMultiplier;
private Duration maxDelay;
private Duration maxDuration;
private int maxRetries;
private boolean retryableContainsFailureCheck;
private List<BiPredicate<Object, Throwable>> retryablePredicates;
private List<BiPredicate<Object, Throwable>> abortablePredicates;
/**
* Creates a retry policy that always retries with no delay.
*/
public RetryPolicy() {
delay = Duration.NONE;
maxRetries = -1;
abortablePredicates = new ArrayList<BiPredicate<Object, Throwable>>();
retryablePredicates = new ArrayList<BiPredicate<Object, Throwable>>();
}
/**
* Copy constructor.
*/
public RetryPolicy(RetryPolicy rp) {
this.delay = rp.delay;
this.delayMultiplier = rp.delayMultiplier;
this.maxDelay = rp.maxDelay;
this.maxDuration = rp.maxDuration;
this.maxRetries = rp.maxRetries;
this.retryablePredicates = new ArrayList<BiPredicate<Object, Throwable>>(rp.retryablePredicates);
this.abortablePredicates = new ArrayList<BiPredicate<Object, Throwable>>(rp.abortablePredicates);
this.retryableContainsFailureCheck = rp.retryableContainsFailureCheck;
}
/**
* Specifies that retries should be aborted if the {@code completionPredicate} matches the completion result.
*
* @throws NullPointerException if {@code completionPredicate} is null
*/
@SuppressWarnings("unchecked")
public <T> RetryPolicy abortIf(BiPredicate<T, ? extends Throwable> completionPredicate) {
Assert.notNull(completionPredicate, "completionPredicate");
abortablePredicates.add((BiPredicate<Object, Throwable>) completionPredicate);
return this;
}
/**
* Specifies that retries should be aborted if the {@code resultPredicate} matches the result.
*
* @throws NullPointerException if {@code resultPredicate} is null
*/
public <T> RetryPolicy abortIf(Predicate<T> resultPredicate) {
Assert.notNull(resultPredicate, "resultPredicate");
abortablePredicates.add(resultPredicateFor(resultPredicate));
return this;
}
@SuppressWarnings("unchecked")
public RetryPolicy abortOn(Class<? extends Throwable>... failures) {
Assert.notNull(failures, "failures");
Assert.isTrue(failures.length > 0, "Failures cannot be empty");
return abortOn(Arrays.asList(failures));
}
public RetryPolicy abortOn(List<Class<? extends Throwable>> failures) {
Assert.notNull(failures, "failures");
Assert.isTrue(!failures.isEmpty(), "failures cannot be empty");
abortablePredicates.add(failurePredicateFor(failures));
return this;
}
/**
* Specifies that retries should be aborted if the {@code failurePredicate} matches the failure.
*
* @throws NullPointerException if {@code failurePredicate} is null
*/
public RetryPolicy abortOn(Predicate<? extends Throwable> failurePredicate) {
Assert.notNull(failurePredicate, "failurePredicate");
abortablePredicates.add(failurePredicateFor(failurePredicate));
return this;
}
/**
* Specifies that retries should be aborted if the execution result matches the {@code result}.
*/
public RetryPolicy abortWhen(Object result) {
abortablePredicates.add(resultPredicateFor(result));
return this;
}
/**
* Returns whether an execution can be aborted for the {@code result} and {@code failure} according to the policy.
*/
public boolean canAbortFor(Object result, Throwable failure) {
for (BiPredicate<Object, Throwable> predicate : abortablePredicates) {
if (predicate.test(result, failure))
return true;
}
return false;
}
/**
* Returns whether an execution can be retried according to the configured maxRetries and maxDuration.
*/
public boolean canRetry() {
return (maxRetries == -1 || maxRetries > 0) && (maxDuration == null || maxDuration.toNanos() > 0);
}
/**
* Returns whether an execution can be retried for the {@code result} and {@code failure} according to the policy.
*/
public boolean canRetryFor(Object result, Throwable failure) {
if (!canRetry())
return false;
for (BiPredicate<Object, Throwable> predicate : retryablePredicates) {
if (predicate.test(result, failure))
return true;
}
return failure != null && !retryableContainsFailureCheck;
}
/**
* Returns a copy of this RetryPolicy.
*/
public RetryPolicy copy() {
return new RetryPolicy(this);
}
/**
* Returns the delay between retries. Defaults to {@link Duration#NONE}.
*
* @see #withDelay(long, TimeUnit)
* @see #withBackoff(long, long, TimeUnit)
* @see #withBackoff(long, long, TimeUnit, double)
*/
public Duration getDelay() {
return delay;
}
/**
* Returns the delay multiplier for backoff retries.
*
* @see #withBackoff(long, long, TimeUnit, double)
*/
public double getDelayMultiplier() {
return delayMultiplier;
}
/**
* Returns the max delay between backoff retries.
*
* @see #withBackoff(long, long, TimeUnit)
*/
public Duration getMaxDelay() {
return maxDelay;
}
/**
* Returns the max duration to perform retries for.
*
* @see #withMaxDuration(long, TimeUnit)
*/
public Duration getMaxDuration() {
return maxDuration;
}
/**
* Returns the max retries. Defaults to -1, which retries forever.
*
* @see #withMaxRetries(int)
*/
public int getMaxRetries() {
return maxRetries;
}
/**
* Specifies that a retry should occur if the {@code completionPredicate} matches the completion result and the retry
* policy is not exceeded.
*
* @throws NullPointerException if {@code completionPredicate} is null
*/
@SuppressWarnings("unchecked")
public <T> RetryPolicy retryIf(BiPredicate<T, ? extends Throwable> completionPredicate) {
Assert.notNull(completionPredicate, "completionPredicate");
retryableContainsFailureCheck = true;
retryablePredicates.add((BiPredicate<Object, Throwable>) completionPredicate);
return this;
}
/**
* Specifies that a retry should occur if the {@code resultPredicate} matches the result and the retry policy is not
* exceeded.
*
* @throws NullPointerException if {@code resultPredicate} is null
*/
public <T> RetryPolicy retryIf(Predicate<T> resultPredicate) {
Assert.notNull(resultPredicate, "resultPredicate");
retryablePredicates.add(resultPredicateFor(resultPredicate));
return this;
}
@SuppressWarnings("unchecked")
public RetryPolicy retryOn(Class<? extends Throwable>... failures) {
Assert.notNull(failures, "failures");
Assert.isTrue(failures.length > 0, "Failures cannot be empty");
return retryOn(Arrays.asList(failures));
}
public RetryPolicy retryOn(List<Class<? extends Throwable>> failures) {
Assert.notNull(failures, "failures");
Assert.isTrue(!failures.isEmpty(), "failures cannot be empty");
retryableContainsFailureCheck = true;
retryablePredicates.add(failurePredicateFor(failures));
return this;
}
/**
* Specifies that a retry should occur if the {@code failurePredicate} matches the failure and the retry policy is not
* exceeded.
*
* @throws NullPointerException if {@code failurePredicate} is null
*/
public RetryPolicy retryOn(Predicate<? extends Throwable> failurePredicate) {
Assert.notNull(failurePredicate, "failurePredicate");
retryableContainsFailureCheck = true;
retryablePredicates.add(failurePredicateFor(failurePredicate));
return this;
}
/**
* Specifies that a retry should occur if the execution result matches the {@code result} and the retry policy is not
* exceeded.
*/
public RetryPolicy retryWhen(Object result) {
retryablePredicates.add(resultPredicateFor(result));
return this;
}
public RetryPolicy withBackoff(long delay, long maxDelay, TimeUnit timeUnit) {
return withBackoff(delay, maxDelay, timeUnit, 2);
}
public RetryPolicy withBackoff(long delay, long maxDelay, TimeUnit timeUnit, double delayMultiplier) {
Assert.notNull(timeUnit, "timeUnit");
this.delay = new Duration(delay, timeUnit);
this.maxDelay = new Duration(maxDelay, timeUnit);
this.delayMultiplier = delayMultiplier;
Assert.isTrue(this.delay.toNanos() > 0, "The delay must be greater than 0");
if (maxDuration != null)
Assert.state(this.delay.toNanos() < this.maxDuration.toNanos(), "delay must be less than the maxDuration");
Assert.isTrue(this.delay.toNanos() < this.maxDelay.toNanos(), "delay must be less than the maxDelay");
Assert.isTrue(delayMultiplier > 1, "delayMultiplier must be greater than 1");
return this;
}
public RetryPolicy withDelay(long delay, TimeUnit timeUnit) {
Assert.notNull(timeUnit, "timeUnit");
this.delay = new Duration(delay, timeUnit);
Assert.isTrue(this.delay.toNanos() > 0, "delay must be greater than 0");
if (maxDuration != null)
Assert.state(this.delay.toNanos() < maxDuration.toNanos(), "delay must be less than the maxDuration");
Assert.state(maxDelay == null, "Backoff delays have already been set");
return this;
}
public RetryPolicy withMaxDuration(long maxDuration, TimeUnit timeUnit) {
Assert.notNull(timeUnit, "timeUnit");
this.maxDuration = new Duration(maxDuration, timeUnit);
Assert.state(this.maxDuration.toNanos() > delay.toNanos(), "maxDuration must be greater than the delay");
return this;
}
public RetryPolicy withMaxRetries(int maxRetries) {
Assert.isTrue(maxRetries >= -1, "maxRetries must be greater than or equal to -1");
this.maxRetries = maxRetries;
return this;
}
private static BiPredicate<Object, Throwable> resultPredicateFor(Object result) {
return new BiPredicate<Object, Throwable>() {
@Override
public boolean test(Object t, Throwable u) {
return result == null ? t == null : result.equals(t);
}
};
}
@SuppressWarnings("unchecked")
private static <T> BiPredicate<Object, Throwable> resultPredicateFor(Predicate<T> resultPredicate) {
return new BiPredicate<Object, Throwable>() {
@Override
public boolean test(Object t, Throwable u) {
return ((Predicate<Object>) resultPredicate).test(t);
}
};
}
private static BiPredicate<Object, Throwable> failurePredicateFor(List<Class<? extends Throwable>> failures) {
return new BiPredicate<Object, Throwable>() {
@Override
public boolean test(Object t, Throwable u) {
if (u == null)
return false;
for (Class<? extends Throwable> failureType : failures)
if (failureType.isAssignableFrom(u.getClass()))
return true;
return false;
}
};
}
@SuppressWarnings("unchecked")
private static BiPredicate<Object, Throwable> failurePredicateFor(Predicate<? extends Throwable> failurePredicate) {
return new BiPredicate<Object, Throwable>() {
@Override
public boolean test(Object t, Throwable u) {
return u != null && ((Predicate<Throwable>) failurePredicate).test(u);
}
};
}
}
|
package net.sf.jmimemagic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oro.text.perl.Perl5Util;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class MagicMatcher implements Cloneable
{
private static Log log = LogFactory.getLog(MagicMatcher.class);
private ArrayList subMatchers = new ArrayList(0);
private MagicMatch match = null;
/**
* constructor
*/
public MagicMatcher()
{
log.debug("instantiated");
}
/**
* DOCUMENT ME!
*
* @param match DOCUMENT ME!
*/
public void setMatch(MagicMatch match)
{
log.debug("setMatch()");
this.match = match;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public MagicMatch getMatch()
{
log.debug("getMatch()");
return this.match;
}
/**
* test to see if everything is in order for this match
*
* @return whether or not this match has enough data to be valid
*/
public boolean isValid()
{
log.debug("isValid()");
if ((match == null) || (match.getTest() == null)) {
return false;
}
String type = new String(match.getTest().array());
char comparator = match.getComparator();
String description = match.getDescription();
String test = new String(match.getTest().array());
if ((type != null) && !type.equals("") && (comparator != '\0') &&
((comparator == '=') || (comparator == '!') || (comparator == '>') ||
(comparator == '<')) && (description != null) && !description.equals("") &&
(test != null) && !test.equals("")) {
return true;
}
return false;
}
/**
* add a submatch to this magic match
*
* @param m a magic match
*/
public void addSubMatcher(MagicMatcher m)
{
log.debug("addSubMatcher()");
subMatchers.add(m);
}
/**
* set all submatches
*
* @param a a collection of submatches
*/
public void setSubMatchers(Collection a)
{
log.debug("setSubMatchers(): for match '" + match.getDescription() + "'");
subMatchers.clear();
subMatchers.addAll(a);
}
/**
* get all submatches for this magic match
*
* @return a collection of submatches
*/
public Collection getSubMatchers()
{
log.debug("getSubMatchers()");
return subMatchers;
}
/**
* test to see if this match or any submatches match
*
* @param f the file that should be used to test the match
* @param onlyMimeMatch DOCUMENT ME!
*
* @return the deepest magic match object that matched
*
* @throws IOException DOCUMENT ME!
* @throws UnsupportedTypeException DOCUMENT ME!
*/
public MagicMatch test(File f, boolean onlyMimeMatch)
throws IOException, UnsupportedTypeException
{
log.debug("test(File)");
int offset = match.getOffset();
String description = match.getDescription();
String type = match.getType();
String mimeType = match.getMimeType();
log.debug("test(File): testing '" + f.getName() + "' for '" + description + "'");
log.debug("test(File): \n=== BEGIN MATCH INFO ==");
log.debug(match.print());
log.debug("test(File): \n=== END MATCH INFO ====\n");
RandomAccessFile file = null;
file = new RandomAccessFile(f, "r");
try {
int length = 0;
if (type.equals("byte")) {
length = 1;
} else if (type.equals("short") || type.equals("leshort") || type.equals("beshort")) {
length = 4;
} else if (type.equals("long") || type.equals("lelong") || type.equals("belong")) {
length = 8;
} else if (type.equals("string")) {
length = match.getTest().capacity();
} else if (type.equals("regex")) {
final int matchLength = match.getLength();
length = (matchLength == 0) ? (int) file.length() - offset : matchLength;
if (length < 0) {
length = 0;
}
} else if (type.equals("detector")) {
length = (int) file.length() - offset;
if (length < 0) {
length = 0;
}
} else {
throw new UnsupportedTypeException("unsupported test type '" + type + "'");
}
// we know this match won't work since there isn't enough data for the test
if (length > (file.length() - offset)) {
return null;
}
byte[] buf = new byte[length];
file.seek(offset);
int bytesRead = 0;
int size = 0;
boolean gotAllBytes = false;
boolean done = false;
while (!done) {
size = file.read(buf, 0, length - bytesRead);
if (size == -1) {
throw new IOException("reached end of file before all bytes were read");
}
bytesRead += size;
if (bytesRead == length) {
gotAllBytes = true;
done = true;
}
}
log.debug("test(File): stream size is '" + buf.length + "'");
MagicMatch match = null;
MagicMatch submatch = null;
if (testInternal(buf)) {
// set the top level match to this one
try {
match = getMatch() != null ? (MagicMatch) getMatch()
.clone() : null;
} catch (CloneNotSupportedException e) {
// noop
}
log.debug("test(File): testing matched '" + description + "'");
// set the data on this match
if ((onlyMimeMatch == false) && (subMatchers != null) && (subMatchers.size() > 0)) {
log.debug("test(File): testing " + subMatchers.size() + " submatches for '" +
description + "'");
for (int i = 0; i < subMatchers.size(); i++) {
log.debug("test(File): testing submatch " + i);
MagicMatcher m = (MagicMatcher) subMatchers.get(i);
if ((submatch = m.test(f, false)) != null) {
log.debug("test(File): submatch " + i + " matched with '" +
submatch.getDescription() + "'");
match.addSubMatch(submatch);
} else {
log.debug("test(File): submatch " + i + " doesn't match");
}
}
}
}
return match;
} finally {
try {
file.close();
} catch (Exception fce) {
}
}
}
/**
* test to see if this match or any submatches match
*
* @param data the data that should be used to test the match
* @param onlyMimeMatch DOCUMENT ME!
*
* @return the deepest magic match object that matched
*
* @throws IOException DOCUMENT ME!
* @throws UnsupportedTypeException DOCUMENT ME!
*/
public MagicMatch test(byte[] data, boolean onlyMimeMatch)
throws IOException, UnsupportedTypeException
{
log.debug("test(byte[])");
int offset = match.getOffset();
String description = match.getDescription();
String type = match.getType();
String test = new String(match.getTest().array());
String mimeType = match.getMimeType();
log.debug("test(byte[]): testing byte[] data for '" + description + "'");
log.debug("test(byte[]): \n=== BEGIN MATCH INFO ==");
log.debug(match.print());
log.debug("test(byte[]): \n=== END MATCH INFO ====\n");
int length = 0;
if (type.equals("byte")) {
length = 1;
} else if (type.equals("short") || type.equals("leshort") || type.equals("beshort")) {
length = 4;
} else if (type.equals("long") || type.equals("lelong") || type.equals("belong")) {
length = 8;
} else if (type.equals("string")) {
length = match.getTest().capacity();
} else if (type.equals("regex")) {
// FIXME - something wrong here, shouldn't have to subtract 1???
length = data.length - offset - 1;
if (length < 0) {
length = 0;
}
} else if (type.equals("detector")) {
// FIXME - something wrong here, shouldn't have to subtract 1???
length = data.length - offset - 1;
if (length < 0) {
length = 0;
}
} else {
throw new UnsupportedTypeException("unsupported test type " + type);
}
byte[] buf = new byte[length];
log.debug("test(byte[]): offset=" + offset + ",length=" + length + ",data length=" +
data.length);
if ((offset + length) < data.length) {
System.arraycopy(data, offset, buf, 0, length);
log.debug("test(byte[]): stream size is '" + buf.length + "'");
MagicMatch match = null;
MagicMatch submatch = null;
if (testInternal(buf)) {
// set the top level match to this one
try {
match = getMatch() != null ? (MagicMatch) getMatch()
.clone() : null;
} catch (CloneNotSupportedException e) {
// noop
}
log.debug("test(byte[]): testing matched '" + description + "'");
// set the data on this match
if ((onlyMimeMatch == false) && (subMatchers != null) && (subMatchers.size() > 0)) {
log.debug("test(byte[]): testing " + subMatchers.size() + " submatches for '" +
description + "'");
for (int i = 0; i < subMatchers.size(); i++) {
log.debug("test(byte[]): testing submatch " + i);
MagicMatcher m = (MagicMatcher) subMatchers.get(i);
if ((submatch = m.test(data, false)) != null) {
log.debug("test(byte[]): submatch " + i + " matched with '" +
submatch.getDescription() + "'");
match.addSubMatch(submatch);
} else {
log.debug("test(byte[]): submatch " + i + " doesn't match");
}
}
}
}
return match;
} else {
return null;
}
}
/**
* internal test switch
*
* @param data DOCUMENT ME!
* @return DOCUMENT ME!
*/
private boolean testInternal(byte[] data)
{
log.debug("testInternal(byte[])");
if (data.length == 0) {
return false;
}
String type = match.getType();
String test = new String(match.getTest().array());
String mimeType = match.getMimeType();
String description = match.getDescription();
ByteBuffer buffer = ByteBuffer.allocate(data.length);
if ((type != null) && (test != null) && (test.length() > 0)) {
if (type.equals("string")) {
buffer = buffer.put(data);
return testString(buffer);
} else if (type.equals("byte")) {
buffer = buffer.put(data);
return testByte(buffer);
} else if (type.equals("short")) {
buffer = buffer.put(data);
return testShort(buffer);
} else if (type.equals("leshort")) {
buffer = buffer.put(data);
buffer.order(ByteOrder.LITTLE_ENDIAN);
return testShort(buffer);
} else if (type.equals("beshort")) {
buffer = buffer.put(data);
buffer.order(ByteOrder.BIG_ENDIAN);
return testShort(buffer);
} else if (type.equals("long")) {
buffer = buffer.put(data);
return testLong(buffer);
} else if (type.equals("lelong")) {
buffer = buffer.put(data);
buffer.order(ByteOrder.LITTLE_ENDIAN);
return testLong(buffer);
} else if (type.equals("belong")) {
buffer = buffer.put(data);
buffer.order(ByteOrder.BIG_ENDIAN);
return testLong(buffer);
} else if (type.equals("regex")) {
return testRegex(new String(data));
} else if (type.equals("detector")) {
buffer = buffer.put(data);
return testDetector(buffer);
// } else if (type.equals("date")) {
// return testDate(data, BIG_ENDIAN);
// } else if (type.equals("ledate")) {
// return testDate(data, LITTLE_ENDIAN);
// } else if (type.equals("bedate")) {
// return testDate(data, BIG_ENDIAN);
} else {
log.error("testInternal(byte[]): invalid test type '" + type + "'");
}
} else {
log.error("testInternal(byte[]): type or test is empty for '" + mimeType + " - " +
description + "'");
}
return false;
}
/**
* test the data against the test byte
*
* @param data the data we are testing
*
* @return if we have a match
*/
private boolean testByte(ByteBuffer data)
{
log.debug("testByte()");
String test = new String(match.getTest().array());
char comparator = match.getComparator();
long bitmask = match.getBitmask();
String s = test;
byte b = data.get(0);
b = (byte) (b & bitmask);
log.debug("testByte(): decoding '" + test + "' to byte");
int tst = Integer.decode(test).byteValue();
byte t = (byte) (tst & 0xff);
log.debug("testByte(): applying bitmask '" + bitmask + "' to '" + tst + "', result is '" +
t + "'");
log.debug("testByte(): comparing byte '" + b + "' to '" + t + "'");
switch (comparator) {
case '=':
return t == b;
case '!':
return t != b;
case '>':
return t > b;
case '<':
return t < b;
}
return false;
}
/**
* test the data against the byte array
*
* @param data the data we are testing
*
* @return if we have a match
*/
private boolean testString(ByteBuffer data)
{
log.debug("testString()");
ByteBuffer test = match.getTest();
char comparator = match.getComparator();
byte[] b = data.array();
byte[] t = test.array();
boolean diff = false;
int i = 0;
for (i = 0; i < t.length; i++) {
log.debug("testing byte '" + b[i] + "' from '" + new String(data.array()) +
"' against byte '" + t[i] + "' from '" + new String(test.array()) + "'");
if (t[i] != b[i]) {
diff = true;
break;
}
}
switch (comparator) {
case '=':
return !diff;
case '!':
return diff;
case '>':
return t[i] > b[i];
case '<':
return t[i] < b[i];
}
return false;
}
/**
* test the data against a short
*
* @param data the data we are testing
*
* @return if we have a match
*/
private boolean testShort(ByteBuffer data)
{
log.debug("testShort()");
short val = 0;
String test = new String(match.getTest().array());
char comparator = match.getComparator();
long bitmask = match.getBitmask();
val = byteArrayToShort(data);
// apply bitmask before the comparison
val = (short) (val & (short) bitmask);
short tst = 0;
try {
tst = Integer.decode(test).shortValue();
} catch (NumberFormatException e) {
log.error("testShort(): " + e);
return false;
//if (test.length() == 1) {
// tst = new Integer(Character.getNumericValue(test.charAt(0))).shortValue();
}
log.debug("testShort(): testing '" + Long.toHexString(val) + "' against '" +
Long.toHexString(tst) + "'");
switch (comparator) {
case '=':
return val == tst;
case '!':
return val != tst;
case '>':
return val > tst;
case '<':
return val < tst;
}
return false;
}
/**
* test the data against a long
*
* @param data the data we are testing
*
* @return if we have a match
*/
private boolean testLong(ByteBuffer data)
{
log.debug("testLong()");
long val = 0;
String test = new String(match.getTest().array());
char comparator = match.getComparator();
long bitmask = match.getBitmask();
val = byteArrayToLong(data);
// apply bitmask before the comparison
val = val & bitmask;
long tst = Long.decode(test).longValue();
log.debug("testLong(): testing '" + Long.toHexString(val) + "' against '" + test +
"' => '" + Long.toHexString(tst) + "'");
switch (comparator) {
case '=':
return val == tst;
case '!':
return val != tst;
case '>':
return val > tst;
case '<':
return val < tst;
}
return false;
}
/**
* test the data against a regex
*
* @param text the data we are testing
*
* @return if we have a match
*/
private boolean testRegex(String text)
{
log.debug("testRegex()");
String test = new String(match.getTest().array());
char comparator = match.getComparator();
Perl5Util utility = new Perl5Util();
log.debug("testRegex(): searching for '" + test + "'");
if (comparator == '=') {
if (utility.match(test, text)) {
return true;
} else {
return false;
}
} else if (comparator == '!') {
if (utility.match(test, text)) {
return false;
} else {
return true;
}
}
return false;
}
/**
* test the data using a detector
*
* @param data the data we are testing
*
* @return if we have a match
*/
private boolean testDetector(ByteBuffer data)
{
log.debug("testDetector()");
String detectorClass = new String(match.getTest().array());
try {
log.debug("loading class: " + detectorClass);
Class c = Class.forName(detectorClass);
MagicDetector detector = (MagicDetector) c.newInstance();
String[] types = detector.process(data.array(), match.getOffset(), match.getLength(),
match.getBitmask(), match.getComparator(), match.getMimeType(),
match.getProperties());
if ((types != null) && (types.length > 0)) {
// the match object has no mime type set, so set from the detector class processing
match.setMimeType(types[0]);
return true;
}
} catch (ClassNotFoundException e) {
log.error("failed to load detector: " + detectorClass, e);
} catch (InstantiationException e) {
log.error("specified class is not a valid detector class: " + detectorClass, e);
} catch (IllegalAccessException e) {
log.error("specified class cannot be accessed: " + detectorClass, e);
}
return false;
}
/**
* Get the extensions for the underlying detectory
*
* @return DOCUMENT ME!
*/
public String[] getDetectorExtensions()
{
log.debug("testDetector()");
String detectorClass = new String(match.getTest().array());
try {
log.debug("loading class: " + detectorClass);
Class c = Class.forName(detectorClass);
MagicDetector detector = (MagicDetector) c.newInstance();
return detector.getHandledTypes();
} catch (ClassNotFoundException e) {
log.error("failed to load detector: " + detectorClass, e);
} catch (InstantiationException e) {
log.error("specified class is not a valid detector class: " + detectorClass, e);
} catch (IllegalAccessException e) {
log.error("specified class cannot be accessed: " + detectorClass, e);
}
return new String[0];
}
/**
* encode a byte as an octal string
*
* @param b a byte of data
*
* @return an octal representation of the byte data
*/
private String byteToOctalString(byte b)
{
int n1;
int n2;
int n3;
n1 = (b / 32) & 7;
n2 = (b / 8) & 7;
n3 = b & 7;
return String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3);
}
/**
* convert a byte array to a short
*
* @param data buffer of byte data
*
* @return byte array converted to a short
*/
private short byteArrayToShort(ByteBuffer data)
{
return data.getShort(0);
}
/**
* convert a byte array to a long
*
* @param data buffer of byte data
*
* @return byte arrays (high and low bytes) converted to a long value
*/
private long byteArrayToLong(ByteBuffer data)
{
return (long) data.getInt(0);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws CloneNotSupportedException DOCUMENT ME!
*/
protected Object clone()
throws CloneNotSupportedException
{
MagicMatcher clone = new MagicMatcher();
clone.setMatch((MagicMatch) match.clone());
Iterator i = subMatchers.iterator();
ArrayList sub = new ArrayList();
while (i.hasNext()) {
MagicMatcher m = (MagicMatcher) i.next();
sub.add(m.clone());
}
clone.setSubMatchers(sub);
return clone;
}
}
|
package net.simpvp.Events;
import java.util.Collection;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scoreboard.Team;
/** This class is responsible for handling the /event command.
*
* Saves all the player's information.
* Teleports users to the set starting location of the event.
* And prepares them for the event. */
public class EventCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
/* Command sender must be an ingame player */
if (player == null) {
Events.instance.getLogger().info("You must be a player to use this command.");
return true;
}
/* Event must be active */
if (!Event.getIsActive()) {
player.sendMessage(ChatColor.RED + "Event is currently closed for new contestants.\n"
+ "Please wait until the next event starts.");
return true;
}
/* If the event is not setup yet */
if (!Event.getIsComplete()) {
sender.sendMessage(ChatColor.RED + "Woops. Looks like the event is set to active,\n" +
"but I'm missing some information about the event.\n" +
"Please tell the nice admin that they're missing something :)");
return true;
}
if (player.isInsideVehicle()) {
sender.sendMessage(ChatColor.RED + "You cannot join events while in a vehicle.");
return true;
}
if (player.getLocation().getY() < 0.0) {
sender.sendMessage(ChatColor.RED + "You cannot join events from your current location.");
return true;
}
if (player.isOp()) {
player.performCommand("rg bypass off");
}
UUID uuid = player.getUniqueId();
/* Everything seems to be in order. Saving all player info for when the event is over */
if (!Event.isPlayerActive(uuid)) {
save_player_data(player);
}
/* Now we reset all their stuff and teleport them off */
player.setFoodLevel(20);
player.setLevel(0);
player.setExp(0);
player.getInventory().clear();
player.getInventory().setArmorContents(null);
player.setHealth(player.getMaxHealth());
for (PotionEffect potionEffect : player.getActivePotionEffects())
player.removePotionEffect(potionEffect.getType());
player.setGameMode(GameMode.SURVIVAL);
player.teleport(Event.getStartLocation());
/* Leave current team. Doesn't save it, but maybe it should? */
Team team = player.getScoreboard().getPlayerTeam(player);
if (team != null) {
team.removePlayer(player);
}
player.sendMessage(ChatColor.AQUA + "Teleporting you to the event arena."
+ "\nWhen you die, you will be teleported back with all your items and XP in order.");
return true;
}
private void save_player_data(Player player) {
String sPlayer = player.getName();
Location playerLocation = player.getLocation();
int playerFoodLevel = player.getFoodLevel();
int playerLevel = player.getLevel();
float playerXP = player.getExp();
ItemStack[] armorContents = player.getInventory().getArmorContents();
ItemStack[] inventoryContents = player.getInventory().getContents();
Double playerHealth = player.getHealth();
Collection<PotionEffect> potionEffects = player.getActivePotionEffects();
GameMode gameMode = player.getGameMode();
/* Save all this data */
EventPlayer eventPlayer = new EventPlayer(player.getUniqueId(), sPlayer, playerLocation, playerFoodLevel, playerLevel, playerXP, armorContents, inventoryContents, playerHealth, potionEffects, gameMode, false);
eventPlayer.save();
/* Log it all, just in case */
String sInventoryContents = "";
for (ItemStack itemStack : inventoryContents) {
if (itemStack == null)
continue;
String tmp = itemStack.getType().toString()
+ "." + itemStack.getAmount()
+ "." + itemStack.getDurability()
+ "." + itemStack.getEnchantments().toString();
tmp = tmp.replaceAll(" ", "");
sInventoryContents += " " + tmp;
}
Events.instance.getLogger().info(sPlayer + " is participating in event: " + playerLevel + sInventoryContents);
}
}
|
package org.basex.query.expr;
import static org.basex.query.QueryText.*;
import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.value.*;
import org.basex.query.value.node.*;
import org.basex.util.*;
public final class Extension extends Single {
/** Pragmas of the ExtensionExpression. */
private final Pragma[] pragmas;
/**
* Constructor.
* @param ii input info
* @param prag pragmas
* @param e enclosed expression
*/
public Extension(final InputInfo ii, final Pragma[] prag, final Expr e) {
super(ii, e);
pragmas = prag;
}
@Override
public void checkUp() throws QueryException {
expr.checkUp();
}
@Override
public Expr compile(final QueryContext ctx) throws QueryException {
try {
for(final Pragma p : pragmas) p.init(ctx, info);
expr = expr.compile(ctx);
} finally {
for(final Pragma p : pragmas) p.finish(ctx);
}
return this;
}
@Override
public ValueIter iter(final QueryContext ctx) throws QueryException {
return value(ctx).iter(ctx);
}
@Override
public Value value(final QueryContext ctx) throws QueryException {
try {
for(final Pragma p : pragmas) p.init(ctx, info);
return ctx.value(expr);
} finally {
for(final Pragma p : pragmas) p.finish(ctx);
}
}
@Override
public void plan(final FElem plan) {
addPlan(plan, planElem(), pragmas, expr);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for(final Pragma p : pragmas) sb.append(p).append(' ');
return sb.append(BRACE1 + ' ' + expr + ' ' + BRACE2).toString();
}
@Override
public Expr markTailCalls() {
expr = expr.markTailCalls();
return this;
}
}
|
package org.dynmap.bukkit;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Future;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.world.ChunkPopulateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Tree;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.DynmapAPI;
import org.dynmap.DynmapChunk;
import org.dynmap.DynmapCore;
import org.dynmap.DynmapLocation;
import org.dynmap.DynmapWebChatEvent;
import org.dynmap.DynmapWorld;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.MapType;
import org.dynmap.PlayerList;
import org.dynmap.bukkit.permissions.BukkitPermissions;
import org.dynmap.bukkit.permissions.NijikokunPermissions;
import org.dynmap.bukkit.permissions.OpPermissions;
import org.dynmap.bukkit.permissions.PEXPermissions;
import org.dynmap.bukkit.permissions.PermBukkitPermissions;
import org.dynmap.bukkit.permissions.PermissionProvider;
import org.dynmap.bukkit.permissions.bPermPermissions;
import org.dynmap.common.BiomeMap;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.common.DynmapServerInterface;
import org.dynmap.common.DynmapListenerManager.EventType;
import org.dynmap.hdmap.HDMap;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.utils.MapChunkCache;
public class DynmapPlugin extends JavaPlugin implements DynmapAPI {
private DynmapCore core;
private PermissionProvider permissions;
private String version;
public SnapshotCache sscache;
private boolean has_spout = false;
public PlayerList playerList;
private MapManager mapManager;
public static DynmapPlugin plugin;
public SpoutPluginBlocks spb;
public PluginManager pm;
private Metrics metrics;
private BukkitEnableCoreCallback enabCoreCB = new BukkitEnableCoreCallback();
private Method ismodloaded;
private class BukkitEnableCoreCallback extends DynmapCore.EnableCoreCallbacks {
@Override
public void configurationLoaded() {
/* Check for Spout */
if(detectSpout()) {
if(core.configuration.getBoolean("spout/enabled", true)) {
has_spout = true;
Log.info("Detected Spout");
if(spb == null) {
spb = new SpoutPluginBlocks(DynmapPlugin.this);
}
}
else {
Log.info("Detected Spout - Support Disabled");
}
}
if(!has_spout) { /* If not, clean up old spout texture, if needed */
File st = new File(core.getDataFolder(), "renderdata/spout-texture.txt");
if(st.exists())
st.delete();
}
}
}
private static class BlockToCheck {
Location loc;
int typeid;
byte data;
String trigger;
};
private LinkedList<BlockToCheck> blocks_to_check = null;
private LinkedList<BlockToCheck> blocks_to_check_accum = new LinkedList<BlockToCheck>();
public DynmapPlugin() {
plugin = this;
try {
Class<?> c = Class.forName("cpw.mods.fml.common.Loader");
ismodloaded = c.getMethod("isModLoaded", String.class);
} catch (NoSuchMethodException nsmx) {
} catch (ClassNotFoundException e) {
}
}
/**
* Server access abstraction class
*/
public class BukkitServer implements DynmapServerInterface {
/* Chunk load handling */
private Object loadlock = new Object();
private int chunks_in_cur_tick = 0;
private long cur_tick;
@Override
public void scheduleServerTask(Runnable run, long delay) {
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay);
}
@Override
public DynmapPlayer[] getOnlinePlayers() {
Player[] players = getServer().getOnlinePlayers();
DynmapPlayer[] dplay = new DynmapPlayer[players.length];
for(int i = 0; i < players.length; i++)
dplay[i] = new BukkitPlayer(players[i]);
return dplay;
}
@Override
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.disablePlugin(DynmapPlugin.this);
pluginManager.enablePlugin(DynmapPlugin.this);
}
@Override
public DynmapPlayer getPlayer(String name) {
Player p = getServer().getPlayerExact(name);
if(p != null) {
return new BukkitPlayer(p);
}
return null;
}
@Override
public Set<String> getIPBans() {
return getServer().getIPBans();
}
@Override
public <T> Future<T> callSyncMethod(Callable<T> task) {
return getServer().getScheduler().callSyncMethod(DynmapPlugin.this, task);
}
@Override
public String getServerName() {
return getServer().getServerName();
}
@Override
public boolean isPlayerBanned(String pid) {
OfflinePlayer p = getServer().getOfflinePlayer(pid);
if((p != null) && p.isBanned())
return true;
return false;
}
@Override
public String stripChatColor(String s) {
return ChatColor.stripColor(s);
}
private Set<EventType> registered = new HashSet<EventType>();
@Override
public boolean requestEventNotification(EventType type) {
if(registered.contains(type))
return true;
switch(type) {
case WORLD_LOAD:
case WORLD_UNLOAD:
/* Already called for normal world activation/deactivation */
break;
case WORLD_SPAWN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onSpawnChange(SpawnChangeEvent evt) {
DynmapWorld w = new BukkitWorld(evt.getWorld());
core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w);
}
}, DynmapPlugin.this);
break;
case PLAYER_JOIN:
case PLAYER_QUIT:
/* Already handled */
break;
case PLAYER_BED_LEAVE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerBedLeave(PlayerBedLeaveEvent evt) {
DynmapPlayer p = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p);
}
}, DynmapPlugin.this);
break;
case PLAYER_CHAT:
try {
Class.forName("org.bukkit.event.player.AsyncPlayerChatEvent");
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent evt) {
if(evt.isCancelled()) return;
final Player p = evt.getPlayer();
final String msg = evt.getMessage();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() {
public void run() {
DynmapPlayer dp = null;
if(p != null)
dp = new BukkitPlayer(p);
core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, dp, msg);
}
});
}
}, DynmapPlugin.this);
} catch (ClassNotFoundException cnfx) {
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerChat(PlayerChatEvent evt) {
if(evt.isCancelled()) return;
DynmapPlayer p = null;
if(evt.getPlayer() != null)
p = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, p, evt.getMessage());
}
}, DynmapPlugin.this);
}
break;
case BLOCK_BREAK:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent evt) {
if(evt.isCancelled()) return;
Block b = evt.getBlock();
if(b == null) return; /* Work around for stupid mods.... */
Location l = b.getLocation();
core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getType().getId(),
BukkitWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
}, DynmapPlugin.this);
break;
case SIGN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onSignChange(SignChangeEvent evt) {
if(evt.isCancelled()) return;
Block b = evt.getBlock();
Location l = b.getLocation();
String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */
DynmapPlayer dp = null;
Player p = evt.getPlayer();
if(p != null) dp = new BukkitPlayer(p);
core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().getId(),
BukkitWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp);
}
}, DynmapPlugin.this);
break;
default:
Log.severe("Unhandled event type: " + type);
return false;
}
registered.add(type);
return true;
}
@Override
public boolean sendWebChatEvent(String source, String name, String msg) {
DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg);
getServer().getPluginManager().callEvent(evt);
return ((evt.isCancelled() == false) && (evt.isProcessed() == false));
}
@Override
public void broadcastMessage(String msg) {
getServer().broadcastMessage(msg);
}
@Override
public String[] getBiomeIDs() {
BiomeMap[] b = BiomeMap.values();
String[] bname = new String[b.length];
for(int i = 0; i < bname.length; i++)
bname[i] = b[i].toString();
return bname;
}
@Override
public double getCacheHitRate() {
return sscache.getHitRate();
}
@Override
public void resetCacheStats() {
sscache.resetStats();
}
@Override
public DynmapWorld getWorldByName(String wname) {
World w = getServer().getWorld(wname); /* FInd world */
if(w != null) {
return new BukkitWorld(w);
}
return null;
}
@Override
public DynmapPlayer getOfflinePlayer(String name) {
OfflinePlayer op = getServer().getOfflinePlayer(name);
if(op != null) {
return new BukkitPlayer(op);
}
return null;
}
@Override
public Set<String> checkPlayerPermissions(String player, Set<String> perms) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if(p.isBanned())
return new HashSet<String>();
Set<String> rslt = permissions.hasOfflinePermissions(player, perms);
if (rslt == null) {
rslt = new HashSet<String>();
if(p.isOp()) {
rslt.addAll(perms);
}
}
return rslt;
}
@Override
public boolean checkPlayerPermission(String player, String perm) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if(p.isBanned())
return false;
return permissions.hasOfflinePermission(player, perm);
}
/**
* Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread
*/
@Override
public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) {
MapChunkCache c = w.getChunkCache(chunks);
if(w.visibility_limits != null) {
for(MapChunkCache.VisibilityLimit limit: w.visibility_limits) {
c.setVisibleRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
c.setAutoGenerateVisbileRanges(w.do_autogenerate);
}
if(w.hidden_limits != null) {
for(MapChunkCache.VisibilityLimit limit: w.hidden_limits) {
c.setHiddenRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) {
Log.severe("CraftBukkit build does not support biome APIs");
}
if(chunks.size() == 0) { /* No chunks to get? */
c.loadChunks(0);
return c;
}
final MapChunkCache cc = c;
while(!cc.isDoneLoading()) {
synchronized(loadlock) {
long now = System.currentTimeMillis();
if(cur_tick != (now/50)) { /* New tick? */
chunks_in_cur_tick = mapManager.getMaxChunkLoadsPerTick();
cur_tick = now/50;
}
}
Future<Boolean> f = core.getServer().callSyncMethod(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean exhausted;
synchronized(loadlock) {
if(chunks_in_cur_tick > 0)
chunks_in_cur_tick -= cc.loadChunks(chunks_in_cur_tick);
exhausted = (chunks_in_cur_tick == 0);
}
return exhausted;
}
});
Boolean delay;
try {
delay = f.get();
} catch (CancellationException cx) {
return null;
} catch (Exception ix) {
Log.severe(ix);
return null;
}
if((delay != null) && delay.booleanValue()) {
try { Thread.sleep(25); } catch (InterruptedException ix) {}
}
}
return c;
}
@Override
public int getMaxPlayers() {
return getServer().getMaxPlayers();
}
@Override
public int getCurrentPlayers() {
return getServer().getOnlinePlayers().length;
}
@Override
public boolean isModLoaded(String name) {
if(ismodloaded != null) {
try {
Object rslt =ismodloaded.invoke(null, name);
if(rslt instanceof Boolean) {
if(((Boolean)rslt).booleanValue()) {
return true;
}
}
} catch (IllegalArgumentException iax) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return false;
}
}
/**
* Player access abstraction class
*/
public class BukkitPlayer extends BukkitCommandSender implements DynmapPlayer {
private Player player;
private OfflinePlayer offplayer;
public BukkitPlayer(Player p) {
super(p);
player = p;
offplayer = p.getPlayer();
}
public BukkitPlayer(OfflinePlayer p) {
super(null);
offplayer = p;
}
@Override
public boolean isConnected() {
return offplayer.isOnline();
}
@Override
public String getName() {
return offplayer.getName();
}
@Override
public String getDisplayName() {
if(player != null)
return player.getDisplayName();
else
return offplayer.getName();
}
@Override
public boolean isOnline() {
return offplayer.isOnline();
}
@Override
public DynmapLocation getLocation() {
if(player == null) {
return null;
}
Location loc = player.getEyeLocation(); // Use eye location, since we show head
return toLoc(loc);
}
@Override
public String getWorld() {
if(player == null) {
return null;
}
World w = player.getWorld();
if(w != null)
return BukkitWorld.normalizeWorldName(w.getName());
return null;
}
@Override
public InetSocketAddress getAddress() {
if(player != null)
return player.getAddress();
return null;
}
@Override
public boolean isSneaking() {
if(player != null)
return player.isSneaking();
return false;
}
@Override
public int getHealth() {
if(player != null)
return player.getHealth();
else
return 0;
}
@Override
public int getArmorPoints() {
if(player != null)
return Armor.getArmorPoints(player);
else
return 0;
}
@Override
public DynmapLocation getBedSpawnLocation() {
Location loc = offplayer.getBedSpawnLocation();
if(loc != null) {
return toLoc(loc);
}
return null;
}
@Override
public long getLastLoginTime() {
return offplayer.getLastPlayed();
}
@Override
public long getFirstLoginTime() {
return offplayer.getFirstPlayed();
}
}
/* Handler for generic console command sender */
public class BukkitCommandSender implements DynmapCommandSender {
private CommandSender sender;
public BukkitCommandSender(CommandSender send) {
sender = send;
}
@Override
public boolean hasPrivilege(String privid) {
if(sender != null)
return permissions.has(sender, privid);
return false;
}
@Override
public void sendMessage(String msg) {
if(sender != null)
sender.sendMessage(msg);
}
@Override
public boolean isConnected() {
if(sender != null)
return true;
return false;
}
@Override
public boolean isOp() {
if(sender != null)
return sender.isOp();
else
return false;
}
}
@Override
public void onEnable() {
pm = this.getServer().getPluginManager();
PluginDescriptionFile pdfFile = this.getDescription();
version = pdfFile.getVersion();
/* Set up player login/quit event handler */
registerPlayerLoginListener();
Map<String, Boolean> perdefs = new HashMap<String, Boolean>();
List<Permission> pd = plugin.getDescription().getPermissions();
for(Permission p : pd) {
perdefs.put(p.getName(), p.getDefault() == PermissionDefault.TRUE);
}
permissions = PEXPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = bPermPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = PermBukkitPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = NijikokunPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = BukkitPermissions.create("dynmap", perdefs);
if (permissions == null)
permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload", "purgequeue", "pause", "ips-for-id", "ids-for-ip", "add-id-for-ip", "del-id-for-ip" });
/* Get and initialize data folder */
File dataDirectory = this.getDataFolder();
if(dataDirectory.exists() == false)
dataDirectory.mkdirs();
/* Get MC version */
String bukkitver = getServer().getVersion();
String mcver = "1.0.0";
int idx = bukkitver.indexOf("(MC: ");
if(idx > 0) {
mcver = bukkitver.substring(idx+5);
idx = mcver.indexOf(")");
if(idx > 0) mcver = mcver.substring(0, idx);
}
/* Instantiate core */
if(core == null)
core = new DynmapCore();
/* Inject dependencies */
core.setPluginVersion(version);
core.setMinecraftVersion(mcver);
core.setDataFolder(dataDirectory);
core.setServer(new BukkitServer());
/* Load configuration */
if(!core.initConfiguration(enabCoreCB)) {
this.setEnabled(false);
return;
}
/* See if we need to wait before enabling core */
if(!readyToEnable()) {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPluginEnabled(PluginEnableEvent evt) {
if (!readyToEnable()) {
spb.markPluginEnabled(evt.getPlugin());
if (readyToEnable()) { /* If we;re ready now, finish enable */
doEnable(); /* Finish enable */
}
}
}
};
pm.registerEvents(pl, this);
}
else {
doEnable();
}
}
private boolean readyToEnable() {
if (spb != null) {
return spb.isReady();
}
return true;
}
private void doEnable() {
/* Prep spout support, if needed */
if(spb != null) {
spb.processSpoutBlocks(this, core);
}
/* Enable core */
if(!core.enableCore(enabCoreCB)) {
this.setEnabled(false);
return;
}
playerList = core.playerList;
sscache = new SnapshotCache(core.getSnapShotCacheSize());
/* Get map manager from core */
mapManager = core.getMapManager();
/* Initialized the currently loaded worlds */
for (World world : getServer().getWorlds()) {
BukkitWorld w = new BukkitWorld(world);
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
/* Register our update trigger events */
registerEvents();
/* Submit metrics to mcstats.org */
initMetrics();
Log.info("Enabled");
}
@Override
public void onDisable() {
if (metrics != null) {
metrics = null;
}
/* Disable core */
core.disableCore();
if(sscache != null) {
sscache.cleanup();
sscache = null;
}
Log.info("Disabled");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
DynmapCommandSender dsender;
if(sender instanceof Player) {
dsender = new BukkitPlayer((Player)sender);
}
else {
dsender = new BukkitCommandSender(sender);
}
return core.processCommand(dsender, cmd.getName(), commandLabel, args);
}
@Override
public final MarkerAPI getMarkerAPI() {
return core.getMarkerAPI();
}
@Override
public final boolean markerAPIInitialized() {
return core.markerAPIInitialized();
}
@Override
public final boolean sendBroadcastToWeb(String sender, String msg) {
return core.sendBroadcastToWeb(sender, msg);
}
@Override
public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz,
int maxx, int maxy, int maxz) {
return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz);
}
@Override
public final int triggerRenderOfBlock(String wid, int x, int y, int z) {
return core.triggerRenderOfBlock(wid, x, y, z);
}
@Override
public final void setPauseFullRadiusRenders(boolean dopause) {
core.setPauseFullRadiusRenders(dopause);
}
@Override
public final boolean getPauseFullRadiusRenders() {
return core.getPauseFullRadiusRenders();
}
@Override
public final void setPauseUpdateRenders(boolean dopause) {
core.setPauseUpdateRenders(dopause);
}
@Override
public final boolean getPauseUpdateRenders() {
return core.getPauseUpdateRenders();
}
@Override
public final void setPlayerVisiblity(String player, boolean is_visible) {
core.setPlayerVisiblity(player, is_visible);
}
@Override
public final boolean getPlayerVisbility(String player) {
return core.getPlayerVisbility(player);
}
@Override
public final void postPlayerMessageToWeb(String playerid, String playerdisplay,
String message) {
core.postPlayerMessageToWeb(playerid, playerdisplay, message);
}
@Override
public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay,
boolean isjoin) {
core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin);
}
@Override
public final String getDynmapCoreVersion() {
return core.getDynmapCoreVersion();
}
@Override
public final int triggerRenderOfVolume(Location l0, Location l1) {
int x0 = l0.getBlockX(), y0 = l0.getBlockY(), z0 = l0.getBlockZ();
int x1 = l1.getBlockX(), y1 = l1.getBlockY(), z1 = l1.getBlockZ();
return core.triggerRenderOfVolume(BukkitWorld.normalizeWorldName(l0.getWorld().getName()), Math.min(x0, x1), Math.min(y0, y1),
Math.min(z0, z1), Math.max(x0, x1), Math.max(y0, y1), Math.max(z0, z1));
}
@Override
public final void setPlayerVisiblity(Player player, boolean is_visible) {
core.setPlayerVisiblity(player.getName(), is_visible);
}
@Override
public final boolean getPlayerVisbility(Player player) {
return core.getPlayerVisbility(player.getName());
}
@Override
public final void postPlayerMessageToWeb(Player player, String message) {
core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message);
}
@Override
public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) {
core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin);
}
@Override
public String getDynmapVersion() {
return version;
}
private static DynmapLocation toLoc(Location l) {
return new DynmapLocation(DynmapWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
private void registerPlayerLoginListener() {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent evt) {
DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp);
}
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent evt) {
DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp);
}
};
pm.registerEvents(pl, this);
}
private class BlockCheckHandler implements Runnable {
public void run() {
BlockToCheck btt;
while(blocks_to_check.isEmpty() != true) {
btt = blocks_to_check.pop();
Location loc = btt.loc;
World w = loc.getWorld();
if(!w.isChunkLoaded(loc.getBlockX()>>4, loc.getBlockZ()>>4))
continue;
int bt = w.getBlockTypeIdAt(loc);
/* Avoid stationary and moving water churn */
if(bt == 9) bt = 8;
if(btt.typeid == 9) btt.typeid = 8;
if((bt != btt.typeid) || (btt.data != w.getBlockAt(loc).getData())) {
String wn = BukkitWorld.normalizeWorldName(w.getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), btt.trigger);
}
}
blocks_to_check = null;
/* Kick next run, if one is needed */
startIfNeeded();
}
public void startIfNeeded() {
if((blocks_to_check == null) && (blocks_to_check_accum.isEmpty() == false)) { /* More pending? */
blocks_to_check = blocks_to_check_accum;
blocks_to_check_accum = new LinkedList<BlockToCheck>();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, this, 10);
}
}
}
private BlockCheckHandler btth = new BlockCheckHandler();
private void checkBlock(Block b, String trigger) {
BlockToCheck btt = new BlockToCheck();
btt.loc = b.getLocation();
btt.typeid = b.getTypeId();
btt.data = b.getData();
btt.trigger = trigger;
blocks_to_check_accum.add(btt); /* Add to accumulator */
btth.startIfNeeded();
}
private boolean onplace;
private boolean onbreak;
private boolean onblockform;
private boolean onblockfade;
private boolean onblockspread;
private boolean onblockfromto;
private boolean onblockphysics;
private boolean onleaves;
private boolean onburn;
private boolean onpiston;
private boolean onplayerjoin;
private boolean onplayermove;
private boolean ongeneratechunk;
private boolean onexplosion;
private boolean onstructuregrow;
private boolean onblockgrow;
private boolean onblockredstone;
private void registerEvents() {
// To trigger rendering.
onplace = core.isTrigger("blockplaced");
onbreak = core.isTrigger("blockbreak");
onleaves = core.isTrigger("leavesdecay");
onburn = core.isTrigger("blockburn");
onblockform = core.isTrigger("blockformed");
onblockfade = core.isTrigger("blockfaded");
onblockspread = core.isTrigger("blockspread");
onblockfromto = core.isTrigger("blockfromto");
onblockphysics = core.isTrigger("blockphysics");
onpiston = core.isTrigger("pistonmoved");
onblockfade = core.isTrigger("blockfaded");
onblockredstone = core.isTrigger("blockredstone");
if(onplace) {
Listener placelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockPlace(BlockPlaceEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace");
}
};
pm.registerEvents(placelistener, this);
}
if(onbreak) {
Listener breaklistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
if(b == null) return; /* Stupid mod workaround */
Location loc = b.getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak");
}
};
pm.registerEvents(breaklistener, this);
}
if(onleaves) {
Listener leaveslistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onleaves) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay");
}
}
};
pm.registerEvents(leaveslistener, this);
}
if(onburn) {
Listener burnlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onburn) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn");
}
}
};
pm.registerEvents(burnlistener, this);
}
if(onblockphysics) {
Listener physlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockPhysics(BlockPhysicsEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Material m = b.getType();
if(m == null) return;
switch(m) {
case STATIONARY_WATER:
case WATER:
case STATIONARY_LAVA:
case LAVA:
case GRAVEL:
case SAND:
checkBlock(b, "blockphysics");
break;
default:
break;
}
}
};
pm.registerEvents(physlistener, this);
}
if(onblockfromto) {
Listener fromtolistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockFromTo(BlockFromToEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Material m = b.getType();
if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null))
checkBlock(b, "blockfromto");
b = event.getToBlock();
m = b.getType();
if((m != Material.WOOD_PLATE) && (m != Material.STONE_PLATE) && (m != null))
checkBlock(b, "blockfromto");
}
};
pm.registerEvents(fromtolistener, this);
}
if(onpiston) {
Listener pistonlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try {
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
sscache.invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 2; i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
sscache.invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try {
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
sscache.invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 1+event.getLength(); i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
sscache.invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
};
pm.registerEvents(pistonlistener, this);
}
if(onblockspread) {
Listener spreadlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread");
}
};
pm.registerEvents(spreadlistener, this);
}
if(onblockform) {
Listener formlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform");
}
};
pm.registerEvents(formlistener, this);
}
if(onblockfade) {
Listener fadelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade");
}
};
pm.registerEvents(fadelistener, this);
}
onblockgrow = core.isTrigger("blockgrow");
if(onblockgrow) {
try {
Class.forName("org.bukkit.event.block.BlockGrowEvent");
Listener growTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockGrow(BlockGrowEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockgrow");
}
};
pm.registerEvents(growTrigger, this);
} catch (ClassNotFoundException cnfx) {
/* Pre-R5 - no grow event yet */
}
}
if(onblockredstone) {
Listener redstoneTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockRedstone(BlockRedstoneEvent event) {
Location loc = event.getBlock().getLocation();
String wn = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockredstone");
}
};
pm.registerEvents(redstoneTrigger, this);
}
/* Register player event trigger handlers */
Listener playerTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
if(onplayerjoin) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(BukkitWorld.normalizeWorldName(loc.getWorld().getName()), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playerjoin");
}
}
};
onplayerjoin = core.isTrigger("playerjoin");
onplayermove = core.isTrigger("playermove");
pm.registerEvents(playerTrigger, this);
if(onplayermove) {
Listener playermove = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(BukkitWorld.normalizeWorldName(loc.getWorld().getName()), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playermove");
}
};
pm.registerEvents(playermove, this);
Log.warning("playermove trigger enabled - this trigger can cause excessive tile updating: use with caution");
}
/* Register entity event triggers */
Listener entityTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onEntityExplode(EntityExplodeEvent event) {
Location loc = event.getLocation();
String wname = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<Block> blocks = event.blockList();
for(Block b: blocks) {
Location l = b.getLocation();
int x = l.getBlockX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = l.getBlockY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = l.getBlockZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onexplosion) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode");
}
}
};
onexplosion = core.isTrigger("explosion");
pm.registerEvents(entityTrigger, this);
/* Register world event triggers */
Listener worldTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onWorldLoad(WorldLoadEvent event) {
core.updateConfigHashcode();
BukkitWorld w = new BukkitWorld(event.getWorld());
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
@EventHandler(priority=EventPriority.MONITOR)
public void onWorldUnload(WorldUnloadEvent event) {
core.updateConfigHashcode();
DynmapWorld w = core.getWorld(BukkitWorld.normalizeWorldName(event.getWorld().getName()));
if(w != null)
core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w);
}
@EventHandler(priority=EventPriority.MONITOR)
public void onStructureGrow(StructureGrowEvent event) {
Location loc = event.getLocation();
String wname = BukkitWorld.normalizeWorldName(loc.getWorld().getName());
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<BlockState> blocks = event.getBlocks();
for(BlockState b: blocks) {
int x = b.getX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = b.getY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = b.getZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onstructuregrow) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "structuregrow");
}
}
};
onstructuregrow = core.isTrigger("structuregrow");
// To link configuration to real loaded worlds.
pm.registerEvents(worldTrigger, this);
ongeneratechunk = core.isTrigger("chunkgenerated");
if(ongeneratechunk) {
Listener chunkTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onChunkPopulate(ChunkPopulateEvent event) {
Chunk c = event.getChunk();
/* Touch extreme corners */
int x = c.getX() << 4;
int z = c.getZ() << 4;
mapManager.touchVolume(BukkitWorld.normalizeWorldName(event.getWorld().getName()), x, 0, z, x+15, 128, z+16, "chunkpopulate");
}
};
pm.registerEvents(chunkTrigger, this);
}
}
private boolean detectSpout() {
Plugin p = this.getServer().getPluginManager().getPlugin("Spout");
if(p != null) {
return p.isEnabled();
}
return false;
}
public boolean hasSpout() {
return has_spout;
}
@Override
public void assertPlayerInvisibility(String player, boolean is_invisible,
String plugin_id) {
core.assertPlayerInvisibility(player, is_invisible, plugin_id);
}
@Override
public void assertPlayerInvisibility(Player player, boolean is_invisible,
Plugin plugin) {
core.assertPlayerInvisibility(player.getName(), is_invisible, plugin.getDescription().getName());
}
@Override
public void assertPlayerVisibility(String player, boolean is_visible,
String plugin_id) {
core.assertPlayerVisibility(player, is_visible, plugin_id);
}
@Override
public void assertPlayerVisibility(Player player, boolean is_visible,
Plugin plugin) {
core.assertPlayerVisibility(player.getName(), is_visible, plugin.getDescription().getName());
}
@Override
public boolean setDisableChatToWebProcessing(boolean disable) {
return core.setDisableChatToWebProcessing(disable);
}
@Override
public boolean testIfPlayerVisibleToPlayer(String player, String player_to_see) {
return core.testIfPlayerVisibleToPlayer(player, player_to_see);
}
@Override
public boolean testIfPlayerInfoProtected() {
return core.testIfPlayerInfoProtected();
}
private void initMetrics() {
try {
metrics = new Metrics(this);
Metrics.Graph features = metrics.createGraph("Features Used");
features.addPlotter(new Metrics.Plotter("Internal Web Server") {
@Override
public int getValue() {
if (!core.configuration.getBoolean("disable-webserver", false))
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Spout") {
@Override
public int getValue() {
if(plugin.has_spout)
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Login Security") {
@Override
public int getValue() {
if(core.configuration.getBoolean("login-enabled", false))
return 1;
return 0;
}
});
features.addPlotter(new Metrics.Plotter("Player Info Protected") {
@Override
public int getValue() {
if(core.player_info_protected)
return 1;
return 0;
}
});
Metrics.Graph maps = metrics.createGraph("Map Data");
maps.addPlotter(new Metrics.Plotter("Worlds") {
@Override
public int getValue() {
if(core.mapManager != null)
return core.mapManager.getWorlds().size();
return 0;
}
});
maps.addPlotter(new Metrics.Plotter("Maps") {
@Override
public int getValue() {
int cnt = 0;
if(core.mapManager != null) {
for(DynmapWorld w :core.mapManager.getWorlds()) {
cnt += w.maps.size();
}
}
return cnt;
}
});
maps.addPlotter(new Metrics.Plotter("HD Maps") {
@Override
public int getValue() {
int cnt = 0;
if(core.mapManager != null) {
for(DynmapWorld w :core.mapManager.getWorlds()) {
for(MapType mt : w.maps) {
if(mt instanceof HDMap) {
cnt++;
}
}
}
}
return cnt;
}
});
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.